Code Simplified

Working with junior developers through out my years, I have seen some funky and fun ways of coding.  The three styles I have seen the most are the following.    I have come up with BEFORE and AFTER examples.  Now the AFTER is just my opinion on how the code should be rewritten, but is not necessary the only way.

BEFORE

           String strDelim = “;,”;
           Char[] delimiter = strDelim.ToCharArray();

           String[] emails = to.Split(delimiter);

AFTER

           Char[] delimiter = new[] { ‘;’, ‘,’ };

           

String[] emails = to.Split(delimiter);


EXPLANATION
I prefer this rewrite because it is smaller in number of lines and it is less instructions to the compiler.  Although this example was 3 lines rewritten as two and seems small; in a large program, it adds up if done enough. 

BEFORE
           String answer = “”;
           if(rdButton.Checked == true)
           {
                      answer = “Test 1”;
           }
           else
           {
                      answer = “Test 2”;
           }

AFTER
           String answer = rdButton.Checked ? “Test 1” : “Test 2”;

EXPLANATION
This rewrite uses an old C style called Immediate IF.   This takes your simple if block statement and breaks it down to one line.  The other change is the == true was removed. Since the rdButton.Checked already returns true / false, it is not required to conduct an additional check.

BEFORE
           String rpt = “Error at Line: ” + lineNumber + “n” + “Description: ” + 

AFTER
           String rpt = String.Format(“Error at Line: {0}nDescription: {1}”, lineNumber, Description);

EXPLANATION
This change uses the String.Format command to take a pre-written string and inject the variables into their appropriate position within the string.  This is probably more of a preference of mine, but I think it looks cleaner.   The code does run faster when you are not adding string after string together, but with today’s processors and memory capabilities the savings is probably not much.  The main benefit is you can define these pre-written strings once and used them in this manner multiple times throughout the same piece of code. It will look cleaner overall.

Using LINQ to find a control in the ControlCollection

While writing a windows application in C#, I realized that there was no find control method in the ControlCollection class. This was a problem as it would create a significant amount of code to find a control. Well it turns out you can do it using LINQ. I had found a blog that I was able to implement the code fairly cleanly. The original code limited me a little bit, but with a very minor modification I came up with this code.

Original Blog: linq-the-uber-findcontrol

public static class PageExtensions
{
public static IEnumerable All(this Control.ControlCollection controls)
{
foreach (Control control in controls)
{
if (control.HasChildren)
{
foreach (Control child in control.Controls.All())
{
yield return child;
}
}
else
{
yield return control;
}
}
}
}

private Control GetControlByName(string name)
{
Control firstEmpty = this.Controls.All()
.OfType()
.Where(tb => tb.Name.Trim().Equals(name))
.FirstOrDefault();
return firstEmpty;
}

DotNet Windows Form Image Transparency

Recently during a project I had a need to overlay an image on a windows form in order to indicate a status of inability.  This image had a semi-transparency quality as well as a full transparency background.  To my dismay, the semi-transparency rendered in full color and the full transparency background seemed to inherit the parent form, but not show the controls behind it as one would expect.

After sometime of researching the issue, I came to a determination that what I was trying to do could only be done in web development (HTML).  From my research I had assembled some ideas in how to make transparencies work.   I took ideas from several sources and came up with the following.

Step By Step ( see Sample Code )

1. Create a class that extends System.Windows.Forms.Control
2. Place code from sample cod
3. Compile Project
4. Add new control to the Form ( remember this is for a windows application )
5. Set Background Image

Sample Code


protected override CreateParams CreateParams
{
     // Make window transparent
     get
     {
          CreateParams cp = base.CreateParams;
          cp.ExStyle |= 0x20;  // WS_EX_TRANSPARENT return cp;
     }
}

protected override void OnPaintBackground(PaintEventArgs pevent)
{
// Do not paint the background
}

protected override void OnPaint(PaintEventArgs e)
{ 
     // Paint background image 
     if (BackgroundImage != null)
     {
          Bitmap bmp = new Bitmap(BackgroundImage);
          bmp.MakeTransparent(Color.White);
          e.Graphics.DrawImage(bmp, 0, 0, Width, Height);
     }
}

Note:  When you overlay an image – even transparent, you may see the controls behind, but you will not be able to access them.  This is true in both web and windows development.

Javascript equalsIgnoreCase Function

This week’s code sample is JAVASCRIPT based. I found this while researching user validation routines. This function is a javascript version of a common Java function. We have replicated the calling syntax as a java programmer would expect to use it by effectively appending it as a method of the javascript String Object.

For more great scripts: http://www.apriori-it.co.uk

Important Note: Works with IE and FireFox

//The first line assigns the MatchIgnoreCase function as 
//an equalsIgnoreCase method of the String object 

String.prototype.equalsIgnoreCase = MatchIgnoreCase; 

function MatchIgnoreCase(strTerm, strToSearch) 
{ 
	strToSearch = strToSearch.toLowerCase(); 
	strTerm = strTerm.toLowerCase(); 
	if(strToSearch==strTerm) 
	{ 
		return true; 
	} else { 
		return false; 
	} 
}