Getting started with EWS Managed API SDK

November 11th, 2011 7 comments

EWS Managed API SDK is an easy way to interact with Exchange Web Services from the .Net platform. Exchange web services provides an interface to work with a Exchange server mailbox. Some of the common tasks that can be performed include:

  • Searching for specific emails within a folder
  • Send emails
  • Respond to emails using replies and forwards
  • Working with calendar, contacts and availability information
  • Work with inbox rules
  • Use extended properties on an EmailMessage

To understand EWS better, let us take a scenario, where we want to log information about undelivered emails (NDR) in the database. The logic for such an operation looks simple:

  • Search for NDRs within a time interval
  • Parse NDRs for relevant information
  • Log relevant information into database tables

In this post, we will look at steps 1 and 2. We will ignore step 3 as it is standard stuff.

To start working with EWS, we need to know the EWS endpoint (URL). The endpoint should be discovered using the Autodiscover service (another URL). The Autodiscover service itself should be discovered using either a SCP Lookup in active directory or using the steps outlined in the following article: http://msdn.microsoft.com/en-us/library/ee332364. With EWS Managed API, this boils down to few lines of code:

ExchangeService svc = new ExchangeService();
svc.Credentials = new System.Net.NetworkCredential(userName, password, domain);
svc.AutoDiscoverUrl("vijay@contoso.com");

I maybe slightly getting ahead. So, where is this ExchangeService class? ExchangeWebServices is the name of the NuGet library package that has to be downloaded. This has an assembly – Microsoft.Exchange.WebServices.dll. ExchangeService class is located within this assembly under a namespace – Microsoft.Exchange.WebServices.Data.

To get a list of NDRs within a time interval, we have to query the mailbox. ExchangeService.FindItems() is the method that provides a list of items that match the search criteria. The search criterias include:

  • Email created time is within the time interval.
  • The ItemClass of email message is REPORT.IPM.Note.NDR
// Search for emails within Inbox
FolderId folderId = new FolderId(WellKnownFolderName.Inbox);

// Search for a max of 100 emails, return only the ID of the email
ItemView itemView = new ItemView(100);
itemView.PropertySet = BasePropertySet.IdOnly;

// Apply search filters
SearchFilter sf1 = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeCreated, fromTime);
SearchFilter sf2 = new SearchFilter.IsLessThan(ItemSchema.DateTimeCreated, toTime);
SearchFilter sf3 = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, "REPORT.IPM.Note.NDR");
SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter[] { sf1, sf2, sf3 });

// Search for items
FindItemsResults<Item> results = svc.FindItems(folderId, searchFilter, itemView);

There are a few terms that are used. A folder is the same as the folder that we have in a mailbox – Inbox, Outbox, Sent Items etc. A Item is a base class for EmailMessage and other classes that represent an item within the folder. Item has many properties. While finding items, we can retrieve specific properties of the Item by specifying a property set. PropertySet.IdOnly retrieves items with only the ID.

The last piece of the code involves getting some relevant information from the non delivery report.

// Get all properties of email message
PropertySet pset = new PropertySet(BasePropertySet.FirstClassProperties);

// Get the body in text
pset.RequestedBodyType = Microsoft.Exchange.WebServices.Data.BodyType.Text;

// Do an Item.Bind() to retrieve the Item
emailMessage = Item.Bind(svc, item.Id, pset) as EmailMessage;

// Load the attachment in the NDR
ItemAttachment itemAttachment = emailMessage.Attachments[0] as ItemAttachment;
if (itemAttachment != null)
{
    // load the item attachment with the body as text
    itemAttachment.Load(Microsoft.Exchange.WebServices.Data.BodyType.Text, null);
}

The above code is very straight-forward. We are getting the email message using the ID retrieved in the Find(). We are setting the PropertySet to retrieve all properties. PropertySet also allows the body to be retrieved in text format (default is HTML). We are getting the only attachment in the NDR which is an ItemAttachment. An ItemAttachment is different than FileAttachment as ItemAttachment points to another Item. The attachment in NDR is usually the original sent item. We can use the various properties in the EmailMessage and ItemAttachment.Item to log relevant data to the database.

As you can see, working with EWS Managed API SDK is very simple. Please comment if you have any questions on EWS Managed API SDK.

Categories: WCF Tags: , , , ,

Top 10 Cool features in Classic ASP.NET

October 15th, 2011 3 comments

Classic ASP.NET has a lot of cool features. Here is my list of top 10 features:

#1 – ViewState
ViewState is the USP of classic ASP.NET. By storing the state of the controls in ViewState, we create some sort of statefulness in a stateless Web. For more information about ViewState, check out this link.

#2 – Page lifecycle events
Page is the unit of execution for ASP.NET. All user interactions are handled within the page object. The page object fires events after it completes a certain activity – Initialization of controls within the page, Loading of ViewState information of controls, etc. This allows developers to write event handlers that make the page work – like a button click event handler. The Page lifecycle makes the life of the developer easy. For more information about Page lifecycle, please check this link.

#3 – User controls and Custom controls
User control is a combination of several basic controls. A user control can be reused across several pages. It also can be used to abstract a complex functionality of a page (so that you do not have to worry about it). A custom server control is very useful as well. A custom server control is another type of control where you can extend a basic control to make it more usable. Or you can write your own control that will emit HTML markup and handle Page events. For more information on User controls, please check this link. For more information on Custom server controls, please check this link.

#4 – Templated controls
One of the most useful things about ASP.NET least understood by developers is Templated controls. Templated controls allow you to create a customizable control, where the developer using the control has the ability to change the layout of the control. For more information on Templated controls, please check the link.

#5 – List Controls
Anyone who started using ASP.NET for the first time probably started with these controls – GridView, ListView, FormView, DetailsView. The controls allow developers to quickly come up with a UI for showing a collection of items like say a product catalog or simple tabular data. For more information on GridView control, please check this link.

#6 – AJAX UpdatePanel
UpdatePanel is ASP.NET’s answer to AJAX. It is possible to refresh parts of a page by wrapping it inside an UpdatePanel. The UpdatePanel postback follows all the Page lifecycle events. With the UpdatePanel, a web developer working in ASP.NET need not learn new skills like jQuery to do partial page postbacks. For more information on UpdatePanel, please check this link.

#7 – Master pages
A site developed with master page will have a consistent look and feel for all pages. The developer can add as many content pages as required. Within the content pages, the controls that make up the page as well any HTML text that goes into the page can be written. For more information on Master pages, please check this link.

#8 – Theming
Theming allows the developer to specify multiple skins for a site. A skin file is nothing but styling for different types of controls used within the page. Themes and skins are now overshadowed by a lot of CSS enhancements. But, in the days of ASP.NET 2.0, were immensely useful. For more information on theming, please check this link.

#9 – Web parts and Personalization
Web parts allow developers to divide the page into multiple zones. Within each zone, multiple web parts can be embedded. Users of the page can move these web parts into different zones within the page and personalize the page. Web parts are used widely in Sharepoint sites. For more information on Web parts, please check this link.

#10 – Handlers and Modules
ASP.NET allows you to write custom handlers and modules. Handlers respond to requests from users and serves HTML response. Writing handlers is an alternative to writing a complete Page. Modules fire as part of the request life cycle. Each module does its small bit in serving the response for a request. For eg. Authentication, Session, Caching are just modules built into ASP.NET. You can write new modules and deregister existing ones. For more information on Handlers and Modules, please check this link.

HTML rendered by ASP.NET controls

September 24th, 2011 1 comment

It is sometimes useful to know how things work. As you know, anything in the browser is a bunch of HTML + CSS + Javascript. HTML includes img tag and the object tag. With the object tag, fanciful rendering using Flash or Silverlight is possible. But, for most applications, HTML + CSS + Javascript will do the trick. With Javascript frameworks like jQuery, it is possible to manipulate the HTML within the browser. HTML5 and CSS3 are evolving standards that will change the way web applications are written. With this background in mind, we will return to the topic of this post – how ASP.NET renders HTML. This post will limit itself to classic ASP.NET (and will not cover ASP.NET MVC).

The ASPX markup for a TextBox and the corresponding HTML is shown below. TextBox renders as an input tag. Look at how ASP.NET generates the ID and the Name tag. It is skewed with $ and _ to make it unique within a page.

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input id="MainContent_txtName" type="text" name="ctl00$MainContent$txtName" />

Below, I have added a couple of styles to the TextBox. The rendered HTML has a style attribute. The inline style uses standard CSS attributes.

<asp:TextBox ID="txtName" runat="server"
Font-Bold="true" BorderColor="AliceBlue"></asp:TextBox>
<input name="ctl00$MainContent$txtName" type="text" id="MainContent_txtName"
 style="border-color:AliceBlue;font-weight:bold;" />

The magic behind ASP.NET while rendering HTML lies in a method called RenderContents(). It is possible to create a RoundedTextBox (a (dummy) custom server control) using the following code:

[DefaultProperty("Text")]
[ToolboxData("<{0}:RoundedTextBox runat=server></{0}:RoundedTextBox>")]
public class RoundedTextBox : WebControl
{

    protected override void RenderContents(HtmlTextWriter output)
    {
        output.WriteBeginTag("input");
        output.WriteAttribute("type", "text");
        output.WriteAttribute("id", ClientID);
        output.WriteAttribute("name", ID);
        output.WriteAttribute("style", "border-radius:6px");
        output.WriteEndTag("input");
    }
}

Such a control would produce the following HTML from the ASPX markup. I am using CSS3 style, border-radius to get the rounded corner. For some reason, the rendered HTML has a span tag appended to it.

<cc:RoundedTextBox ID="rtbName" runat="server"></cc:RoundedTextBox>
<span id="MainContent_rtbName">
  <input type="text" id="MainContent_rtbName" name="rtbName"
  style="border-radius:6px"</input>
</span>

The following table shows some of the common ASP.NET controls and their default HTML.

ASPX HTML
<asp:Label
 ID="lblName"
 runat="server"
 Text="Name">
</asp:Label>
<span
 id="MainContent_lblName">
Name
</span>
<asp:Panel
 ID="pnlSection"
 runat="server">
</asp:Panel>
<div
 id="MainContent_pnlSection">

</div>
<asp:TextBox
ID="txtDesc"
runat="server"
TextMode="MultiLine">
</asp:TextBox>
<textarea
name="ctl00$MainContent$txtDesc"
rows="2" cols="20"
id="MainContent_txtDesc">
</textarea>
<asp:DropDownList
 ID="ddlSelect"
 runat="server">
     <asp:ListItem
       Value="Y"
       Text="Yes">
     </asp:ListItem>
</asp:DropDownList>
<select
 name="ctl00$MainContent$ddlSelect"
 id="MainContent_ddlSelect">
	<option
            value="Y">
            Yes
         </option>
</select>
<asp:CheckBox
 ID="chkTest"
 runat="server"
 Text="Test" />
<input
 id="MainContent_chkTest"
 type="checkbox"
 name="ctl00$MainContent$chkTest"
 />
<label
 for="MainContent_chkTest">
 Test
</label>
<asp:CheckBoxList
 ID="lstTest"
 runat="server">
    <asp:ListItem Value="Y" Text="Yes">
    </asp:ListItem>
</asp:CheckBoxList>
<table
 id="MainContent_lstTest">
  <tr>
    <td><input id="MainContent_lstTest_0"
          type="checkbox"
          name="ctl00$MainContent$lstTest$0"
          value="Y" />
        <label
          for="MainContent_lstTest_0">
          Yes
         </label>
      </td>
   </tr>
</table>

As you can see, there is no magic in ASP.NET controls. All ASP.NET controls render as basic HTML tags. This is useful in two ways. It helps us debug any problems in the emitted HTML that is causing a layout or scripting issue. With javascript frameworks like jQuery becoming mainstream, the layout information can be used to do client side scripting. I wish there was some documentation from MSDN on the kind of HTML layout and scripts produced by the ASP.NET controls. jQuery documentation has this for jQuery UI. Each jQuery UI widget has theming information as part of the documentation.

Using the AJAX UpdatePanel Control with jQuery

August 26th, 2011 4 comments

AJAX UpdatePanel is the most popular and the most widely used server control in the Microsoft AJAX stack. As you know, UpdatePanel is used to refresh portions of the page asynchronously. The following code shows how to use the UpdatePanel.

<asp:UpdatePanel ID="upnMain" runat="server">
    <ContentTemplate>
    <fieldset>
        <legend>UpdatePanel</legend>
            <div>
                Name:
            </div>
            <div>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </div>
            <div>
                <asp:Button ID="btnSave" Text="Save" runat="server" />
            </div>
        </fieldset>
    </ContentTemplate>
</asp:UpdatePanel>

The UpdatePanel takes care of preparing the AJAX request. This includes packing all of the form data (like textbox, Viewstate) into the Request body. The UpdatePanel makes an asynchronous call to the page and receives the response. The response data contains only the portion of the page within the UpdatePanel. The end-user gets a flicker-free experience on the page (thanks to AJAX).

In the above code, in addition to the TextBox control and the Button control, we can add a CheckBox control. When the user selects the CheckBox, the TextBox is enabled. If the user deselects the CheckBox, the TextBox is disabled. This is a common requirement in most web pages requiring user input.

<asp:UpdatePanel ID="upnMain" runat="server">
    <ContentTemplate>
    <fieldset>
        <legend>UpdatePanel</legend>
            <div>
                Name:
            </div>
            <div>
                <asp:CheckBox ID="chkName" runat="server" />
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </div>
            <div>
                <asp:Button ID="btnSave" Text="Save" runat="server" />
            </div>
        </fieldset>
    </ContentTemplate>
</asp:UpdatePanel>

To do client-side programming, we have to make use of Javascript. jQuery is a popular javascript framework that can help us write cross-browser compatible code. All HTML elements in a page have a set of events corresponding to user actions on the page. jQuery can help us write event handlers for those user actions. For a checkbox, the user click action can be written to implement the above functionality.

// event fired when document is fully loaded
$(document).ready(
    function () {
        // event handler for the checkbox click event
        $('input[name$=chkName]').click(
            function () {
                // enable / disable textbox on checkbox click
                if ($(this).is(':checked'))
                    $('input[name$=txtName]').removeAttr('disabled');
                else
                    $('input[name$=txtName]').attr('disabled', 'disabled');
            });
        });

The above code works perfectly for normal web pages. But, if jQuery code is embedded in a page with UpdatePanel, it does not work. Why is that? A portion of the page is refreshed by the UpdatePanel. So, the event handlers written for that portion of the page will not be valid. All the event handlers written for the HTML elements within the UpdatePanel have to be rewired again.

To do this, we can move the event handlers for the HTML elements within the UpdatePanel to a new function called initAjax(). This should be called each time an AJAX request is complete. The Microsoft AJAX Library contains a javascript class called the PageRequestManager which exposes an event handler for doing these things. It has events like initializeRequest, beginRequest, pageLoading, pageLoaded, and endRequest. When the request ends, the endRequest event handler is fired. Within this event handler, we can write code to reinitialize all jQuery event handlers like the Checkbox click. The code below shows how this can be done:

// initializes the event handlers for HTML elements
// within the UpdatePanel
function initAjax () {
    // event handler for the checkbox click event
    $('input[name$=chkName]').click(
    function () {
        // enable / disable textbox on checkbox click
        if ($(this).is(':checked'))
            $('input[name$=txtName]').removeAttr('disabled');
        else
            $('input[name$=txtName]').attr('disabled', 'disabled');
    });

    // write some more code for setting textbox enable / disable
    // based on checkbox state (after user clicks save)
    if ($('input[name$=chkName]').is(':checked'))
        $('input[name$=txtName]').removeAttr('disabled');
    else
        $('input[name$=txtName]').attr('disabled', 'disabled');
}

// event fired when document is fully loaded
$(document).ready(
    function () {

        initAjax();

        // Get the page request manager
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        // Initialize the event handlers for the HTML elements within UpdatePanel
        // Sets the endRequest event handler
        prm.add_endRequest(initAjax);
});

The above code illustrates the normal pattern of code while using jQuery with a single UpdatePanel. If you have multiple UpdatePanels, you will have a initPanel1, initPanel2 etc for each UpdatePanel. The endRequest event handler has to be fine-tuned to call only the initialization functions for that UpdatePanel:


function initPanel1 {}
function initPanel2 {}
function initPanel3 {}

var btn;

$(document).ready(
  function() {
       initPanel1();
       initPanel2();
       initPanel3();

       prm.add_beginRequest(
            function (sender, args) {
                btn = args.get_postBackElement().id;
            });

        prm.add_endRequest(
            function (sender, args) {
                if (btn.IndexOf("btnUpdatePanel1") > 0) {
                    initPanel1();
                }
                if (btn.IndexOf("btnUpdatePanel2") > 0) {
                    initPanel2();
                }
                if (btn.IndexOf("btnUpdatePanel3") > 0) {
                    initPanel3();
                }
            });
  });
Categories: AJAX, ASP.NET, jQuery Tags: , , ,

Developing a simple jQuery plugin for Watermarks

August 18th, 2011 1 comment

Watermark is a common feature required in many web applications. Watermarks prompt the user to enter relevant text into a textbox. Watermark text is usually greyed. When you click on the textbox, the watermark disappears. This post explains how to implement Watermarks in Asp.net using jQuery. Below is a picture of how a watermark looks like:

Textbox has an attribute called title. The title of the textbox can be something like “Please enter your name”. This usually appears as a tooltip in many browsers. When there is no text in the textbox, the title of the textbox can be used as the watermark text. When the user clicks on the textbox with the watermark text, the watermark text can be replaced with a blank text. The watermark feature is implemented using a few lines of javascript. Below is a code snippet of how this can be implemented using jQuery:

            $('.watermark').each(
                function () {

                    // on focus, remove the watermark
                    $(this).focus(
                        function () {
                            if ($(this).val() == $(this).attr('title')) {
                                $(this).val('');
                                $(this).removeClass('defaultText');
                            }
                        });

                    // on blur, if text is empty, put the watermark
                    $(this).blur(
                        function () {
                            if ($(this).val() == '') {
                                $(this).val($(this).attr('title'));
                                $(this).addClass('defaultText');
                            }
                        });

                    // this ensures that watermark is on!
                    $(this).blur();
                });
            // end of watermark

The above code picks all textboxes with class=watermark and watermarks it. The HTML markup for the textbox will look like below. The ToolTip attribute of the Textbox appears as the watermark text. The CssClass is “watermark”. The name of the class can be anything. It merely serves as a selector for picking up the textboxes to be watermarked.

<div>
    <asp:TextBox ID="txtFirst" ToolTip="Please enter first name" CssClass="watermark" runat="server"></asp:TextBox>
</div>
<div>
    <asp:TextBox ID="txtLast" ToolTip="Please enter last name" CssClass="watermark" runat="server"></asp:TextBox>
</div>

There is one more thing to do. The text within the textbox should be greyed out. The javascript adds the class=”defaultText” to the textbox. This style should be defined in the stylesheet. Sample css is shown below:

.defaultText
{
    font-style: italic;
    color: #bbb;
}

There is one detail that has to be taken care of. When the user submits the form (click submit button), we have to check whether the text within the textbox is the watermark text. If so, we have to make the textbox empty. This ensures that the server-side code receives a blank text (instead of the watermark text). This is slightly trickier than you think.

An event handler should be written to clear the watermark text before the form is posted. It is easy to assume that $(‘form’).submit(event_handler); will take care of clearing the watermark text. But, in classic Asp.net, each hyperlink can do a postback using the javascript function: __doPostback(). The __doPostback() function looks like the code below:

var theForm = document.forms['aspnetForm'];
if (!theForm) {
    theForm = document.aspnetForm;
}

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

The __doPostback() function does not trigger the jQuery submit event handler for forms. So, $(‘form’).submit(event_handler); will not work (I am not sure if it is by design. Or it is a bug in jQuery). So, we are left to use the onsubmit event of the form to clear the watermark. The code for this looks like:

document.forms[0].onsubmit =
        function () {

            $('.watermark').each(
                function () {
                    if ($(this).val() == $(this).attr('title'))
                        $(this).val('');
                });
        };

The final step to writing a simple plugin is to implement a watermark() function and a clearWatermark() function. The watermark function() implements the watermark feature. The clearWatermark() function removes the watermark before the user clicks the Save button. The code for the simple jQuery plugin is below:

(function ($) {

    $.fn.watermark = function () {

        // on focus, remove the watermark
        return this.each(
            function () {

                $(this).focus(
                    function () {
                        if ($(this).val() == $(this).attr('title')) {
                            $(this).val('');
                            $(this).removeClass('defaultText');
                        }
                    });

                // on blur, if text is empty, put the watermark
                $(this).blur(
                        function () {
                            if ($(this).val() == '') {
                                $(this).val($(this).attr('title'));
                                $(this).addClass('defaultText');
                            }
                        });

                // this ensures that watermark is on!
                $(this).blur();
            });
    };
    // end of watermark function
    // onsubmit of a form should be handled
    // this should remove the watermark
    $.fn.clearWatermark = function () {

        return this.each(
                function () {
                    if ($(this).val() == $(this).attr('title'))
                        $(this).val('');
                });

    };

    // end of plugin
})(jQuery);

Using the plugin is very simple:

$(document).ready(
    function () {
        // Put watermarks on textboxes
        $('.watermark').watermark();

        document.forms[0].onsubmit = function () {
            // Clear watermarks before submit
            $('.watermark').clearWatermark();
        };
    });

The above plugin is fully functional. It meets a lot of jQuery plugin authoring standards. A few things should be done to ensure that it follows all standards:

  • The css style – defaultText is hardcoded. The plugin should allow the developer to specify a css style.
  • clearWatermark() function should be implemented within the watermark() plugin. It should be invoked using $(‘selector’).watermark(‘clear’);

I will leave the user of this plugin to do the standardization. If anyone uses this plugin, please leave a comment.

Manipulating images programmatically

August 14th, 2011 4 comments

There are lot of image formats available. Common formats include jpeg, gif, tiff, png. These formats are based on Raster technology. In Raster format, the image is stored as a series of pixels. Each pixel has color information. Cameras store images in raster formats. As opposed to Raster formats, Scalar formats store images as a series of curves. Examples of scalar formats include svg and ai. The advantage of scalar formats is that the image retains its quality when it is enlarged. This is useful for printing. This makes scalar formats useful for making logos. The same logo can be used in multiple dimensions.

.Net supports manipulation of Raster formats. Even within Raster formats, there are some limitations. The main namespace supporting image manipulation is System.Drawing. Within this namespace, there are classes available to encode and decode various image formats. Within each image format, there is a pixel format. .Net does not support all pixel formats.

The pixel formats supported by .Net can be found here: http://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat.aspx. As you can see, .Net has good support for RGB images. Each pixel in a RGB image is represented as a combination of Red, Green, Blue. Usually, each pixel has one byte for Red, one byte for Green, and one byte for Blue. A byte can store upto 256 values. A combination of these three colors can yield upto 16.7 million colors. If a pixel has three bytes of data, the color depth of the pixel is 24 bits. Some RGB images have a color depth of 48 bits. This means each primary color is stored using a two byte block. A combination of this yields 281 trillion colors. Color depth determines the maximum number of colors that can be stored within the image.

Apart from these three channels (Red, green, blue), there exists an alpha channel. Alpha channels determine the transparency of the image. A alpha value of 0 makes the image completely translucent. This means that only the background color is seen for that pixel. A alpha value of 255 makes the image completely opaque. This means that only the color within the pixel is displayed. Any value between 0 and 255 yields a semi-transparent image that is merged with the background color. When an alpha channel is included, the color depth is usually 32 bits. Sometimes, it can be 64 bits when two bytes are used for each channel.

There is a pixel format that is not supported by .Net. This format is CMYK. CMYK stands for Cyan, Magenta, Yellow, Black. Unless RGB which is based on additive combinations, CMYK is based on subtracting the color from black. So, a CMYK value of (0,0,0,0) stands for white. (In RGB, white is represented by (255,255,255)). A CMYK image usually has a color depth of 32 bits (one byte for each channel). If the image has transparency, then the color depth is 40 bits.

Each image can be manipulated programatically by the Bitmap class. Making a thumbnail image or changing the dimensions of image is quite simple. But real image manipulation involves things like detecting gradients or edges within an image. To do this, we can get the bytes within a Bitmap. This can be done using the LockBits method of the Bitmap class. This method locks the Bitmap for manipulating and provides a pointer to the first byte of data. Manipulating bytes as pointers requires compilation using the UNSAFE flag.

The pointer position is calculated using a simple mathematical formula: i*bpp + j*Stride. This formula is explained below:

  • i = Column position of the pixel.
  • j = Row position of the pixel.
  • bpp = bytes per pixel (3 bpp for 24 bit Color depth)
  • Stride = number of bytes for one row of pixel information. (Usually, width*bpp)

Once we know how to traverse the image using the offset pointer as above, the rest of the work is fairly simple. The challenge in manipulating a image is learning how to detect edges and how to detect gradients.

Let us say, we are traversing the image from left to right. If we notice a difference of color from one pixel to another, there can be two reasons. The image is changing from one color to another (like from Red to blue). Or there is a smooth gradient (from Dark red to light red). Each of the above transformations happens over multiple pixels. When an image is changing from one color to another, it is slightly more abrupt and happens within a span of few pixels. Detecting this change is usually called edge detection. A gradient is a much smoother transformation of color and happens over a larger range of pixels. Detecting edges in an image with gradients is much more difficult.

Thankfully, we do not have to write all the code by ourself. There are software vendors who provide sophisticated class libraries for manipulating images. Here is a partial list of software vendors:

Categories: General Tags: , , , , ,

NumberFormatter, a jQuery plugin

August 8th, 2011 3 comments

A common scenario encountered in business applications is to format a number after the user types a number into the textbox. For eg, if the user types 1235, the number should be formatted to 1,235.00. A jQuery plugin called NumberFormatter takes care of this scenario. What is good about the NumberFormatter is that it can format numbers according to the locale specified. The supported locales and minimum documentation is part of the javascript file.

There are two main functions: format() and parse(). format() formats the number with a textbox. parse() is used to convert the formatted number back to the undecorated number format. To illustrate this, we can create a simple calculator that adds two numbers using jQuery. The HTML looks like below:

<fieldset>
    <div>
        <asp:TextBox ID="txtNum1" runat="server" Text="0"></asp:TextBox>
    </div>
    <div>
        <asp:TextBox ID="txtNum2" runat="server" Text="0"></asp:TextBox>
    </div>
    <div>
        <asp:TextBox ID="txtNum3" runat="server" ReadOnly="true"></asp:TextBox>
    </div>
    <div>
        <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
    </div>
</fieldset>

There is a helper function – formatHandler() that is an event handler. This event handler is triggered when user leaves the textbox. The formatHandler() function formats the value of the text within the textbox when the user leaves the textbox. There is another function calcSum() which is also triggered when the value within the textbox changes. The javascript for the above logic is below:

function formatHandler() {
    $(this).format({ format: "#,###.00", locale: "us" });
}

$(document).ready(
    function () {
        $('input[name$=txtNum1]').change(calcSum);
        $('input[name$=txtNum2]').change(calcSum);

        $('input[name$=txtNum1]').blur(formatHandler);
        $('input[name$=txtNum2]').blur(formatHandler);

        calcSum();
    });

Finally, there is a function to calculate the sum of the two numbers. This is quite simple. The only catch to this function is because of the NumberFormatter plugin. The NumberFormatter changes the format of the number within the textbox. If you use a parseFloat() function to convert the textbox value into a floating point value, it picks up only the number before the first comma separator. For eg, if your formatted number is 1,235.00, parseFloat() on the textbox will pick only 1. So, the way to deal with this problem is to unformat the value in the textbox, while performing client-side calculations. The parse() method will give the unformatted value of the textbox. This will give a value of 1235 (after removing the formatting). The calcSum() is given below:

    function calcSum() {
        var rawVal1 = $('input[name$=txtNum1]').parse({ locale: "us" });
        var float1 = parseFloat(rawVal1);
        var rawVal2 = $('input[name$=txtNum2]').parse({ locale: "us" });
        var float2 = parseFloat(rawVal2);
        $('input[name$=txtNum3]').val(float1 + float2);
        formatFunction($('input[name$=txtNum3]'));
    }

    function formatFunction(obj) {
        obj.format({ format: "#,###.00", locale: "us" });
    }

The good thing about NumberFormatter is that the server-side code understands the number formatting very well. The btnSave_Click() event handler can convert the formatted number into a floating point value with a simple float.Parse().

protected void btnSave_Click(object sender, EventArgs e)
{
    float float1 = float.Parse(txtNum1.Text);
    float float2 = float.Parse(txtNum2.Text);
    txtNum3.Text = (float1 + float2).ToString();
}

NumberFormatter is a very good jQuery plugin. It is simple and easy to use. It takes care of the formatting requirements in the browser side. It makes the UI appealing to business applications.

Localization of Webforms applications in multiple languages

August 7th, 2011 No comments

Usually, web applications should be available in multiple languages other than English. In this blogpost, I am going to walk over creating a sample application that will be localized in French and Dutch. Usually, the preferred language is picked from the user’s browser settings. To make it a little tougher, we will allow the user to switch languages at runtime. To enable runtime switching of languages, we will add three link buttons in the master page.

<div style="background-color: #cccccc;float:right;">
    <asp:LinkButton ID="btnEn" runat="server" Text="en" CommandArgument="en" OnCommand="SetCulture"></asp:LinkButton> |
    <asp:LinkButton ID="btnFr" runat="server" Text="fr" CommandArgument="fr" OnCommand="SetCulture"></asp:LinkButton> |
    <asp:LinkButton ID="btnNl" runat="server" Text="nl" CommandArgument="nl" OnCommand="SetCulture"></asp:LinkButton>
</div>

Localization is providing a placeholder for text in multiple languages. The text comes from a resource file. Asp.Net provides multiple ways of doing localization: implicit and explicit. In Default.aspx, we enable implicit localization. We allow the text within a label with ID lblImplicit to come from resource files. The code for the label has a meta:resourcekey=”" attribute attached to it:

<h2>
    Culture Demo - Implicit Localization
</h2>
<p>
    <asp:Label ID="lblImplicit" runat="server" meta:resourcekey="lblImplicit" Text="Implicit Localization"></asp:Label>
</p>

In implicit localization, the text comes from a resource file defined under App_LocalResources folder. The resource file has the convention of .aspx..resx. The default resource file for default.aspx is default.aspx.resx. The resource file for french is default.aspx.fr.resx. Create resource files for each supported language. Within the resource file, use the .Text to define the text for the label. The french resource file looks like:

We can set explicit localization for About.aspx (just to try it out). Explicit localization looks for resource files under App_GlobalResources. In this folder, resource files are not organized by aspx page names. You can create a default resource file of Messages.resx. In the About.aspx, we can create a label to use Message1 from Messages.resx as follows:

<h2>
    Culture Demo - Explicit Localization
</h2>
<p>
    <asp:Label ID="lblExplicit" Text="<%$ Resources: Messages, Message1 %>" runat="server"></asp:Label>
</p>

In the above label, the text is available within a tag. It has a Resources: keyword. Both the Resource file name as well as the Key name is provided (delimited with a comma). The french resource file for Messages will look like Messages.fr.resx. The dutch resource file, Messages.nl.resx looks like:

Now, we are ready to write some code to make all of this work. When we are clicking the link button in the master page, the SetCulture event handler is called. All we do in the below code is set the Session["Culture"] variable to the selected language. Also, the page is redirected to. This will ensure that the selected culture will set in the reload.

protected void SetCulture(object sender, CommandEventArgs e)
{
    Session["Culture"] = e.CommandArgument.ToString();
    Response.Redirect(Request.RawUrl);
}

Every page has a method – InitializeCulture(). This method is triggered in the Page lifecycle ahead of all events including Page_PreInit(). This is one reason that the page is reloaded again. In InitializeCulture(), we pick the language setting from the Session variable. Then, we set the UICulture for the current thread. This will ensure that the right resource files are picked for the current request.

protected override void InitializeCulture()
{
    // When the user comes to the page for the first time
    if (Session["Culture"] == null)
    {
        Session["Culture"] = "en";
        Session["OldCulture"] = "en";
    }

    // Set the UI Culture here

    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo((string)Session["Culture"]);
    UICulture = (string)Session["Culture"];
    base.InitializeCulture();

}

Finally, there is some code to enable / disable the link buttons in the Page_load of the master page:

protected void Page_Load(object sender, EventArgs e)
{

    string culture = (string)Session["Culture"];
    string oldCulture = (string)Session["OldCulture"];

    // Disable the button in current culture
    // This is required if user goes to some other page
    // Page is populated with controls.
    LinkButton newBtn = FindControl("btn" + culture) as LinkButton;
    if (newBtn != null)
        newBtn.Enabled = false;

    // if old culture is different
    // This happens when the user clicks on any of the link buttons
    if (culture != oldCulture)
    {
        // disable the button for the current culture

        // enable the old button and reset oldculture
        LinkButton oldBtn = FindControl("btn" + oldCulture) as LinkButton;
        if (oldBtn != null)
            oldBtn.Enabled = true;
        Session["OldCulture"] = culture;
    }
}

One last thing to note, I have used a baseclass for Page – CultureDemo.MainPage. This class overrides the InitializeCulture method. All pages in the CultureDemo application derive from CultureDemo.MainPage instead of System.Web.UI.Page. This ensures that all page and all requests have the right language setting. The complete application is available in the zip file: CultureDemo

Categories: ASP.NET Tags: ,

Integrating jQuery UI with your app

July 29th, 2011 2 comments

jQuery UI has a lot of widgets: Accordion, Auto-complete, Datepicker, Dialog, Slider, Tabs. It is not very obvious how to integrate these widgets into your apps. jQuery site has a Getting Started guide. But, this guide covers the download part, alone. This blog post will help you get started in integrating jQuery into your Asp.Net applications.

jQuery UI comes with a lot of themes. The Gallery contains a lot of themes that you can browse. Once you decide on a theme, click the download link. In the download page, select your preferred theme in the right hand dropdownlist.

In the selections, select all of UI core. Select all of Interactions. This is because some of the widgets might use a few Interactions internally. In the Widget section, select few widgets. In my project, I require Datepicker, and Dialog. So, I am selecting only these two widgets. Deselect all of effects. Effects are required for animations. For most professional applications, this may not be required. Once the selection is complete, click Download button.

The Download button downloads a zip of the selected source. Extract the zip into a folder of your choice. Of all the extracted files, we need two script files and a CSS folder. Copy the jQuery (jquery-1.5.1.min.js) and jQuery UI (jquery-ui-1.8.14.custom.min.js) script file from the js folder into the Scripts folder of the application. Copy the theme folder from the css folder into Styles folder of the application.

Open the application in Visual Studio. Add the script files and the theme folder into your project (using Add Existing Item). In the header section of your content page, add references to the script files and stylesheet file. The code can be found below:

<link href="Styles/jquery-ui-1.8.14.custom.css" type="text/css" rel="Stylesheet" />
<script type="text/javascript" src="Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-ui-1.8.14.custom.min.js"></script>

Finally, write the script to use the jQuery widget. This is very simple. If you have a textbox (txtDate) for which you want to attach a datepicker, all that you have to write is the following code:

$(document).ready(
  function() {
    // the below selector gets the textbox with name ending with txtDate
    // this selector ensures that the textbox will be picked even if it is embedded
    // within a naming container like a GridView
    $('input[name$=txtDate]').datepicker();
  });

AjaxControlToolkit vs jQuery

July 28th, 2011 2 comments

AjaxControlToolkit has lot of controls that are AJAX enabled. Some of them are quite popular. AutoComplete, ModalPopup, ReorderList, Tabs are quite popular. These controls are based on Microsoft AJAX library. The AJAX Control Toolkit is available as a bulky DLL that must be referenced by your project.

jQuery is a popular open-source cross-browser compatible javascript framework used by numerous websites. jQuery also has lot of UI plugins. These UI controls have behaviour in jQuery and styling in CSS. A lot of popular themes are available with the jQuery plugin. jQuery UI has a smaller footprint compared to AjaxControlToolkit. The script associated with jQuery UI can be placed in the Script section of the website. jQuery UI does not have a server component and rely on input fields to transmit data to the server.

The popular controls in AjaxControlToolkit and jQuery UI are: Tabs (ACT , jQuery), Calendar (ACT, jQuery), ModalPopup (ACT, jQuery) and ReorderList (ACT, jQuery)

In my opinion, Tabs is well implemented in jQuery. jQuery allows to select div with a specific class and make them as tab container. $(‘.tabs’).tabs(). In ACT, the TabContainer is a sort of layout template. Also, the styling is difficult to manipulate in ACT. Also, by default, there is no postback event. Switching tabs is largely handled in the client side. This is applicable to the jQuery tabs as well

Datepicker is good in both ACT and jQuery. ACT and jQuery both extend a readonly textbox as a calendar control. When the user clicks on the textbox, a calendar control opens.

ModalPopup is very popular in both ACT and jQuery. In ACT, the visibility of ModalPopup can be controlled using the server-side Show() method. In jQuery, this is not possible. jQuery dialog() works largely as a client-side implementation. However, the selector API ensures that the dialogs have a small footprint. Imagine a scenario where each element in a list should have a modal popup. jQuery selector API helps avoid repeated code.

The Reorder list is well implemented in ACT. The reordered list is available in the postback. In jQuery, the reorder should be packed into the postback data. Additional processing should be done at the server-side for the jQuery reorder list.