Archive for '.net Programming'

Use Debug output window to monitor SQL generated by LINQ2SQL

Posted on 28. Jun, 2010 by naresh in .net Programming

In all the examples out there to see the SQL generated by a LINQ2SQL query console.out is used, but to monitor the SQL in a debug window we need to write a special text writer implementation

using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System;
namespace nj.Diagnostics
{
    /// <summary>
    /// Implements a <see cref="TextWriter"/> for writing information to the debugger log.
    /// </summary>
    /// <seealso cref="Debugger.Log"/>
    public class DebuggerWriter : TextWriter
    {
        private bool isOpen;
        private static UnicodeEncoding encoding;
        private readonly int level;
        private readonly string category;
 
        /// <summary>
        /// Initializes a new instance of the <see cref="DebuggerWriter"/> class.
        /// </summary>
        public DebuggerWriter()
            : this(0, Debugger.DefaultCategory)
        {
        }
 
        /// <summary>
        /// Initializes a new instance of the <see cref="DebuggerWriter"/> class with the specified level and category.
        /// </summary>
        /// <param name="level">A description of the importance of the messages.</param>
        /// <param name="category">The category of the messages.</param>
        public DebuggerWriter(int level, string category)
            : this(level, category, CultureInfo.CurrentCulture)
        {
        }
 
        /// <summary>
        /// Initializes a new instance of the <see cref="DebuggerWriter"/> class with the specified level, category and format provider.
        /// </summary>
        /// <param name="level">A description of the importance of the messages.</param>
        /// <param name="category">The category of the messages.</param>
        /// <param name="formatProvider">An <see cref="IFormatProvider"/> object that controls formatting.</param>
        public DebuggerWriter(int level, string category, IFormatProvider formatProvider)
            : base(formatProvider)
        {
            this.level = level;
            this.category = category;
            this.isOpen = true;
        }
 
        protected override void Dispose(bool disposing)
        {
            isOpen = false;
            base.Dispose(disposing);
        }
 
        public override void Write(char value)
        {
            if (!isOpen)
            {
                throw new ObjectDisposedException(null);
            }
            Debugger.Log(level, category, value.ToString());
        }
 
        public override void Write(string value)
        {
            if (!isOpen)
            {
                throw new ObjectDisposedException(null);
            }
            if (value != null)
            {
                Debugger.Log(level, category, value);
            }
        }
 
        public override void Write(char[] buffer, int index, int count)
        {
            if (!isOpen)
            {
                throw new ObjectDisposedException(null);
            }
            if (buffer == null || index < 0 || count < 0 || buffer.Length - index < count)
            {
                base.Write(buffer, index, count); // delegate throw exception to base class
            }
            Debugger.Log(level, category, new string(buffer, index, count));
        }
 
        public override Encoding Encoding
        {
            get
            {
                if (encoding == null)
                {
                    encoding = new UnicodeEncoding(false, false);
                }
                return encoding;
            }
        }
 
        public int Level
        {
            get { return level; }
        }
 
        public string Category
        {
            get { return category; }
        }
    }
}

The you can use

datacontext.log = new DebuggerWriter();

Tags: ,

Forms Authentication fails even when browser accepts cookies

Posted on 15. Jun, 2010 by naresh in .net Programming

While using Forms authentication in ASP.net

<forms name=".ASPXAUTH" loginUrl="login.aspx"
		  defaultUrl="Default.aspx" protection="All" timeout="30" path="/"
		  requireSSL="false" slidingExpiration="true"
		  cookieless="AutoDetect" domain=""
		  enableCrossAppRedirects="false">
		  <credentials passwordFormat="SHA1" />
</forms>

please remeber to set path = “/” or else the cookie based authentication fails, I am yet to figure out why this is happening but atleast this solves the problem.

Tags: ,

Cascade Delete with Linq2SQL

Posted on 22. Dec, 2009 by naresh in .net Programming, Blog

Consider this, you have Invoice and Invioce details in 2 tables and the details are referenced by InvoiceId, What happens to Invoice Details once you delete the invoice ?, In SQL atleast you can do cascade delete and also set the value to null, but most real life programs would want to delete the details, Linq2SQL by default tries to set a null value which in most cases fails, and there is no visual way to set this the only way to do this is to do some manual xml editing.
Right click and open the .dbml file with the XML Editor and then navigate to the table for which you want to do this, then look for the relation which references the parent table

<association Name="...." Member="...." ThisKey="...." OtherKey="...." Type="...." IsForeignKey="true" />

Now add DeleteOnNull=”true” to this association so this behaves as expected

<association Name="...." Member="...." ThisKey="...." OtherKey="...." Type="...." IsForeignKey="true" DeleteOnNull="true" />

Tags: ,

Use Linq with SQL CE

Posted on 20. Feb, 2009 by naresh in .net Programming

If you have tried this before you might have run into an error which says that the database is unsupported, Baisically LINQ2SQL in just language extension which converts into plain old SQL, so in theory it should work with any database, but SQL CE supports the same SQL as SQL Server This is not because Linq2SQL doesn’t support SQL CE but VS ORM designer doesn’t support that, but there is a way in which you can generate the Linq2SQL class ,
This is by using the “SQLMetal.exe”, this utility helps you in generating the Linq2SQL classes,
To do this simply create a batch file with the following command in the SQLCE database directory

"C:Program FilesMicrosoft SDKsWindowsv6.0abinsqlmetal.exe" /pluralize /dbml:DBMLNAME.dbml DATAFILENAME.sdf

This will create the DBML which you can then edit and manipulate in the VS ORM designer, and since the datacontext will not have connection string in it, while initializing the data context you can use something like

DataContext db = new DataContext (@"Data Source=DataBase.sdf");

Convert (Cast) between 2 custom classes

Posted on 19. Feb, 2009 by naresh in .net Programming

If you have ever wanted to convert (cast) between two custom classes, there is a simple way to do it,

public partial class xxxFinalClass
    {
        public static explicit operator xxxFinalClass(xxxOriginalClass data)
        {
            var temp = new xxxFinalClass();
            //do Conversion
            return temp;
        }
}

Now you can use like

xxxFinalClass newobj = (xxxFinalClass)oldobj;

Tags: ,

LINQ2SQL RAD with confidence

Posted on 24. Jan, 2009 by naresh in .net Programming

If you are like me who also does have to done some rapid prototyping and application development, you know how painstaking it is to do setup each wire for even a simple application to work, and you will be working so rapidly that you would have forgotten the column names you have entered in db few minutes ago, that fact aside you would still require a large prieces of code which would actually constitute the middle tier of application, but the problem is in RAD you do need a top notch middle tier which would cover all the aspects required, then what ? and add to that the fact that you are so used to working with objects that you have even forgotten how to retrive data just using code or you find the whole connection – adapter – dataset thing too outdated and too much work just to retrive one row from db.

Now we know what a middle teir is , its nothing but an ORM which maps objects to data along with addtional functions to manipulate that data, for this there exists good amount of code generators which based on your database would generate all code required which would constitute the core of middle tier, but i always found them to be too cumberome ( may be i am too lazy) , now may be some year and a half ago , i was working on a project which extensively used LINQ for queying objects, instead of writing functions for each thing, till then LINQ has become second nature, and i wonder how i used to to do this when LINQ was not around, same time i started looking web for LINQ and i saw something about DLINQ which is now reffered to as LINQ2SQL, LINQ2SQL does what we need to do the hard way, wire up. Just create a new LINQ2SQL class in your project and drag the tables from Server Explorer and voila , you have your midddle tier ready (well not exactly) , it creates classes for each of the table in the db along with associations for relations ,  (eg : If i have a students table in it creates a student class with each column in student as a property, and if you have something like SectionId in Student which links to the section table you can access the linked section by just using Student.Section). Everything becomes so simple from here on, atleast for RAD, It also creates functions for SPs,

The only problem i have with this till date is it works only with SQL Server (I have been able to get it working with SQLCE – If  this only worked with MySQL) and some things like serialization doesn’t happen the way i want it to , but anyway this is a tool which you have to use once to get know its usefullness.

Tags: ,

My latest Work on WPF

Posted on 02. Jan, 2009 by naresh in .net Programming, Personal

WPF has been here for quite a while now and i done some basic projects on wpf, but for the last two months i had the opportunity to completely work on WPF, not just WPF but also used Linq2SQL as the base for the complete application, wet my hands with ADO.net Entity Model and lot of work in Expression Blend,
The software was for KPCC and it an complete automation and information management system for them, I will not reveal much more, but a few screens which are not part of the NDA have been posted here,
KPCC
KPCC
KPCC

Tags: , ,

Implementing IEditableObject when using as a datasource

Posted on 16. Dec, 2008 by naresh in .net Programming

If have used a class as datasource , you would know that to provide proper validation and you would nees to implement a IEditableObject, but if you sont its really simple all you have to do is provide 3 functions , The code Mentioned below is a simple example and I think you can take it from there

 public class ReceiptPay : IEditableObject
        {
            public int FeeComponentId { get; set; }
            public string FeeComponent { get; set; }
            public decimal Amount { get; set; }
 
            private decimal amtbkp;
            private bool inTXN = false;
 
            public ReceiptPay(int FCId, string FC)
            {
                FeeComponentId = FCId;
                FeeComponent = FC;
            }
 
            #region IEditableObject Members
 
            public void BeginEdit()
            {
                if (!inTXN)
                {
                    amtbkp = Amount;
                    inTXN = true;
                }
            }
 
            public void CancelEdit()
            {
                if (inTXN)
                {
                    Amount = amtbkp;
                    inTXN = false;
                }
            }
 
            public void EndEdit()
            {
                inTXN = false;
            }
 
            #endregion
        }

Tags: ,

Serialize and Deserialize object as XML

Posted on 06. Dec, 2008 by naresh in .net Programming

If you ever wanted to store an in memory obejct, i think serialization is the best possible method to do so, so is when you want to transport an object, i was using this for a long time now, now i have modified it a bit with generics

using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
 
/// <summary>
/// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
/// </summary>
/// <param name="characters">Unicode Byte Array to be converted to String</param>
/// <returns>String converted from Unicode Byte Array</returns>
private static string UTF8ByteArrayToString(byte[] characters)
{
   UTF8Encoding encoding = new UTF8Encoding();
   string constructedString = encoding.GetString(characters);
   return (constructedString);
}
 
/// <summary>
/// Converts the String to UTF8 Byte array and is used in De serialization
/// </summary>
/// <param name="pXmlString"></param>
/// <returns></returns>
private static Byte[] StringToUTF8ByteArray(string pXmlString)
{
   UTF8Encoding encoding = new UTF8Encoding();
   byte[] byteArray = encoding.GetBytes(pXmlString);
   return byteArray;
}
 
/// <summary>
/// Serialize an object into an XML string
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializeObject<t>(T obj)
{
   try
   {
      string xmlString = null;
      MemoryStream memoryStream = new MemoryStream();
      XmlSerializer xs = new XmlSerializer(typeof(T));
      XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
      xs.Serialize(xmlTextWriter, obj);
      memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
      xmlString = UTF8ByteArrayToString(memoryStream.ToArray());      return xmlString;
   }
   catch
   {
      return string.Empty;
   }
}
 
/// <summary>
/// Reconstruct an object from an XML string
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static T DeserializeObject</t><t>(string xml)
{
   XmlSerializer xs = new XmlSerializer(typeof(T));
   MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
   XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
   return (T)xs.Deserialize(memoryStream);
}
</t>

Tags: ,

Vista Style Command link

Posted on 28. Nov, 2008 by naresh in .net Programming

Have you obeserved the new taskdialog in vista, (May I am the last one to write about this), but sure looks great, and it is easy to implement,

thre are lots of versions out there but like this the most, so here is the code

using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
 
namespace CommandLink
{
    [ToolboxBitmap(typeof(Button))]
    [DefaultEvent("Click")]
    public partial class CommandLink : Button
    {
        public CommandLink()
        {
            InitializeComponent();
            this.DoubleBuffered = true; //Smooth redrawing
            this.ImageVerticalAlign = VerticalAlign.Middle; //Set Default
        }
 
        #region Fields---------------------------------
        public enum State
        {
            Normal,
            Hover,
            Pushed,
            Disabled
        }
 
        public enum VerticalAlign
        {
            Top,
            Middle,
            Bottom
        }
 
        private State state = State.Normal;
        private int offset = 0;
 
        private string headerText = "Header Text";
        private string descriptionText = "Description";
 
        private Bitmap image;
        private Bitmap grayImage;
        private Size imageSize = new Size(24, 24);
        private VerticalAlign imageAlign = VerticalAlign.Top;
        private VerticalAlign textAlign = VerticalAlign.Middle;
 
        private Font descriptFont;
 
        #endregion
 
        #region Properties----------------------------
 
        ///
        /// Gets or sets the string associated with the Header text of the control.
        ///
        [Category("Command Appearance"),
         Browsable(true),
         DefaultValue("Header Text")]
        public string HeaderText
        {
            get
            {
                return headerText;
            }
            set
            {
                headerText = value;
                this.Refresh();
            }
        }
 
        ///
        /// Gets or sets the string associated with the Description text of the control.
        ///
        [Category("Command Appearance"),
         Browsable(true),
         DefaultValue("Description")]
        public string DescriptionText
        {
            get
            {
                return descriptionText;
            }
            set
            {
                descriptionText = value;
                this.Refresh();
            }
        }
 
        ///
        /// Gets or sets the left-hand Bitmap object of the control.
        ///
        [Category("Command Appearance"),
         Browsable(true),
         DefaultValue(null)]
        public Bitmap Image
        {
            get
            {
                return image;
            }
            set
            {
                //Clean up
                if (image != null)
                    image.Dispose();
 
                if (grayImage != null)
                    grayImage.Dispose();
 
                image = value;
                if (image != null)
                    grayImage = GetGrayscale(image); //generate image for disabled state
                else
                    grayImage = null;
                this.Refresh();
            }
        }
 
        ///
        /// Gets or sets the target size of the Image object.
        ///
        [Category("Command Appearance"),
         Browsable(true),
         DefaultValue(typeof(Size), "24,24")]
        public Size ImageScalingSize
        {
            get
            {
                return imageSize;
            }
            set
            {
                imageSize = value;
                this.Refresh();
            }
        }
 
        ///
        /// Gets or sets the alignment of the Image object along the vertical axis.
        ///
        [Category("Command Appearance"),
         Browsable(true),
         DefaultValue(VerticalAlign.Top)]
        public VerticalAlign ImageVerticalAlign
        {
            get
            {
                return imageAlign;
            }
            set
            {
                imageAlign = value;
                this.Refresh();
            }
        }
 
        ///
        /// Gets or sets the alignment of the displayed text along the vertical axis.
        ///
        [Category("Command Appearance"),
         Browsable(true),
         DefaultValue(VerticalAlign.Middle)]
        public VerticalAlign TextVerticalAlign
        {
            get
            {
                return textAlign;
            }
            set
            {
                textAlign = value;
                this.Refresh();
            }
        }
 
        ///
        /// Gets or sets the Font object that will be applied to the header and description strings.
        ///
        [Category("Command Appearance")]
        public override Font Font
        {
            get
            {
                return base.Font;
            }
            set
            {
                base.Font = value;
 
                //Clean up
                if (descriptFont != null)
                    descriptFont.Dispose();
 
                //Update the description font, which is the same just 3 sizes smaller
                descriptFont = new Font(this.Font.FontFamily, this.Font.Size - 3);
            }
        }
 
        ///
        /// Gets a string representation of the header and description strings.
        ///
        [Browsable(false)]
        public override string Text
        {
            get
            {
                return this.HeaderText + ": " + this.DescriptionText;
            }
        }
 
        #endregion
 
        #region Events-----------------------------------
        protected override void OnPaint(PaintEventArgs e)
        {
            DrawBackground(e.Graphics);
 
            if (this.Focused &amp;&amp; state == State.Normal)
                DrawHighlight(e.Graphics);
 
            switch (state)
            {
                case State.Normal:
                    DrawNormalState(e.Graphics);
                    break;
                case State.Hover:
                    DrawHoverState(e.Graphics);
                    break;
                case State.Pushed:
                    DrawPushedState(e.Graphics);
                    break;
                case State.Disabled:
                    DrawNormalState(e.Graphics); //DrawForeground takes care of drawing the disabled state
                    break;
                default:
                    break;
            }
        }
 
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
                this.PerformClick();
 
            base.OnKeyPress(e);
        }
 
        protected override void OnGotFocus(EventArgs e)
        {
            this.Refresh();
            base.OnGotFocus(e);
        }
 
        protected override void OnLostFocus(EventArgs e)
        {
            this.Refresh();
            base.OnLostFocus(e);
        }
 
        protected override void OnMouseEnter(EventArgs e)
        {
            if (this.Enabled)
                state = State.Hover;
            this.Refresh();
 
            base.OnMouseEnter(e);
        }
 
        protected override void OnMouseLeave(EventArgs e)
        {
            if (this.Enabled)
                state = State.Normal;
            this.Refresh();
 
            base.OnMouseLeave(e);
        }
 
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (this.Enabled)
                state = State.Pushed;
            this.Refresh();
 
            base.OnMouseDown(e);
        }
 
        protected override void OnMouseUp(MouseEventArgs e)
        {
            if (this.Enabled)
            {
                if (this.RectangleToScreen(this.ClientRectangle).Contains(Cursor.Position))
                    state = State.Hover;
                else
                    state = State.Normal;
            }
            this.Refresh();
 
            base.OnMouseUp(e);
        }
 
        protected override void OnEnabledChanged(EventArgs e)
        {
            if (this.Enabled)
                state = State.Normal;
            else
                state = State.Disabled;
 
            this.Refresh();
 
            base.OnEnabledChanged(e);
        }
 
        protected override void Dispose(bool disposing)
        {
            if (disposing &amp;&amp; components != null)
            {
                image.Dispose();
                grayImage.Dispose();
                descriptFont.Dispose();
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        #endregion
 
        #region Drawing Methods-------------------------
 
        //Draws the light-blue rectangle around the button when it is focused (by Tab for example)
        private void DrawHighlight(Graphics g)
        {
            //The outline is drawn inside the button
            GraphicsPath innerRegion = RoundedRect(this.Width - 3, this.Height - 3, 3);
 
            //----Shift the inner region inwards
            Matrix translate = new Matrix();
            translate.Translate(1, 1);
            innerRegion.Transform(translate);
            translate.Dispose();
            //-----
 
            Pen inlinePen = new Pen(Color.FromArgb(192, 233, 243)); //Light-blue
 
            g.SmoothingMode = SmoothingMode.AntiAlias;
 
            g.DrawPath(inlinePen, innerRegion);
 
            //Clean-up
            inlinePen.Dispose();
            innerRegion.Dispose();
        }
 
        //Draws the button when the mouse is over it
        private void DrawHoverState(Graphics g)
        {
            GraphicsPath outerRegion = RoundedRect(this.Width - 1, this.Height - 1, 3);
            GraphicsPath innerRegion = RoundedRect(this.Width - 3, this.Height - 3, 2);
            //----Shift the inner region inwards
            Matrix translate = new Matrix();
            translate.Translate(1, 1);
            innerRegion.Transform(translate);
            translate.Dispose();
            //-----
            Rectangle backgroundRect = new Rectangle(1, 1, this.Width - 2, (int)(this.Height * 0.75f) - 2);
 
            Pen outlinePen = new Pen(Color.FromArgb(189, 189, 189)); //SystemColors.ControlDark
            Pen inlinePen = new Pen(Color.FromArgb(245, 255, 255, 255)); //Slightly transparent white
 
            //Gradient brush for the background, goes from white to transparent 75% of the way down
            LinearGradientBrush backBrush = new LinearGradientBrush(new Point(0, 0), new Point(0, backgroundRect.Height), Color.White, Color.Transparent);
            backBrush.WrapMode = WrapMode.TileFlipX; //keeps the gradient smooth incase of the glitch where there's an extra gradient line
 
            g.SmoothingMode = SmoothingMode.AntiAlias;
 
            g.FillRectangle(backBrush, backgroundRect);
            g.DrawPath(inlinePen, innerRegion);
            g.DrawPath(outlinePen, outerRegion);
 
            //Text/Image
            offset = 0; //Text/Image doesn't move
            DrawForeground(g);
 
            //Clean up
            outlinePen.Dispose();
            inlinePen.Dispose();
            outerRegion.Dispose();
            innerRegion.Dispose();
        }
 
        //Draws the button when it's clicked down
        private void DrawPushedState(Graphics g)
        {
            GraphicsPath outerRegion = RoundedRect(this.Width - 1, this.Height - 1, 3);
            GraphicsPath innerRegion = RoundedRect(this.Width - 3, this.Height - 3, 2);
            //----Shift the inner region inwards
            Matrix translate = new Matrix();
            translate.Translate(1, 1);
            innerRegion.Transform(translate);
            translate.Dispose();
            //-----
            Rectangle backgroundRect = new Rectangle(1, 1, this.Width - 3, this.Height - 3);
 
            Pen outlinePen = new Pen(Color.FromArgb(167, 167, 167)); //Outline is darker than normal
            Pen inlinePen = new Pen(Color.FromArgb(227, 227, 227)); //Darker white
            SolidBrush backBrush = new SolidBrush(Color.FromArgb(234, 234, 234)); //SystemColors.ControlLight
 
            g.SmoothingMode = SmoothingMode.AntiAlias;
 
            g.FillRectangle(backBrush, backgroundRect);
            g.DrawPath(inlinePen, innerRegion);
            g.DrawPath(outlinePen, outerRegion);
 
            //Text/Image
            offset = 1; //moves image inwards 1 pixel (x and y) to create the illusion that the button was pushed
            DrawForeground(g);
 
            //Clean up
            outlinePen.Dispose();
            inlinePen.Dispose();
            outerRegion.Dispose();
            innerRegion.Dispose();
        }
 
        //Draws the button in it's regular state
        private void DrawNormalState(Graphics g)
        {
            //Nothing needs to be drawn but the text and image
 
            //Text/Image
            offset = 0; //Text/Image doesn't move
            DrawForeground(g);
        }
 
        //Draws Text and Image
        private void DrawForeground(Graphics g)
        {
            //Make sure drawing is of good quality
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
 
            //Coordinates-------------------------------
            int imageLeft = 9;
            int imageTop = 0;
            int textLeft = 20;
            if (image != null)
                textLeft = imageLeft + imageSize.Width + 5; //adjust the text left coordinate to accomodate the image
            //
 
            //Text Layout-------------------------------
            string wrappedDescriptText = WordWrap(descriptionText, descriptFont, this.Width - (textLeft + offset) - 5);
 
            //Gets the width/height of the text once it's drawn out
            SizeF headerLayout = g.MeasureString(headerText, this.Font);
            SizeF descriptLayout = g.MeasureString(wrappedDescriptText, descriptFont);
 
            //Merge the two sizes into one big rectangle
            Rectangle totalRect = new Rectangle(0, 0, (int)Math.Max(headerLayout.Width, descriptLayout.Width), (int)(headerLayout.Height + descriptLayout.Height) - 4);
 
            //Align the text rectangle
            totalRect.X = textLeft;
 
            switch (textAlign)
            {
                case VerticalAlign.Top:
                    totalRect.Y = 4;
                    break;
                case VerticalAlign.Middle:
                    totalRect.Y = (this.Height / 2) - (totalRect.Height / 2);
                    break;
                case VerticalAlign.Bottom:
                    totalRect.Y = this.Height - totalRect.Height;
                    break;
                default:
                    break;
            }
            //---------------------------------------------------
 
            //Align the top of the image---------------------
            if (image != null)
            {
                switch (imageAlign)
                {
                    case VerticalAlign.Top:
                        imageTop = 4;
                        break;
                    case VerticalAlign.Middle:
                        imageTop = (imageSize.Height / 2);
                        break;
                    case VerticalAlign.Bottom:
                        imageTop = this.Height - imageSize.Height;
                        break;
                    default:
                        break;
                }
            }
            //-----------------------------------------------
 
            //Brushes--------------------------------
            // Determine text color depending on whether the control is enabled or not
            Color textColor = this.ForeColor;
            if (!this.Enabled)
                textColor = SystemColors.GrayText;
 
            SolidBrush textBrush = new SolidBrush(textColor);
            //------------------------------------------
 
            g.DrawString(headerText, this.Font, textBrush, totalRect.Left + offset, totalRect.Top + offset);
            g.DrawString(wrappedDescriptText,
                         descriptFont,
                         textBrush,
                         totalRect.Left + 1 + offset,
                         totalRect.Bottom - (int)descriptLayout.Height + offset);
            //Note: the + 1 in "totalRect.Left + 1 + offset" compensates for GDI+ inconsistency
 
            if (image != null)
            {
                if (this.Enabled)
                    g.DrawImage(image, new Rectangle(imageLeft + offset, imageTop + offset, imageSize.Width, imageSize.Height));
                else
                {
                    //make sure there is a gray-image
                    if (grayImage == null)
                        grayImage = GetGrayscale(image); //generate grayscale now
 
                    g.DrawImage(grayImage, new Rectangle(imageLeft + offset, imageTop + offset, imageSize.Width, imageSize.Height));
                }
            }
 
            //Clean-up
            textBrush.Dispose();
        }
 
        //Draws the solid background of the control
        private void DrawBackground(Graphics g)
        {
            SolidBrush backBrush = new SolidBrush(this.BackColor);
            g.FillRectangle(backBrush, this.DisplayRectangle);
            backBrush.Dispose();
        }
        #endregion
 
        #region Helper Methods--------------------------
        private static GraphicsPath RoundedRect(int width, int height, int radius)
        {
            RectangleF baseRect = new RectangleF(0, 0, width, height);
            float diameter = radius * 2.0f;
            SizeF sizeF = new SizeF(diameter, diameter);
            RectangleF arc = new RectangleF(baseRect.Location, sizeF);
            GraphicsPath path = new GraphicsPath();
 
            // top left arc
            path.AddArc(arc, 180, 90);
 
            // top right arc
            arc.X = baseRect.Right - diameter;
            path.AddArc(arc, 270, 90);
 
            // bottom right arc
            arc.Y = baseRect.Bottom - diameter;
            path.AddArc(arc, 0, 90);
 
            // bottom left arc
            arc.X = baseRect.Left;
            path.AddArc(arc, 90, 90);
 
            path.CloseFigure();
            return path;
        }
 
        private static Bitmap GetGrayscale(Image original)
        {
            //Set up the drawing surface
            Bitmap grayscale = new Bitmap(original.Width, original.Height);
            Graphics g = Graphics.FromImage(grayscale);
 
            //Grayscale Color Matrix
            ColorMatrix colorMatrix = new ColorMatrix(new float[][]
                                                      {
                                                         new float[] {0.3f, 0.3f, 0.3f, 0, 0},
                                                         new float[] {0.59f, 0.59f, 0.59f, 0, 0},
                                                         new float[] {0.11f, 0.11f, 0.11f, 0, 0},
                                                         new float[] {0, 0, 0, 1, 0},
                                                         new float[] {0, 0, 0, 0, 1}
                                                      });
 
            //Create attributes
            ImageAttributes att = new ImageAttributes();
            att.SetColorMatrix(colorMatrix);
 
            //Draw the image with the new attributes
            g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, att);
 
            //Clean up
            g.Dispose();
 
            return grayscale;
        }
 
        private static string WordWrap(string originalString, Font font, int targetWidth)
        {
            string[] words = originalString.Split(' ');
 
            string wrappedString = words[0];
 
            //Add one word at a time, making sure it doesn't go over
            for (int i = 1; i &lt; words.Length; i++)
            {
                //Use TextRenderer since it has a static measure function
                if (TextRenderer.MeasureText(wrappedString + " " + words[i], font).Width &lt;= targetWidth)
                    wrappedString += " " + words[i]; //next word fits on the same line
                else
                    wrappedString += Environment.NewLine + words[i]; //start it on the next line
            }
 
            return wrappedString;
        }
 
        public void PerformClick()
        {
            this.OnClick(null);
        }
        #endregion
    }
}

I will also post for the complete task dialog in my next post.
* I did not write this code, credit to whomever who did this

Tags: ,