SQL – string inside a string

Handy little nugget to check if a string exists within another string. Particularly useful if you’re working with a delimited string as I was, as it makes dealing with the delimiters irrelevant.


SELECT * FROM table
WHERE CHARINDEX('string1', 'string2') != 0

In this instance ‘string1’ is the string you’re searching for in ‘string2’. Obviously these could be substituted for columns in a table or whatever.

Advertisements

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;
        }
    }
}