Archive for csharp

Dilaogs with timed self destruct

My colleague came to me today with the following question: “How can I inform the user using a MessageBox in a separate thread while the main thread continues working ?”

Since I did not found a direct answer hidden in some corner in my brain, we took a dive in internet together, found some golden fish, and cooked the following recipe:

First we create a minimalistic Form with the needed functionality for timed self destruct :

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace hacks.wordpress.com
{
    public class TimedDialog : System.Windows.Forms.Form
    {
        public TimedDialog()
        {
            this.InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "I am a mission impossible message";
        }

        public void ShowTimedDialog(int time)
        {
            //{{ Setup and start the timer
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = time;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Enabled = true;
            //}}

            base.ShowDialog();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Now we use the new created dialog in our main application

public class MainApplication
{
    public static void Main(string[] args)
    {
       Console.WriteLine("1");
       Thread mainThread = new Thread(new ThreadStart(MainApplication.startTimedDialog));
       mainThread.Start();
       Console.WriteLine("2");
       Console.WriteLine("3");

    }
    private static startTimedDialog()
    {
        TimedDialog timedDialog = new TimedDialog();
        timedDialog.ShowTimedDialog(5000);
    }
}

Leave a Comment

The most useful short keys for VisualStudio C#

This list is sticked right on my monitor. It contains the most useful short keys I really use frequently to increase productivity in VisualStudio C#

Code Generation  
Ctrl + R + E generates getters and setters for a property
Shift + Alt + F10 adds a using statement
Code Navigation  
Ctrl + M + M toggles any tag :method, region, class etc. 🙂 (my favourite)
Shift + F12 finds all references to a avariable
F12 goes to variable definition
Text Editing  
Ctrl + L cuts a line

Those short keys are in available in my newly created the reference card : MS Visual Studio C# Reference Card

Comments (1)

LockImage project added to google code

Finally I got my open source project LockImage started on google code. Read more and download it form LockImage

Leave a Comment

Master c# enum with System.Enum.Parse

[This post has been updated! please go to the end of it to check the update]

We start with a typical enum in C#:

public enum WEEK_DAY : byte
{
 MONDAY    = 0x01,
 TUESDAY   = 0x02,
 WEDNESDAY = 0x03,
 THURSDAY  = 0x04,
 FRIDAY    = 0x05,
 SATURDAY  = 0x06,
 SUNDAY    = 0x07
}

With System.Enum.Parse you can do the following:

/*
 * Converting a numeric value to an enum name
 */
byte numericValue = 0x04;
WEEK_DAY dayOfTheWeek = (WEEK_DAY)
							(
								System.Enum.Parse
								(
								typeof(WEEK_DAY),
								numericValue.ToString()
								)
							);

/*
 * Freindly printing of enum names
 */
// this will print "THURSDAY"
Console.WriteLine(dayOfTheWeek.ToString());

Update:I found today in this post a simpler way to format and print out an enumeration entry:

            Console.WriteLine(WEEK_DAY.FRIDAY.ToString("G")); // Friday  (String)
            Console.WriteLine(WEEK_DAY.FRIDAY.ToString("F")); // Friday  (String)
            Console.WriteLine(WEEK_DAY.FRIDAY.ToString("X")); // 05      (Hex)
            Console.WriteLine(WEEK_DAY.FRIDAY.ToString("D")); // 5       (Decimal)
I found it in this

Leave a Comment

Work easly with bit masks in c#

Lately I got confronted with inserting and reading selections from a byte value using bit masks. I wrote the following class that makes it easier to deal with such operations for bytes. It can be extended for other types (short, int,..)

using System;
using System.Collections.Generic;
using System.Text;

namespace Sandbox
{
    public class ByteBitVector
    {
        private byte value;

        public byte Value
        {
            get { return this.value; }
            set { this.value = value; }
        }

        public ByteBitVector(byte value)
        {
            this.value = value;
        }

        public ByteBitVector()
        {
            this.value = 0x0000;
        }

        public void InsertSection(byte section, String mask)
        {
            this.checkMask(mask);
            Console.WriteLine("mask= " + mask);

            Console.WriteLine("this.getShift(mask)= " + this.getShift(mask));
            Console.WriteLine("section= " + Convert.ToString(section,2));

            this.value += (byte)(section << this.getShift(mask));
        }

        public byte GetSection(String mask)
        {
            this.checkMask(mask);
            /*
 		 * String mask         = "-xx----"
 		 * String maskAsBitStr = "0110000"
 		*  Byte   maskAsByte   = (byte) 0110000 = 0x30
 		*/ 

            String maskAsBitStr = String.Empty;
            maskAsBitStr = mask.Replace('-', '0');
            maskAsBitStr = maskAsBitStr.Replace('x', '1');
            byte maskAsByte = Convert.ToByte(maskAsBitStr, 2);

            return (byte)(((this.value) & maskAsByte) >> this.getShift(mask));
        }

        private void checkMask(String mask)
        {
            if (8 != mask.Length)
            {
                throw new Exception("The mask length must be exactly 8!");
            }
            foreach (char c  in mask)
         {
                if ((c != '-') && (c != 'x'))
                {
                    throw new Exception("Wrong format for mask! Accepted format: ---xx---");
                }
         }
        }

        private byte getShift(String mask)
        {
            return (byte)((8-1) - mask.LastIndexOf('x'));
        }

        public void Main(String arg[])
 	{

             ByteBitVector v = new ByteBitVector();
 	     String a_mask = "xx------";
 	     String b_mask = "--xxxx--";
 	     String c_mask = "------x-";
 	     String d_mask = "-------x";

             /* sections to insert and read */
	     byte a = 0x3; //00000011
 	     byte b = 0XB; //00001011
 	     byte c = 0x1; //00000001
 	     byte d = 0x1; //00000001

             /*  inserting sections  */
 	    			         // v.Value = 0000 0000
 	     v.InsertSection(a, a_mask); // v.Value = 1100 0000
 	     v.InsertSection(b, b_mask); // v.Value = 1110 1100
 	     v.InsertSection(c, c_mask); // v.Value = 1110 1110
 	     v.InsertSection(d, d_mask); // v.Value = 1110 1111

            /*  reading sections  */
 	     Console.WriteLine("v.GetSection(a_mask) = " + Convert.ToString(v.GetSection(a_mask), 2)); //00000011 = a
 	     Console.WriteLine("v.GetSection(b_mask) = " + Convert.ToString(v.GetSection(b_mask), 2)); //00001011 = b
 	     Console.WriteLine("v.GetSection(c_mask) = " + Convert.ToString(v.GetSection(c_mask), 2)); //00000001 = c
 	     Console.WriteLine("v.GetSection(d_mask) = " + Convert.ToString(v.GetSection(d_mask), 2)); //00000001 = d

	}
    }
}

Comments (2)