Why use LINQ

I was asked “Why I never used LINQ?”   I guess the real answer was, I never thought about it.  I really had no good reason for not using LINQ other it was new and unfamiliar.  When I finally used LINQ; I found I was getting rid of old habits and making code simpler and cleaner.

Example of code written in C#:

foreach (Charges charge in (ary))
{
if (charge.ChargeDescription.ToLower().Contains("total"))
{
ary.Remove(charge);
}
}

Code converted to LINQ:

var rslt = from Charges charge in ary where charge.ChargeDescription.ToLower().Contains("total") select charge;

while(rslt.Count() > 0)
{
Charges chargese = rslt.ElementAt(0);
ary.RemoveAt(ary.IndexOf(Chargese));
}

To this day I still use C# with a little LINQ to simplify my code.   I use LINQ for validations, quick look up and data manipulations.  It is definitely a change from what I used to do, but worth learning.  What I like about the above code is I had eliminated the nested if without complicating the code.

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.