A Binary Look at System.IConvertible Derivations

Welcome to another article for the Extension Me series. This series focuses on various uses of the .NET Framework feature: Extension Methods. This entry will focus on extending System.IConvertible objects to retrieve its binary form as a String. Basic knowledge of programming in C# and creating extension methods is assumed.

Converting from one data type to another (Casting) is quite commonplace in computer programming. In C# this can be done in various ways:

  1. Implicit Casting
  2. Explicit Casting
  3. Using System.Convert

The list above will be described in the following three sections.

Implicit Casting

This is one of the most basic forms. When one variable of one data type is assigned to another with a different yet compatible data type, they can be implicitly cast. Here is an example:

long lngValue = 9223372036854775806L;
int intValue = 2147483646;
lngValue = intValue;

Above is an example of implicit casting. A long (Int64) variable occupies 64 bits (or 8 bytes, or 16 nibbles). An int (Int32) variable occupies 32 bits (or 4 bytes, or 8 nibbles). Since Int32 memory space can easily fit within Int64 memory space (as depicted below), an implicit conversion can be applied from Int32 to Int64. An explicit cast must be performed when converting the opposite direction (Int64 to Int32) where truncation will occur.

A visual comparison between Int32 and Int64 memory space
Above is a visual comparison between Int32 and Int64 memory space (Int32 to Int64 cast).

Explicit Casting

This is another basic form of casting. Here is an example:

long lngValue = 2147483646L;
int intValue = 0;
intValue = (int)lngValue;

Above is an example of explicit casting. Since a 64-bit variable does not completely fit within a 32-bit memory space, we must use explicit casting while accepting the fact truncation may occur (possibly loss of data). Truncation is depicted below (an Int64 to Int32 cast):

an Int64 to Int32 cast

Using System.Convert

System.Convert contains many methods meant to convert from one base data type to another. There are methods such as ToInt64, ToByte, ToDateTime, etc. Here is an example:

int intValue = 2147483646;
long value = Convert.ToInt64(intValue);

Above is an example using the ToInt64 method of System.Convert. The method accepts the Int32 value we initialized and converts it to Int64. This particular method simply wraps an explicit cast: (long)value. Others are dependent on an object’s implementation of the System.IConvertible interface as shown in the implementation of the Convert.ToInt64(object) method:

public static long ToInt64(object value)
{
    if (value != null)
    {
        return ((IConvertible) value).ToInt64(null);
    }
    return 0L;
}

Above is the implementation of Convert.ToInt64(object). The ToInt64 method of value is called after converting it to System.IConvertible proving its dependence on System.IConvertible objects.

The Extension

Now that we have gone over the basics of casting and the dependency on System.IConvertible objects, the extension method can be created. Below is the implementation:

public static class IConvertibleToBinaryString
{
   public static string ToBinaryString(this IConvertible @this)
   {
      long value = Convert.ToInt64(@this, CultureInfo.InvariantCulture);
      string converted = Convert.ToString(value, 2);
      return converted;
   }
}

Above is the implementation of the extension method to convert objects deriving from System.IConvertible to their binary form as a String. First, the object is converted to long. This must be done to be able to specify the base for the Convert.ToString method that follows. The culture information provided is optional. Convert.ToString accepts a value to convert of type long and an integer specifying the base. This is important. Base 2 is binary, therefore, calling Convert.ToString(lngValue, base) with 2 as the base indicates a conversion to the binary form of the long value. There are other bases that can be used as well to created methods such as:

  1. ToHexString (use base 16)
  2. ToOctetString (use base 8)
  3. ToDecimalString (use base 10)

Proving Binary Validity

How does one know that the method actually works? Unit-testing is how! Below is a basic method testing four uses of the extension method previously created. This uses MSTest:

public void ToBinaryFromLong()
{
   long lv = 10L;
   Assert.AreEqual("1010", lv.ToBinaryString());

   short sv = 2;
   Assert.AreEqual("10", sv.ToBinaryString());

   Boolean bln = true;
   Assert.AreEqual("1", bln.ToBinaryString());

   bln = false;
   Assert.AreEqual("0", bln.ToBinaryString());
}

Running the code above should pass. This means the binary form is retrieved as expected.

Conclusion

This entry provided a look at a combination of System.Convert, System.IConvertable, and extension methods. Please note: This entry demonstrated extending System.IConvertible objects. It is not to suggest a String of binary numbers has common relevant uses. This is an enjoyable entry meant to prove it can be done.

Custom Data-Bound Control for ASP.Net

This post was a result from a question on Code Project asking what the GetData method is. This post will be a basic tutorial on how to create custom data-bound controls for ASP.Net. General knowledge of ASP.Net development with C# will be assumed.

What is GetData()?

The question implies the necessity of a custom data-bound control. When creating a custom data-bound control, the data-binding abilities must be implemented. DataBoundControl, GetData(), DataSourceView, and GetDataSource() are a few methods and classes involved in these custom controls.

DataBoundControl is the base class used to implement custom data-bound controls. It contains methods such as GetData() and GetDataSource() to help with the data-binding implementation of the custom control.

A data-bound control by definition will need to bind to data. There is one important question to answer regarding data: What is the data? Is it a file? Is it a table in a database? If it is a file, what format is it in: CSV, XML, text, pdf? Is it a collection of related data or a single piece? Knowing what the raw data is; its structure; its format; is essential to be able to use it as the underlying data for the data source of the custom control.

A data-bound control will need a data source. The data source is generally set by the user of the control. The data source can be such things as files and database entities as previously implied. When working with binding in the custom control the data is accessed by calling GetData(). The GetData method calls GetDataSource() internally. Calling these methods retrieves an IDataSource instance that is cached by the DataBoundControl object. This instance will remain until the OnDataPropertyChanged method signals that the data source has changed.

Specifically, GetData() returns a DataSourceView. The DataSourceView is a base class and is used by the control for data operations. Creating a custom data-bound control may involve creating a custom DataSourceView. A DataSourceView provides create, read, update, and delete (CRUD) operations for working with the underlying raw data. The corresponding methods are: Insert, Select, Update, and Delete.

In a way, the DataSourceView provides the structure of the data for the data-bound control. Therefore, there are three representations of the raw-data: the raw-data structure itself (XML, database table), the DataSourceView (the structure to provide to the control), and the data-bound control (the way the control presents the data to the user).

That’s the theory. Here’s an example.

The following will be a walkthrough in creating a custom list control. The CustomList control will be created that renders CustomListRecord children controls which will also be demonstrated. First, the CustomListRecord will be shown, then the CustonList control. The process will include setting up necessary Bindable properties, data-binding methods, and rendering.

CustomListRecord : WebControl

The CustomListRecord will contain the text to display to the user. It will be wrapped in a <div> tag and will be attributed with a class named “customlistrecord-data”. The only Bindable property is Text which will be the text displayed to the user. Here is the implementation:

[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomListRecord runat=server></{0}:CustomListRecord>")]
public class CustomListRecord : WebControl
{
   [Bindable(true)]
   [Category("Appearance")]
   [DefaultValue("")]
   [Localizable(true)]
   public string Text
   {
      get
      {
         string s = (ViewState["Text"] as string);
         return ((s == null) ? String.Empty : s);
      }
      set
      {
         ViewState["Text"] = value;
      }
   }

   protected override void RenderContents(HtmlTextWriter output)
   {
      output.WriteBeginTag("div");
      output.WriteAttribute("class", "customlistrecord-data");
      output.Write(">");
      output.WriteEncodedText(this.Text);
      output.WriteEndTag("div");
   }
}

Here we have a class derived from WebControl that has the DefaultPropertyAttribute and ToolboxData attribute. This class has a single property called Text. It is the property used to display text to the user. It has the BindableAttribute, CategoryAttribute, DefaultValueAttribute, and LocalizableAttribute. Click the links for each of the attributes to learn more about them. The property’s backing store is the control’s ViewState. When this control is rendered, it will use the given HtmlTextWriter to emit a <div> tag using the various Write methods. The html will generally look like:

<div class=’customlistrecord-data’> Text to display to the user. </div>

It is very important to emit the “>” character after calls to WriteBeginTag. Otherwise, the opening tag will not be closed properly. The end tags do not need this character.

CustomList : DataBoundControl

Now that the record for the list is created, the creation of the CustomList can begin. Below is the implementation:

[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomList runat=server></{0}:CustomList>")]
public class CustomList : DataBoundControl
{
   public CustomList() : base()
   {
      this._records = new Collection<CustomListRecord>();
   }

   protected override void PerformSelect()
   {
      if (!this.IsBoundUsingDataSourceID)
      {
         this.OnDataBinding(EventArgs.Empty);
      }

      var view = this.GetData();
      view.Select(CreateDataSourceSelectArguments(),
         new DataSourceViewSelectCallback((IEnumerable retrievedData) =>
         {
            if (this.IsBoundUsingDataSourceID)
            {
               this.OnDataBinding(EventArgs.Empty);
            }

            this.PerformDataBinding(retrievedData);
         })
      );
   }

     protected override void PerformDataBinding(IEnumerable data)
     {
           base.PerformDataBinding(data);
           if (data != null)
           {
                 foreach (object dataItem in data)
                 {
                       var record = new CustomListRecord();
                       if (this.DataMember.Length > 0)
                       {
                             record.Text = DataBinder.GetPropertyValue(dataItem, this.DataMember, null);
                       }
                       else
                       {
                             var props = TypeDescriptor.GetProperties(dataItem);
                             if (props.Count > 0)
                             {
                                   for (var i = 0; i < props.Count; i++)
                                   {
                                         var value = props[0].GetValue(dataItem);
                                         if (value != null)
                                         {
                                               record.Text += value.ToString();
                                         }
                                   }
                             }
                             else
                             {
                                   record.Text = String.Empty;
                             }
                       }
                       this._records.Add(record);
                 }

           }

           this.RequiresDataBinding = false;
           this.MarkAsDataBound();
           this.OnDataBound(EventArgs.Empty);
     }

     private IList _records;
     public IList Records
     {
           get
           {
                 if (null == this._records)
                 {
                       this._records = new Collection<CustomListRecord>();
                 }
                 return this._records;
           }
     }

     [Bindable(true)]
     [Category("Appearance")]
     [DefaultValue("")]
     [Localizable(true)]
     public string Title
     {
           get
           {
                 string s = ViewState["Title"] as string;
                 return ((s == null) ? String.Empty : s);
           }
           set
           {
                 ViewState["Title"] = value;
                 if (this.Initialized)
                 {
                       this.OnDataPropertyChanged();
                 }
           }
     }

     protected override void Render(HtmlTextWriter output)
     {
           if (output == null)
           {
                 return;
           }
           if (this._records.Count <= 0)
           {
                 return;
           }
           if (this.Page != null)
           {
                 this.Page.VerifyRenderingInServerForm(this);
           }

           /*
            * <div class="customlist-container">
            *    </div class="customlist-header">
            *       Heading Text
            *    </div>
            *    <div class="customlist-data">
            *       <div class="customlist-record">
            *          <customlistrecord />
            *       </div>
            *       <div class="customlist-record">
            *          <customlistrecord />
            *       </div>
            *    </div>
            * </div>
            */

           output.WriteBeginTag("div");
           output.WriteAttribute("class", "customlist-container");
           output.Write(">");

           output.WriteBeginTag("div");
           output.WriteAttribute("class", "customlist-header");
           output.Write(">");
           output.WriteEncodedText(this.Title);
           output.WriteEndTag("div");

           output.WriteBeginTag("div");
           output.WriteAttribute("class", "customlist-data");
           output.Write(">");

           foreach (CustomListRecord item in this._records)
           {
                 output.WriteBeginTag("div");
                 output.WriteAttribute("class", "customlist-record");
                 output.Write(">");

                 item.RenderControl(output);

                 output.WriteEndTag("div");
           }

           output.WriteEndTag("div");
           output.WriteEndTag("div");
     }
}

CustomList’s Implementation Explained

Here we have a class derived from DataBoundControl that has the DefaultPropertyAttribute and ToolboxData attribute. Each section will be explained.

The Constructor

The constructor simply initializes the _records field with a Collection of CustomListRecords:

public CustomList() : base()
{
   this._records = new Collection<CustomListRecord>();
}

The Properties

This class has two properties: Records and Title.

private IList _records;
public IList Records
{
   get
   {
      if (null == this._records)
      {
         this._records = new Collection<CustomListRecord>();
      }
      return this._records;
   }
}

[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Title
{
   get
   {
      string s = ViewState["Title"] as string;
      return ((s == null) ? String.Empty : s);
   }

   set
   {
      ViewState["Title"] = value;
      if (this.Initialized)
      {
         this.OnDataPropertyChanged();
      }
   }
}

The Title property is used to display the title of the list to the user. It has the BindableAttribute, CategoryAttribute, DefaultValueAttribute, and LocalizableAttribute. The property’s backing store is the control’s ViewState. When this is rendered a <div> tag will be emitted:
<div class=’customlist-header’> Title of the CustomList control </div>
The Records property contains the children CustomListRecord controls. The backing store is the private IList _records field. CustomListRecord controls will be added to this list upon data-binding.

The Data

The PerformSelect method is where the control obtains its data:

protected override void PerformSelect()
{
   if (!this.IsBoundUsingDataSourceID)
   {
      this.OnDataBinding(EventArgs.Empty);
   }

   var view = this.GetData();
   view.Select(CreateDataSourceSelectArguments(),
      new DataSourceViewSelectCallback((IEnumerable retrievedData) =>
      {
         if (this.IsBoundUsingDataSourceID)
         {
            this.OnDataBinding(EventArgs.Empty);
         }
         this.PerformDataBinding(retrievedData);
      })
   );
}

The internals of the PerformSelect method depends on the DataSourceView that is obtained by the call to GetData(). The Select method of the DataSourceView instance is called with DataSourceSelectArguments and a new instance of the DataSourceViewSelectCallback. The Select method, as described by Microsoft’s documentation, asynchronously retrieves a list of data from the underlying data store.

The Binding

Within the DataSourceViewSelectCallback handler is where the binding part of data-binding resides. The binding code is executed in the PerformDataBinding method:

protected override void PerformDataBinding(IEnumerable data)
{
   base.PerformDataBinding(data);

   if (data != null)
   {
      foreach (object dataItem in data)
      {
         var record = new CustomListRecord();

         if (this.DataMember.Length > 0)
         {
            record.Text = DataBinder.GetPropertyValue(dataItem,
               this.DataMember, null);
         }
         else
         {
            var props = TypeDescriptor.GetProperties(dataItem);

            if (props.Count > 0)
            {
               for (var i = 0; i < props.Count; i++)
               {
                  var value = props[0].GetValue(dataItem);
                  if (value != null)
                  {
                     record.Text += value.ToString();
                  }
               }
            }
            else
            {
               record.Text = String.Empty;
            }
         }
         this._records.Add(record);
      }

   }

   this.RequiresDataBinding = false;
   this.MarkAsDataBound();
   this.OnDataBound(EventArgs.Empty);
}

The list below outlines the major aspects of this method:

  • Cycles through the list of data retrieved from the Select method described previously.
  • Upon each item:
    • A new CustomListRecord instance is created
    • An adequate property is found on the data item
    • The property is then assigned to the Text property of the CustomListRecord instance
    • The new CustomListRecord instance is added to the collection of CustomListRecords
  • Notifies listeners that the control has been data-bound.

The Rendering

After data-binding, the control has it’s internals ready for rendering:

protected override void Render(HtmlTextWriter output)
{
        if (output == null)
        {
                 return;
        }

        if (this._records.Count <= 0)
        {
                 return;
        }

        if (this.Page != null)
        {
                 this.Page.VerifyRenderingInServerForm(this);
        }

        /*
         * <div class="customlist-container">
         *    </div class="customlist-header">
         *       Heading Text
         *    </div>
         *    <div class="customlist-data">
         *       <div class="customlist-record">
         *          <customlistrecord />
         *       </div>
         *       <div class="customlist-record">
         *          <customlistrecord />
         *       </div>
         *    </div>
         * </div>
         */

        output.WriteBeginTag("div");
        output.WriteAttribute("class", "customlist-container");
        output.Write(">");

        output.WriteBeginTag("div");
        output.WriteAttribute("class", "customlist-header");
        output.Write(">");
        output.WriteEncodedText(this.Title);
        output.WriteEndTag("div");

        output.WriteBeginTag("div");
        output.WriteAttribute("class", "customlist-data");
        output.Write(">");

        foreach (CustomListRecord item in this._records)
        {
                 output.WriteBeginTag("div");
                 output.WriteAttribute("class", "customlist-record");
                 output.Write(">");

                 item.RenderControl(output);

                 output.WriteEndTag("div");
        }

        output.WriteEndTag("div");

        output.WriteEndTag("div");
}

The DataBoundControl’s Render method is overridden in order to render the data for the user. The first two if-statements help deal with potential invalidity of the control. In this example, nothing is displayed. In a real scenario, it would be wise to add an ability to specify what is done. The comment block in this method merely depicts the html that the code below it will emit. Finally the html is emitted with the control’s Title and Records property. To render each CustomListRecord appropriately, the RenderControl method of the WebControl created earlier is called.

Using the CustomList Control

Now that the CustomList and CustomListRecord control is created, it can be used in an ASP.Net page. The steps provided in the subsequent sections are:

  1. Registering access to the CustomList control at the top of the page.
  2. Adding the CustomList control to the page.
  3. Creating a data source for the CustomList control.
  4. Setting up the data-binding to the data source previously created.
  5. Viewing the results.

Registering Access to the CustomList Control

To use the custom data-bound control, there must be a reference to the Assembly containing it as described in (@ Register):

<%@ Register assembly="DataBoundControls"
      namespace="DataBoundControls.Custom" tagprefix="asp" %>

Please note: Along with the assembly reference on the page, the project the page resides in must also reference the assembly containing the custom data-bound control. If the page and control reside in the same project, the project assembly reference is not necessary.

Adding the CustomList Control

Once the assembly is referenced, the CustomList control can be added to the page:

<body>
        <form id="Form1" runat="server">
               <cc1:CustomList ID="customList" Title="This is the title."
                     runat="server" />
        </form>
</body>

Here the CustomList control is added to the body of the page within a <form> element. The title is set to “CustomList Heading” and runat=”server” is specified.

The page should now generally look like this:

<%@ Page Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="AspPageLifeCycle._Default" %>

<%@ Register assembly="ASPNetServerControls"
      namespace="ASPNetServerControls.DataBound" tagprefix="cc1" %>

<html>
<head><title>Custom Data-Bound Controls</title></head>
<body>
        <form id="Form1" runat="server">
               <cc1:CustomList ID="customList" Title="This is the title."
                     runat="server" />
        </form>
</body>
</html>

Creating a Data Source

The CustomList control needs data to bind to. Here, the CustomList’s data source will be created. The data source will consist of a simple List of CustomListDataRecord objects. Here is the implementation of CustomListDataRecord:

public class CustomListDataRecord
{
    public CustomListDataRecord(string text)
    {
        this.Text = text;
    }
    public string Text { get; set; }
}

This object will be used to provide the item data for each CustomListRecord in the CustomList control. The data source will be of type List<CustomListDataRecord>. Here is the code:

var data = new List<CustomListDataRecord>();
data.Add(new CustomListDataRecord("Hello,"));
data.Add(new CustomListDataRecord("world!"));
data.Add(new CustomListDataRecord("This"));
data.Add(new CustomListDataRecord("is goodbye..."));

The above code creates a new List<CustomListDataRecord> instance and adds four items. This list will be used as the data source for the CustomList control on the page. Placement of this code will be described below.

Data-Binding Setup

Next comes the data-binding setup. The steps here include assigning the List<CustomListDataRecord> instance to customList’s DataSource property, using CustomListDataRecord’s Text property for the DataMember, and calling DataBind(). Here is the code that does this:

customList.DataSource = data;
customList.DataMember = "Text";
customList.DataBind();

The above code sets up the data-binding for the CustomList instance and then calls DataBind. The DataBind method will in turn call the methods we created in the CustomList control. The following section will describe the placement of this code.

Viewing the Results

At this point, the CustomList is created, added to the page, and is set up for data-binding. The code in the previous two sections will be placed in the PreRender page event handler:

protected void Page_PreRender(object sender, EventArgs e)
{
        var data = new List<CustomListDataRecord>();
        data.Add(new CustomListDataRecord("Hello,"));
        data.Add(new CustomListDataRecord("world!"));
        data.Add(new CustomListDataRecord("This"));
        data.Add(new CustomListDataRecord("is goodbye..."));

        customList.DataSource = data;
        customList.DataMember = "Text";
        customList.DataBind();
}

Further information on the PreRender event and the ASP.Net Life Cycle can be found here (ASP.Net Page Life Cycle Overview). With this code in place, the project should be ready to run! Run the project to view the created page in the browser. The page shouldn’t look too much different than below:

The view inside the browser

The page doesn’t look like much but, the html provides great potential with CSS.

Conclusion

Custom data-bound controls depend on data, data structures, and rendering. This article described the creation of each of these. There can certainly be improvements to the control ranging from default CSS to more robust data-binding and the inclusion of item templating. The code provided lays a foundation to improve upon.

Run a System.Action Instantiation Asynchronously

Here is the second article in the Extension Me series. The Extension Me series focuses on various uses of Extension Methods in .NET and primarily uses C# as the language of choice. This article will briefly focus on the topic of Asynchronous Programming by extending System.Action delegates. Using the extension method, any code wrapped in an instantiation of System.Action delegates can be executed asynchronously. The assumptions made about the reader are: has experience with the basics of programming in C# and knows what extension methods are. Please be advised: the implications of asynchronous programming are not to be ignored for severe consequences can occur.

Not only is asynchronous programming fun and beneficial (if used correctly), it is becoming an essential skill as Windows 8 is introduced. Although the implementation of the following asynchronous pattern is incompatible with Metro-style WinRT apps, the theory of asynchronous programming will surely be applicable. More information on Asynchronous Programming can be found at Visual Studio Asynchronous Programming where How-To videos, whitepapers, samples, and walkthroughs are available.

Below is the implementation of the extension method:

public static class ActionExtensions
{
	public static void Async(this Action @this)
	{
		var thread = new Thread(@this.Invoke);
		thread.Start();
	}
}

The code snippet above shows how extension methods can introduce the beauty of System.Action and System.Threading.Thread objects working together. The Action and the Thread are very close. An essential function of System.Action is wrapping a block of executable code while an essential function of System.Threading.Thread is wrapping a block of execution. By embracing these two abilities, code can be executed asynchronously just by wrapping it in an Action delegate. Here is an example:

public void ReturnsQuick()
{
        new Action(() =>
        {
                 //Long Running Code here runs on a separate thread...
        }).Async();
}

When the ReturnsQuick method is called, it creates a new instance of an Action passing a lambda containing “long-running code”. Using the extension method created previously, the code is executed on a separate thread. The code is now asynchronous and, as the name suggests, the ReturnsQuick method returns immediately after calling Async().

As mentioned above when introducing the topic of this article, there are plenty of caveats that must be addressed before adopting this approach (especially application-wide). Shared resource is one of the most important things to consider. If two threads try to access a single resource at the same time, one of them has to loose! Please take a look at the available pdf, “Threading in C#” by Joseph Albahari for a more detailed explanation of proper asynchronous approaches.

Serialization, Encryption, and Extension Methods Working In Harmony

Recently I wrote a blog entry called “Extension Me Serialize: With Encryption!” for Magenic focusing on encrypting serialized data. The url is: http://magenic.com/Blog/ExtensionMeSerializeWithEncryption.aspx and it has been referenced on Channel 9: http://channel9.msdn.com/Shows/This+Week+On+Channel+9/TWC9-Windows-8-C-Amp-NuGet-Mouse-Mischief-and-more.

Embracing the power of extension methods, I offered the ability to easily serialize objects while simultaneously offering security by default and defense in depth approaches. Also, as noted in the post, depending solely on encryption is not a responsible form of security for your IT system. The protection and maintenance of your encryption keys must be the first step. Encryption is meaningless unless the encryption keys are properly managed. If an attacker can easily access the encryption keys used for data encryption and can apply those to decrypt the data, the data is plaintext to them. I implore you, protect   your   keys !