Saturday, August 4, 2012

Using Extension methods in Asp.Net 3.0 and higher .net framework

Since the dawn of asp.net, web based development has become a lot easier. It provides a great deal of control over designs and code. Let's say, one of them is Extension methods. It make it easy to add functionality to an existing type using a natural syntax. Also, since the extension methods appear in Visual Studio's IntelliSense drop-down list, they are easier to find and use than wrapper class equivalents. In this article, I show you how to create extension methods in asp.net.

Extension Methods in ASP.NET

At first, we need to create one class as below.
//Extensions.cs
namespace System
{
    public static class Extensions
    {
        public static int? ToNullInt(this string value)
        {
            int result;
            if (int.TryParse(value, out result))
            {
                return result;
            }
            return null;
        }
        public static int ToIntOrDefaultInt(this string value, int result = 0)
        {
            int.TryParse(value, out result);
            return result;
        }
        public static bool? ToNullBool(this string value)
        {
            bool result;
            if (bool.TryParse(value, out result))
            {
                return result;
            }
            return null;
        }
        public static bool ToBoolOrDefaultBool(this string value, bool result = false)
        {
            bool.TryParse(value, out result);
            return result;
        }
        public static string ToStringFormat(this int value)
        {
            return value.ToString("#,##0");
        }
        public static string ToStringFormat(this double value)
        {
            return value.ToString("#,##0.00");
        }
    }
}
we need an extension method to mark the function as static so that it can be accessed at any time without declaring object and secondly, mark the first parameter with the "this" keyword. This keyword basically tells the CLR that when this extension method is called, to use "this" parameter as the source.

Copy the following code to page load event in code-behind for using extension methods we created above.
string strVal = "12345";
int? nullableIntVal = strVal.ToNullInt();
//return 12345

int intVal = strVal.ToIntOrDefaultInt();
//return 12345

string blnVal = "True";
string blnVal2 = "Yes"; // can not parse
string blnVal3 = "1"; // can not parse
bool? nullableBool = blnVal.ToNullBool();
//return True

bool? nullableBool2 = blnVal2.ToNullBool();
//return Null since can not parse

bool? nullableBool3 = blnVal3.ToNullBool();
//return Null since can not parse

bool bln = blnVal.ToBoolOrDefaultBool();
//return True

bool bln2 = blnVal2.ToBoolOrDefaultBool();
//return False since can not parse

bool bln3 = blnVal3.ToBoolOrDefaultBool();
//return False since can not parse

string strIntFormat = intVal.ToStringFormat();
//return 12,345

double dblVal = 12345.67;
string strDblFormat = dblVal.ToStringFormat();
//return 12,345.67 
Now, run it again! I hope you guys those who are new to extension methods will able to write more better and reusable codes but I can not test it in Microsoft Visual Web Developer 2010 Express. Please drop a line if you know why. Thank.

Thursday, August 2, 2012

HTML noscript tag for javascript disabled browser

We often use javascript for dynamic web site and javascript is getting critical in most web application. So,   we also need to protect from malfunction for browsers that do not support client-side scripts. In this post, I introduce you html <noscript> tag here.
The <noscript> tag is used to provide an alternate content for users that have disabled scripts in their browser or have a browser that doesn’t support client-side scripting.The <noscript> element can contain all the elements that you can find inside the <body> element of a normal HTML page.The content inside the <noscript> element will only be displayed if scripts are not supported, or are disabled in the user’s browser. You can insert <noscript> tag to <head> tag or <body> tag.
Put the following script to <head> tag and disable javascript and then run and see it.
<script type="text/javascript">
        document.write("Hello World!")
</script>
<noscript>
    Please active javascript on your browesr.
</noscript>


Sunday, July 22, 2012

How to show Modal Dialog Box with JQueryUI API in Asp.net Web Form

I used JQuery a lot thesedays for user interactive web pages and then I start using JQueryUI for Dialog box in web form. I realize that It is simpler and more effective than I expected. This post explain you how to create Modal Dialog with JQueryUI in asp.net web form.
A dialog is a floating window that contains a title bar and a content area. The dialog window can be moved, resized and closed with the 'x' icon by default.
If the content length exceeds the maximum height, a scrollbar will automatically appear.

JQueryui Dialog Box in ASP.Net Web Form

First you need to download the JQuery UI API here and copy them to your project folder. After that, copy and paste the following code to <head> tag.
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript">
    $(function () {
        // Dialog
        $('#dialog').dialog({
            autoOpen: false,
            width: 500,
            closeOnEscape: true,
            resizable: false,
            draggable: true,
            modal: true,
            title: "Customer Details"
        });

        // Dialog Link
        $('#btnEditText').click(function () {
            $('#dialog').dialog('open');
            $('#dialog').parent().appendTo($('form:first'));
            return false;
        });

        $('#editBox_Cancel').click(function () {
            $('#dialog').dialog('close');
            return false;
        });
    });
</script>
Create the following control in <form> tag. There are tow sessions (two div) for displaying customer information. One is main content and other is for editing.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
    <!--Using Partial Rendering to Update the Customer View -->
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table>
                <tr>
                    <td>
                        <b>Customer ID:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="lblCustomerID" Text="C00001" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Company Name:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="lblCompanyName" Text="Eastern Connection" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Contact Name:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="lblContactName" Text="Ann Devon" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Country:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="lblCountry" Text="Germany" />
                    </td>
                </tr>
            </table>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="editBox_OK" />
        </Triggers>
    </asp:UpdatePanel>
    <asp:Button runat="server" ID="btnEditText" Text="Edit text" />
</div>
<div id="dialog">
    <!-- Dialog box:: Edit customer info -->
    <asp:UpdatePanel runat="server" ID="ModalPanel1" RenderMode="Inline" UpdateMode="Conditional">
        <ContentTemplate>
            <table>
                <tr>
                    <td>
                        <b>Customer ID:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="editCustomerID" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Company Name:</b>
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="editTxtCompanyName" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Contact Name:</b>
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="editTxtContactName" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Country:</b>
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="editTxtCountry" />
                    </td>
                </tr>
            </table>
            <hr />
            <asp:Button ID="btnApply" runat="server" Text="Apply" OnClick="btnApply_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:Button ID="editBox_OK" runat="server" Text="OK" OnClick="editBox_OK_Click" />
    <asp:Button ID="editBox_Cancel" runat="server" Text="Cancel" />
</div>
In code-behind, the coding is as below.
protected void InitDialog()
{
    editCustomerID.Text = lblCustomerID.Text;
    editTxtCompanyName.Text = lblCompanyName.Text;
    editTxtContactName.Text = lblContactName.Text;
    editTxtCountry.Text = lblCountry.Text;
    SetFocus("editTxtCompanyName");
}
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        InitDialog();
    }
}
protected void editBox_OK_Click(object sender, EventArgs e)
{
    // Save to the database
    // Refresh the UI
    lblCompanyName.Text = editTxtCompanyName.Text;
    lblContactName.Text = editTxtContactName.Text;
    lblCountry.Text = editTxtCountry.Text;
}
protected void btnApply_Click(object sender, EventArgs e)
{
    if (editTxtCountry.Text == "Germany")
        editTxtCountry.Text = "Cuba";
    else
        editTxtCountry.Text = "USA";
}
The jQuery UI API provides us simple and advance effects that you can use to create highly interactive web applications. Like other jQuery UI effects, jQuery UI Dialog is easy to use. Using it on the right way to help it be more flexible and scalability. You can see other post(How to show Modal Dialog Box with ASP.Net Ajax) I wrote before. Thank.

More Details

Other Nice Post

Monday, June 18, 2012

Simple jQuery Confirm and Alert Dialogs

These days, JQuery is getting more powerful and more useful for rich interactive web application. For myself, I used a lot of JQuery for web interface and ajax pattern. Here, I show you the simple and easy way to use the beautiful jquery Confirm and Alert popup as below.

JQuery confirm popup
First, you need to download the jquery library and resource here (it inclueds images, css and js file.).
Put the following code to <head> tag.
<script src="jquery.alerts.js" type="text/javascript"></script>
<link href="jquery.alerts.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
 function ConfirmPopup() {
   jConfirm('Can you confirm to leave page?', 'Confirmation Message', function (r) {
     if (r) {
       jAlert('Please visit again.', 'Alert Message' , function (r) {
         window.location = 'http://www.aspmemo.net';
       });
     }
   });
}
Create the sever button control like this.
<asp:button id="Button1" onclick="Button1_Click" runat="server" text="Show Confirm">
In that button click event, we register the created javascript function to call.
protected void Button1_Click(object sender, EventArgs e)
{
 Page.ClientScript.RegisterStartupScript(this.GetType(), "popupScript", "ConfirmPopup()", true);
}
That's it. When you clicks the button, it show Confirm popup and then click on Ok button, it show Alert pop and click on OK again, it redirects to one url.

More details bout this JQuery Plugin

Saturday, June 2, 2012

How to bind enum type to dropdownlist in asp.net 4

We often encounter to use DropDownList binding an Enum Type as a DataSource. This tutorial show you the simple way to bind Enum Type to ASP.Net DropDownList control.

First, create sever control like below:
<form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlMonth" runat="server">
        </asp:DropDownList>
    </div>
</form>
Second, create Enum Type "Emonth" and bind to dropdownlist control in code-behind as follow:
public partial class Enumddl : System.Web.UI.Page
{
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ddlMonth.DataSource = Enum.GetValues(typeof(EMonth)).Cast<EMonth>()
                    .Select(x => new { text = x.ToString(), value = ((int)x).ToString() }).ToList();
                ddlMonth.DataTextField = "text";
                ddlMonth.DataValueField = "value";
                ddlMonth.DataBind();
            }
        }
}
public enum EMonth
{
        January = 1,
        February = 2,
        March = 3,
        April = 4,
        May = 5,
        June = 6,
        July = 7,
        August = 8,
        September = 9,
        October = 10,
        November = 11,
        December = 12
}
That's it. How's easy!