ToString Enhancements with Regular Expressions

This entry will be a walkthrough on creating a ToString extension method for easily extracting a substring matching a given regular expression (RegEx). General regular expression knowledge is assumed as well as basic String manipulation in C#.

Implementation & Use

Diving right in here is the implementation:

public static string ToString(this string @this, string regexPattern)
{
  return (Regex.IsMatch(@this, regexPattern) ?
  Regex.Match(@this, regexPattern).Value : null);
}

This extension method is for System.String objects. It can be used like this:

string phoneRegex =
     @"^[- .]?(([2-9]\d{2})|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$"
string phoneRaw = "ea011-122-2333klai";
string phone = phoneRaw.ToString(phoneRegex);

Above is an example of the extension method in use. First, the regex pattern is stored. This pattern is used to match particular phone number formats. The raw data for the phone number is then stored. The raw data of the phone number cannot be used in its entirety to make a valid phone call therefore, it must be scrubbed. This occurs with the call to phoneRaw.ToString(phoneRegex). This call returns the string “011-122-2333”. Using the extension method, the phone number went from a raw, unusable form, to a valid format using a single method call.

Implementation Details

The ToString extension method created above uses the Regex class. This class provides various methods for retrieving information regarding the Regex’s anatomy such as groups, group numbers, and pattern matches.  The ToString extension method uses two of these: IsMatch, and Match.

Regex.IsMatch

This is a static method returning a Boolean value indicating whether a match is found in the specified string using the specified regular expression. In the extension method created above, this is used to decide whether to proceed with returning the value of Regex.Match, or simply return null.

Regex.Match

This is a static method returning a Match object containing information about the first occurrence of the specified regular expression in the specified string. The extension method created above uses this to return the Value of the match. This value contains the string representation of the matched substring found in the input string.

Originally Perceived Enhancements

There are a few improvements that can be made to the original extension method. One, in particular, is the use of the static method Matches. This returns all of the successful matches of a regular expression in a given string. The user can then determine which match to use. Below is an example:

public static string ToString(
  this string @this,
  string regexPattern,
  int matchIndex)
{
  var matches = Regex.Matches(@this, regexPattern);
  return
     (matches.Count > matchIndex ? matches[matchIndex].Value : null);
}

Above is another version of the ToString extension method that accepts a RegEx pattern and a match index. The method retrieves all of the matches and, if valid, returns the desired match’s value. This way, the user is able to do this:

string phoneRegex = @"^?\d{3}";
string phoneRaw = "(011) 122-2333";
string areaCode = phoneRaw.ToString(phoneRegex, 0);

Above shows the enhanced version of the ToString extension method. It is used to obtain the area code “011” of the phone number by retrieving the first occurrence of 3 consecutive digits.

Conclusion

The two versions of the ToString extension method created above allow, with just a few lines of code, the ability to do all sorts of string manipulation and input validation using regular expressions.

A Binary Look at System.IConvertible Derivations

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</span> 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 with a “customlistrecord-data” class attribute. 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</span> 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" %>

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 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 <a title=”List” href=”http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx” target=”_blank” rel=”noopener noreferrer”>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. 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 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 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.

The Dispose Pattern in C++

This article will describe the Dispose pattern, and how to employ it in C++. Please note: this is not an introduction to C++. The topics and code presented here are done so with the assumption that the reader knows how to write basic data structures in C++. Also, with most of my background in .NET, C++ best practices are followed to the extent of my abilities.

Why not just use the destructor?

It is written [MSDN: Implementing a Dispose Method], “the pattern for disposing an object, referred to as a dispose pattern, imposes order on the lifetime of an object.” Using the Dispose pattern, the developer can determine when an object is destroyed. In .Net, it is generally only used for objects that access unmanaged resources. Since C++ is unmanaged, memory management is our priority and responsibility. One of the points this gets to is properly destroying objects. Memory leaks can occur when improperly destroying objects (or when failing to destroy them). I, along with many other developers, cannot prevent 100% of memory leaks. We can take measures to get as close to that point as possible but, odds are there will be at least one somewhere in the vastness of the code. One measure that can be taken is implementing the Dispose pattern and using it appropriately. It makes managing memory more explicit and allows for a higher-level mechanism for managing an object’s lifetime.

How is it done in .NET?

Implementing the Dispose pattern in .NET requires deriving from System.IDisposable:

public interface IDisposable
{
  void Dispose();
}

public sealed class DisposableObject : IDisposable
{
  private bool _disposing;
  public override Dispose()
  {
    this.Dispose(!this._disposing);
    GC.SuppressFinalize(this);
  }

  private void Dispose(bool disposing)
  {
    if(disposing)
    {
      this._disposing = true;
      //… release resources here …
    }
  }
}

Implementing the dispose pattern in this way basically marks the object as “dead”. By doing this, it allows the Garbage Collector to free the memory used by the object without the need to perform costly finalization. It is best practice to create a protected (or private if the class is not inheritable) dispose method accepting a boolean value indicating if the object is disposing. Doing this allows further control of object disposal.

Proper OOD (Object-Oriented Design) is employed here by separating the interface from its implementation (please see the Separation PDF). Microsoft did well with this one. With the IDisposable interface, multiple objects can be “Disposable” and mechanisms can be created to track these kinds of objects.

How is it done in C++?

In C++ the Dispose pattern is used to explicitly release resources used by the internals of the object. To properly implement this, an interface must be created:

public class IDisposable
{
  void dispose() = 0;
};

This looks much like the interface in .NET but with a few C++ semantics to enforce what we are intending. By making the dispose() method virtual, we force the user of this interface to implement it in their subclass:

public class DisposableObject : public IDisposable
{
  private bool _disposing;
  public override dispose()
  {
    if(this.dispose(!this->_disposing))
    {
      //… more disposing-dependent logic here …
    }
  }
  protected bool dispose(bool disposing)
  {
    if(disposing)
    {
      this->_disposing = true;
      //… release resources here …
    }
    return this->_disposing;
  }
};

Again, this looks a lot like the .NET version but with a few changes for C++ compliance. The code also includes a variation of the protected dispose method to demonstrate the ability for even further disposal control.

How is it used in C++?

Generally the dispose method is called within the object’s destructor. By tracking whether the object is disposed or not, other tracking mechanisms can be used to explicitly dispose the object. Below is a basic custom auto_ptr implementation created based on various sources (A Sample auto_ptr implementation, Scott Meyers Update on auto_ptr):

template<typename TObject, typename R, R (TObject::*Dispose)()>
 class AutoPtr
 {
  public:
  explicit AutoPtr(TObject* pointerToWrap = NULL)
    : wrapper(pointerToWrap)
  {
  }
  AutoPtr(AutoPtr& Other)
    : wrapper(Other.Release())
  {
  }
  AutoPtr& operator=(AutoPtr& Other)
  {
    Reset(Other.Release());
    return (*this);
  }
  ~AutoPtr()
  {
    if(wrapper)
    {
      (wrapper->*Dispose)();
      wrapper = NULL;
    }
  }
  TObject& operator() const { return (wrapper); }
  TObject** operator&()
  {
    Reset();
    return &wrapper;
  }
  TObject* operator->() const
  {
    return GetPointer();
  }
  operator bool() const
  {
    return wrapper != NULL;
  }
  TObject* GetPointer() const
  {
    return wrapper;
  }
  TObject* Release()
  {
    TObject* tempPtr = wrapper;
    wrapper = NULL;
    return tempPtr;
  }
  void Reset(TObject* p = NULL)
  {
    if(p != wrapper)
    {
      if(wrapper)
      {
        (wrapper->*Dispose)();
      }
    }
    wrapper = p;
  }

  private:
  TObject* wrapper; //the wrapped pointer
};

With this code we can do something like:

typedef AutoPtr<DisposableObject,
                void,
                &DisposableObject::Dispose> DisposablePtr;

And use it like this (note that “work” is assumed to be an instance method of DisposableObject):

DisposablePtr obj(new DisposableObject());
obj->work();

Above is an AutoPtr implementation that automatically disposes objects when the AutoPtr instance goes out of scope. This is an example of a high-level mechanism of memory management making good use of the Dispose pattern.

Conclusion

This was an exhaustive look at how the Dispose pattern can be implemented in C++ to encourage easier memory management. First, the .NET version of the pattern was examined. Then, moving on to C++, the Dispose pattern was implemented and then used in a custom auto_ptr implementation. Memory management is a very important aspect of C++. This article describes one way to make it a little easier.

The Importance of SharePointWebPartCodeGenerator

Honestly, I have yet to actually enjoy SharePoint development specifically but, I still let myself learn. I want to briefly describe an issue I had when creating visual web parts in a sandbox solution. As the name of this entry implies, the SharePointWebPartCodeGenerator plays an important role in the web part creation. I will briefly describe what it is, where it is used, and why it is important. A basic knowledge of ASP.Net and developing in Visual Studio is necessary.

Huge Name, Small Functional Scope

The SharePointWebPartCodeGenerator is quite a self-descriptive name. It is a tool used to generate code for a web part. It is the “designer file” creator for the visual aspect of the SharePoint web part. Let me explain by describing what this is in average ASP.Net. In ASP.Net, pages and controls (ASPX and ASCX respectively) have a corresponding designer file. This is where the generated UI code is placed when a developer adds such things as “<asp:Textbox..” or “<asp:Literal..” etc etc. This is automated so it doesn’t usually affect the developer. The wonder that is the Visual Studio 2010 SharePoint Power Tools requires the use of the tool SharePointWebPartCodeGenerator. I’ll explain how and where to use this tool in the following sections.

Case in Point

I recently created a web part to display items from a list in a certain way and to wrap some specific functionality around those items. I went with a Visual Web Part. I find it a lot easier to develop a web user interface when it can actually be seen in HTML while I’m developing it. As usual, I found a better way to implement the web part only After I finished creating it. The change involved updating the controls used in the markup for the web part. After making the changes, I attempted to build the solution and got a nice error similar to:

‘..WebPart’ does not contain a definition for ‘userControlID’ and no extension method ‘userControlID’ accepting a first argument of type ‘..WebPart’ could be found (are you missing a using directive or an assembly reference?)

Looking at the project structure I noticed there was no designer file. Obviously, that is a problem! No designer file means that there is no code-behind support for the management of controls in my web part. I finally found that I needed to use a tool to create this designer file. I had to add ‘SharePointWebPartCodeGenerator’ to the ‘Custom Tool’ field of the markup file’s properties.

How-To

Let me describe this process. It is quite straightforward.

Make sure the markup file (e.g. .ascx) is selected in the Visual Studio project as shown below:

Select the ASCX In VS Solution Explorer

View the Properties of the markup file and make sure the ‘Custom Tool’ field contains ‘SharePointWebPartCodeGenerator’ as shown below:

Add SharePointWebPartCodeGenerator as CustomTool in ASCX's File Properties

This was all I needed to fix my issue. Making markup edits were no problem after I made that entry into the properties of the markup file. It now automatically runs the custom tool when I save my changes to the markup.

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 lose! 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 !