Compact Framework build and deployment time.

As anybody who has developed mobile applications with the compact framework (with VS2008 anyway) will know, the build and deployment time on even the smallest projects can be painfully long regardless of whether deploying to the device or the emulator.

Finding this has been a complete life saver (I was almost at the point of self harm waiting for builds!), and has slashed my build times by nearly a minute.

Make sure you take the time to read the full article so you know exactly what the implications are of disabling the ‘PlatformVerificationTask’ validation.

BindingContext – List controls that share a datasource

This one had me stumped for a while! If you have multiple list controls (combo’s etc) on the same form set to the same datasource, the default behaviour is for the controls to share the form’s BindingContext ,thus synchronising the current position. This means when you change list position in say ‘Combo A’, the selected index is also changed in ‘Combo B’.

To avoid this behaviour requires just one line of code applied to at least one of your controls.
Phew!


comboBox1.BindingContext = new BindingContext();

Custom Messagebox

9 times out of 10 the standard Windows Forms messagebox will do, but for those occasions it won’t, it’s pretty straight forward to design your own. I have an enum ‘MyMessageBoxButtons’ set up to accept ‘ok’ and ‘okCancel’, I have also set the OK button to fill the width of it’s parent panel if it is the only button to be displayed (this messagebox form is being displayed full screen in a mobile application), but you get the idea.


public partial class MyMessagebox : Form
{
    private static MyMessagebox messageBox;
    private static DialogResult messageboxResult;

    public MyMessagebox ()
    {
        InitializeComponent();
    }

    public static DialogResult Show(string messageText)
    {
        messageBox = new MyMessagebox ();
        messageBox.lbMessageboxMessage.Text = messageText;
        ShowButtons(messageBox, MyMessageBoxButtons.Ok);
        messageBox.ShowDialog();

        return messageboxResult;
    }

    public static DialogResult Show(string messageText, string messageCaption, MyMessageBoxButtons buttons)
    {
        messageBox = new myMessagebox();
        messageBox.lbMessageboxMessage.Text = messageText;
        messageBox.lbMessageboxCaption.Text = messageCaption;
        ShowButtons(messageBox, buttons);
        messageBox.ShowDialog();

        return messageboxResult;
    }
    
    private static void ShowButtons(MyMessageBox myMessageBox, MyMessageBoxButtons buttons)
    {
        myMessageBox.btnMessageboxOk.Enabled = true;
        myMessageBox.btnMessageboxOk.Visible = true;

        if (buttons != MyMessageBoxButtons.Ok)
        {
            myMessageBox.btnMessageboxCancel.Enabled = true;
            myMessageBox.btnMessageboxCancel.Visible = true;
        }
        else
        {
            myMessageBox.btnMessageboxOk.Width = myMessageBox.pnMessageboxDetail.Width;
        }
    }

    private void btnMessageboxOk_Click(object sender, EventArgs e)
    {
        messageboxResult = DialogResult.OK;
        messageBox.Close();
    }

    private void btnMessageboxCancel_Click(object sender, EventArgs e)
    {
        messageboxResult = DialogResult.Cancel;
        messageBox.Close();
    }        
}

Compact Framework – Increasing ScrollBar Width

The Datagrid in the Compact Framework has fixed 13 pixel wide/tall scrollbars but no way to resize them. Creating a control that inherits from Datagrid, overriding the size of the scrollbars would be one way to go, but it can be achieved without the need to do this by using reflection.


FieldInfo fieldInfo = dgBinDetail.GetType().GetField("m_sbVert", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);

((VScrollBar)fieldInfo.GetValue(dgBinDetail)).Width = 30; 

Remember to add the System.Reflection namespace to your list of using statements at the top of your class.

Using Reflection to open a form by name

Here is a quick example of how the System.Reflection namespace can be utilised to open form instances in a method that accepts the form name as a string. It also shows how you can pass across variables to forms with overloaded constructors.

It’s particularly useful when working with a main menu structure, such as I have in a current project loaded into a Treeview.


private void LoadNewForm(string formName)
{
    try
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        Type type = assembly.GetType(formName);

        //for this form I have an overloaded constructor, accepting a 'User' object
        ConstructorInfo ci = type.GetConstructor(new Type[1] { typeof(User) }); 
        object[] argVals = new object[] { CurrentUser };  //pass 'CurrentUser' variable to form constructor
        Form frm = (Form)ci.Invoke(argVals);

        frm.Show();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
} 

Selecting a region within an Image

The following code snippet shows you how to draw a selection rectangle over the top of an image and crop it accordingly.

You’ll need to add a Button and a PictureBox to a Form.

Click and drag over the PictureBox to select an area and when you’re ready, click the button and it will perform the crop and save the cropped selection as a new image. This follows on from my last post, have a play around with these methods and explore further!



using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private Point startPoint = new Point();  //the point(x,y) we start drawing our rectange
        private Rectangle myRectangle = new Rectangle();  //a rectangle

        public Form1()
        {
            InitializeComponent();
        }

        private void pictureBox1_MouseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Cross;
        }

        private void pictureBox1_MouseLeave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            startPoint.X = e.X;  //start point gets mouse coords
            startPoint.Y = e.Y;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)  //are we holding the left mouse button?
            {
                Point endPoint = new Point();  //the end point (x,y) of our rectangle
                Pen p = new Pen(Brushes.Red);  //a red pen
                Graphics g = pictureBox1.CreateGraphics();

                endPoint.X = e.X;  //end point gets mouse coords
                endPoint.Y = e.Y;

                pictureBox1.Refresh();  //stop flicker and actually display rectangle

                Size myRectSize = new Size(endPoint.X - startPoint.X, endPoint.Y - startPoint.Y);  //calculate the size of our rectangle
                myRectangle = new Rectangle(startPoint, myRectSize);  //assign new rectangle object
                g.DrawRectangle(p, myRectangle);  //and draw it!
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Image myImage = CropImage(pictureBox1.Image, myRectangle);  //crop the image
            myImage.Save("C:\\testPic.png", ImageFormat.Png);  //save it
        }

        private static Image CropImage(Image imageToCrop, Rectangle rect)
        {
            Bitmap b = new Bitmap(imageToCrop);  //new bmp
            Image croppedImage = b.Clone(rect, b.PixelFormat);  //copy a section of the original

            return croppedImage;
        }
    }
}

ISO 6346 – Shipping Container Codes

The following link explains how to perform check digit calculations for the validation of shipping container codes.

Below is some code based on the calculation steps shown in the above wikipedia page, it validates the check digit, so the complete container number (including check digit) should be entered in the textbox.

Just drop a button and textbox on a form and wire up the event handlers:

public Dictionary<char, int> AlphabetCodes = new Dictionary<char, int>();
public List<int> PowerOfMultipliers = new List<int>();

private void Form1_Load(object sender, EventArgs e)
{
    int step = 10;

    //populate dictionary...
    //...create a dictionary entry for all letters of the alphabet using their Ascii value to identify them.
    //if you subtract their ascii value by the value of the first alpha ascii character (in this case 65 for
    //uppercase 'A'), it will give you it's position in the alphabet, Add 10 to this and skip over all multiples
    //of 11 to give you ISO Owner Code numbers for each letter.
    for (int i = 65; i < 91; i++)
    {
        char c = (char)i;
        int pos = i - 65 + step;

        if (c == 'A' || c == 'K' || c == 'U')  //omit multiples of 11.
            step += 1;

        AlphabetCodes.Add(c, pos);  //add to dictionary
    }

    //populate list...
    //create a list of 10, 2^x numbers for calculation.  List should contain 1, 2, 4, 8, 16, 32, 64 etc..
    for (int i = 0; i < 10; i++)
    {
        int result = (int)Math.Pow(2, i);  //power of 2 calculation.
        PowerOfMultipliers.Add(result);  //add to list.
    }
}

private void button1_Click(object sender, EventArgs e)
{
    int total = 0;

    if (textBox1.Text.Length == 11)  //container numbers must be 11 characters long.
    {
        for (int i = 0; i < 10; i++)  //loop through the first 10 characters (the 11th is the check digit!).
        {
            if (AlphabetCodes.ContainsKey(textBox1.Text[i]))  //if the current character is in the dictionary.
                total += (AlphabetCodes[textBox1.Text[i]] * PowerOfMultipliers[i]);  //add it's value to the total.
            else
            {
                int serialNumber = (int)textBox1.Text[i] - 48;  //it must be a number, so get the number from the char ascii value.
                total += (serialNumber * PowerOfMultipliers[i]);  //and add it to the total.
            }
        }

        int checkDigit = (int)total % 11;  //this should give you the check digit

        //The check digit shouldn't equal 10 according to ISO best practice - BUT there are containers out there that do, so we'll
        //double check and set the check digit to 0...again according to ISO best practice.
        if (checkDigit == 10)
            checkDigit = 0;

        if (checkDigit != (int)textBox1.Text[10] - 48)  //check digit should equal the last character in the textbox.
            MessageBox.Show("Container Number NOT Valid");
        else
            MessageBox.Show("Container Number Valid");
    }
    else
    {
        MessageBox.Show("Container Number must be 11 characters in length");
    }
}