Sunday, December 25, 2011

ASP.NET Gridview with custom paging and sorting.

When displaying large amounts of data it's often best to only display a portion of the data, allowing the user to step through the data ten or so records at a time. Additionally, the end user's experience can be enhanced if they are able to sort the data by one of the columns.
While default paging was easy to implement, it carried with it a performance cost since all records to be paged through were being returned from the database. That is, if the DataGrid was paging through a total of 1,000 records, showing 10 records per page, on each and every page request all 1,000 records would be returned from the database, but only the 10 appropriate ones would be displayed.
Custom paging solved this performance issue by requiring the page developer to tell the DataGrid exactly how many total records were being paged through as well as returning the precise subset of records to display on the page. The following example use ObjectDataSource for DAL and Microsoft.Practices.EnterpriseLibrary.Data.dll (download here) to shorten code.

Gridview with custom paging and sorting.
//Here is server control.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
    AllowPaging="True" AllowSorting="True" AlternatingRowStyle-Wrap="True" 
    DataSourceID="ObjectDataSource1" EmptyDataText="There is no data.">
    <RowStyle BackColor="#EFF3FB" />
    <Columns>
        <asp:BoundField HeaderText="No." DataField="No" />
        <asp:BoundField HeaderText="CustomerID" DataField="CustomerID" SortExpression="CustomerID"/>
        <asp:BoundField HeaderText="CompanyName" DataField="CompanyName" SortExpression="CompanyName" />
        <asp:BoundField HeaderText="ContactName" DataField="ContactName" SortExpression="ContactName" />
        <asp:BoundField HeaderText="ContactTitle" DataField="ContactTitle" SortExpression="ContactTitle" />
    </Columns>
    <AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GridDataPage"
    TypeName="DAL" SelectCountMethod="DataRowCount" 
    SortParameterName="SortExpression" EnablePaging="True">
    <SelectParameters>
        <asp:Parameter Name="maximumRows" Type="Int32" />
        <asp:Parameter Name="startRowIndex" Type="Int32" />
        <asp:Parameter Name="SortExpression" Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>
Here is the connection string in web.config and it use sample "Northwind" db (download here) and "Customers" table.
<connectionStrings>
    <add name="sqlConn" providerName="System.Data.SqlClient"  connectionString="Server='.\SQLEXPRESS';uid='xxxxxx';pwd='xxxxxxxx';Database='Northwind';Pooling=False;"/>
</connectionStrings>
Here is the underlying DAL class for ObjectDataSource.
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
public class DAL
{
    // Methods
    private static Database getDatabase()
    {
        Database database = null;
        try
        {
            database = DatabaseFactory.CreateDatabase("sqlConn");
        }
        catch (Exception ex)
        {
            //handle exception here.
        }
        return database;
    }
    public static DataSet GridDataPage(int maximumRows, int startRowIndex, string SortExpression)
    {
        DataSet ds = new DataSet();
        if (startRowIndex >= maximumRows)
        {
            startRowIndex++;
        }
        try
        {
            ds = getGridData(maximumRows, startRowIndex, SortExpression);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                startRowIndex = (startRowIndex > 0) ? startRowIndex : 1;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ds.Tables[0].Rows[i][0] = Convert.ToString((int)(i + startRowIndex));
                }
                HttpContext.Current.Items["rowCount"] = Convert.ToInt32(ds.Tables[1].Rows[0][0].ToString());
                return ds;
            }
            HttpContext.Current.Items["rowCount"] = 0;
        }
        catch (Exception ex)
        {
            //handle exception here.
        }
        return ds;
    }
    public static DataSet getGridData(int maximumRows, int startRowIndex, string SortExpression)
    {
        DataSet ds = new DataSet();
        try
        {
            ds = getDatabase().ExecuteDataSet("GetCustomers", new object[] { maximumRows, startRowIndex, SortExpression });
        }
        catch (Exception ex)
        {
            ds = null;
            //handle exception here.
        }
        return ds;
    }
    public static int DataRowCount(int maximumRows, int startRowIndex, string SortExpression)
    {
        return (int)HttpContext.Current.Items["rowCount"];
    }
}
//Here is transact-sql.
USE [Northwind]
GO
ALTER PROCEDURE [dbo].[GetCustomers]
    @pageSize INT = NULL,
    @pageStart INT = NULL,
    @orderBy nvarchar(200) = NULL
AS
BEGIN

DECLARE @sqlPopulate VARCHAR(2000)
IF @pageSize IS NULL or @pageSize = 0
    SET @pageSize = 10;
IF @pageStart IS NULL
    SET @pageStart = 0;
IF @orderBy IS NULL OR @orderBy = '' 
    SET @orderBy = 'CustomerID DESC';
IF @pageStart = 0
BEGIN
    SET @sqlPopulate = 'SELECT '' '' AS No, CustomerID, CompanyName, ContactName, ContactTitle ' +
        + ' FROM dbo.Customers WHERE CustomerID IN '+
        '(SELECT top '+ CAST(@pageSize AS VARCHAR(10)) +' CustomerID FROM dbo.Customers ';

    SET @sqlPopulate = @sqlPopulate + ' ORDER BY ' + @orderBy +
        ') ORDER BY ' + @orderBy;
END
ELSE
BEGIN
    SET @sqlPopulate = 'SELECT '' '' AS No, CustomerID, CompanyName, ContactName, ContactTitle ' +
        ' FROM Customers WHERE CustomerID IN '+
        '(SELECT top '+ CAST(@pageSize AS VARCHAR(10)) + ' CustomerID FROM Customers WHERE CustomerID NOT IN '+
            '(SELECT top '+ CAST((@pageStart-1) AS VARCHAR(10)) +' CustomerID FROM Customers ';

    SET @sqlPopulate = @sqlPopulate + ' ORDER BY ' + @orderBy +
            ') ORDER BY ' + @orderBy + ') ORDER BY ' + @orderBy;
END
EXEC(@sqlPopulate)

SET @sqlPopulate = '';
SET @sqlPopulate = 'SELECT COUNT(*) FROM Customers';
EXEC (@sqlPopulate)
END 
Useful link:
Microsoft Enterprise Library

Similar Article

That's it. Enjoy!

Friday, December 23, 2011

What is HTML5?

HTML5 will be the new standard for HTML, XHTML, and the HTML DOM.

The previous version of HTML came in 1999. The web has changed a lot since then.

HTML5 is still a work in progress. However, most modern browsers have some HTML5 support.

Some of the most interesting new features in HTML5:
    * The canvas element for drawing
    * The video and audio elements for media playback
    * Better support for local offline storage
    * New content specific elements, like article, footer, header, nav, section
    * New form controls, like calendar, date, time, email, url, search


Original link : http://www.w3schools.com/html5/html5_intro.asp

How to write log using log4net in asp.net.

The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. log4net is a port of the excellent Apache log4j™ framework to the Microsoft® .NET runtime.
This article describes the easy way to be followed for using File Appender of Log4net to write to a text file in a web application day by day.

First of all, get the latest version of log4net library and add reference of it in your project. You can download here : http://logging.apache.org/log4net/download_log4net.cgi.

Add below line in your AssemblyInfo.cs file.
[assembly: log4net.Config.XmlConfigurator(ConfigFile="Web.config", Watch=true)]

Folder where you put log4net











Add below section in Web.Config file.

<configuration>
  <configSections>
    <!-- log4net START here-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
    <!-- log4net STOP here-->
  </configSections>
  <!-- log4net START here-->
  <log4net>
    <root>
      <level value="ALL"/>
      <appender-ref ref="MyTxt"/>
    </root>
    <appender name="MyTxt" type="log4net.Appender.RollingFileAppender">
      <file value="G:\Log_"/>
      <!-- This is file path to save the log. Note : don't put file extension.-->
      <appendToFile value="true"/>
      <datePattern value="yyyy-MM-dd.\tx\t"/>
      <!-- This is date format for file name to save the log.-->
      <rollingStyle value="Date"/>
      <param name="StaticLogFileName" value="false"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%-5thread] %-5level : %logger : %message %timestampms %n"/>
      </layout>
    </appender>
  </log4net>
  <!-- log4net END here-->
  <appSettings>
    <add key="logging" value="Y"/>
    <!-- Here is boolean flag to log or not-->
  </appSettings>
  //Other sections may go here
</configuration>

Add one class Logging.cs file.
public class Logging
{
    public Logging()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public static void logMsg(string msg, ref log4net.ILog log)
    {
         if (ConfigurationManager.AppSettings["logging"].ToString().Equals("Y"))
        {
            //There are seven logging levels.
            log.Error("MyApp : " + msg);
            //log.Fatal("MyApp : " + msg);
            //log.Warn("MyApp : " + msg);
            //log.Info("MyApp : " + msg);
            //log.Debug("MyApp : " + msg);
        }
    }
}

In your code-behind,
//declare private static variable.
private static log4net.ILog log4 = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        String Qs = Request.QueryString["id"].ToString();
        //here cause error when it miss id querystring.
    }
    catch (Exception ex)
    {
        Logging.logMsg(ex.Message, ref log4);
    }
}

when it lead to error every times, it save the error in log file(here may be Log_2011-12-22.txt) and log statement may be similar as below :
2011-12-22 16:37:47,034 [4688 ] ERROR : WebAppBlog._Default : MyApp : Object reference not set to an instance of an object. 534ms

That's it. Thank for reading.

Thursday, December 22, 2011

$(document).ready() vs pageLoad() vs Application.Init

jQuery’s $(document).ready()

    * Ideal for onetime initialization.
    * Optimization black magic; may run slightly earlier than pageLoad().
    * Does not re-attach functionality to elements affected by partial postbacks.

ASP.NET AJAX’s pageLoad()

    * Unsuitable for onetime initialization if used with UpdatePanels.
    * Slightly less optimized in some browsers, but consistent.
    * Perfect for re-attaching functionality to elements within UpdatePanels.

ASP.NET AJAX’s Application.Init

    * Useful for onetime initialization if only ASP.NET AJAX is available.
    * More work required to wire the event up.
    * Exposes you to the “sys is undefined” error if you aren’t careful. For this error, see this post
       http://www.aspmemo.net/2011/12/how-to-solve-sys-is-undefined-error.html


Original Post : http://encosia.com/document-ready-and-pageload-are-not-the-same/

What is jQuery?

jQuery is a library of JavaScript Functions.

jQuery is a lightweight "write less, do more" JavaScript library.

The jQuery library contains the following features:

    * HTML element selections
    * HTML element manipulation
    * CSS manipulation
    * HTML event functions
    * JavaScript Effects and animations
    * HTML DOM traversal and modification
    * AJAX
    * Utilities

More detail : http://www.w3schools.com/jquery/jquery_intro.asp

What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.
AJAX is not a new programming language, but a new way to use existing standards.

AJAX is the art of exchanging data with a server.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes and update parts of a web page, without reloading the whole page.

Note : Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

Useful Link : http://www.w3schools.com/ajax/ajax_intro.asp

Wednesday, December 21, 2011

Google AJAX Feed API

With the AJAX Feed API, you can download any public Atom or RSS feed using only JavaScript, so you can easily mash up feeds with your content and other APIs like the Google Maps API.
The Google AJAX Feed API takes the pain out of developing mashups in JavaScript because you can now mash up feeds using only a few lines of JavaScript, rather than dealing with complex server-side proxies. This makes it easy to quickly integrate feeds on your website.

Google AJAX Feed API Documentation

Feed Examples

Tuesday, December 20, 2011

JQuery : Using events to take effect when the user interacts with the browser

For every onxxx event available, like onclick, onchange, onsubmit, there is a jQuery equivalent. Some other events, like ready and hover, are provided as convenient methods for certain tasks.

Here is CSS and script to put <head> tag.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<style type="text/css">
     .highlight { border: 5px dotted #eee;}
</style>
<script type="text/javascript">
    $(document).ready(function () {
        //go here the following example scripts
    });
</script>

Add the following to <body> tags.
<a name="top" href="#bottom">Go to bottom</a>
<form id="form">
    Form 1
    <input type="text" value="XXX"/>
</form>
<form>
    Form 2
    <input type="text" value="YYY"/>
</form>
<a id="reset" href="#">Reset!</a>
<br />
<a id="clickme" href="http://www.aspmemo.net">Click Me!</a>
<p>This is probably the most common mishap. The remedy is simple--yank! It's most easily done
with two people. One to restrain the bird and the <a href="#"> This is a link. Hover me to
highlight the parent paragraph.</a> other to pull the feather. Use pliers, or a hemostat. Tweezers won't
work on primaries.</p>
<p>This is probably the most common mishap. The remedy is simple--yank! It's most easily done
with two people. One to restrain the bird and the <a href="#"> This is a link. Hover me to
highlight the parent paragraph.</a> other to pull the feather. Use pliers, or a hemostat. Tweezers won't
work on primaries.</p>
<a name="bottom" href="#top">Go to top</a>

One task you often face is to call methods on DOM elements that are not covered by jQuery. Think of a form you would like to reset after you submitted it successfully via AJAX.

$(document).ready(function() {
   // use this to reset a single form
   $("#reset").click(function() {
     $("form")[0].reset();
   });
 });
This code selects the first form element and calls reset() on it. In case you had more than one form, you could also do this:

 $(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset();
     });
   });
 });
This would select all forms within your document, iterate over them and call reset() for each. Note that in an .each() function, this refers to the actual element. Also note that, since the reset() function belongs to the form element and not to the jQuery object, we cannot simply call $("form").reset() to reset all the forms on the page.
The [expression] syntax is taken from XPath and can be used to filter by attributes. Maybe you want to select all anchors that have a name attribute:

$(document).ready(function() {
   $("a[name]").css("background", "#eee" );
 });
This adds a background color to all anchor elements with a name attribute.

More often than selecting anchors by name, you might need to select anchors by their "href" attribute. This can be a problem as browsers behave quite inconsistently when returning what they think the "href" value is. To match only a part of the value, we can use the contains select "*=" instead of an equals ("="):

 $(document).ready(function() {
   $("a[href*='aspmemo']").click(function() {
        alert('Bye JQuery!');
   });
 });
For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed. In addition, you can also select parent elements (also known as ancestors for those more familiar with XPath). Maybe you want to highlight the paragraph that is the parent of the link the user hovers. Try this:

 $(document).ready(function(){
   $("a").hover(function(){
     $(this).parents("p").addClass("highlight");
   },function(){
     $(this).parents("p").removeClass("highlight");
   });
 });
For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed.

Lets shop here. See you.

Useful link : http://www.w3schools.com/jquery/jquery_ref_events.asp

JQuery : Using selectors to get the specific elements

jQuery provides two approaches to select elements. The first uses a combination of CSS and XPath selectors passed as a string to the jQuery constructor (eg. $("div > ul a")). The second uses several methods of the jQuery object. Both approaches can be combined. Let's start here.

Here is CSS and script to put <head> tag.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<style type="text/css">
    .red { background-color: red;}
    .blue { color: blue;}
    .green { color: green; }
</style>
<script type="text/javascript">
    $(document).ready(function () {
        $("#orderedlist").addClass("red");
        $("#orderedlist > li").addClass("blue");
        $("#orderedlist li:last").hover(function () {
            $(this).addClass("green");
        }, function () {
            $(this).removeClass("green");
        });
    });                
</script>

Add the following to the <body>:
<ol id="orderedlist">
    <li>First element</li>
    <li>Second element</li>
    <li>Third element</li>
</ol>
   
To try some of these selectors, we select and modify the first ordered list in our example.
To get started, we want to select the list itself. The list has an ID "orderedlist". In classic JavaScript, you could select it by using document.getElementById("orderedlist"). With jQuery, we did it like this:

 $(document).ready(function() {
   $("#orderedlist").addClass("red");
 });

The example provides a stylesheet with a class "red" that simply adds a red background. Therefore, when you reload the page in your browser, you should see that the ordered list has a red background. I added some more classes to the child elements of this list as below.

 $(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
 });

This selects all child lis of the element with the id orderedlist and adds the class "blue".
Now for something a little more sophisticated: We want to add and remove the class when the user hovers the li element, but only on the last element in the list. So, I inserted them to $(document).ready() like below:

   $("#orderedlist li:last").hover(function() {
     $(this).addClass("green");
   },function(){
     $(this).removeClass("green");
   });

There are many other selectors similar to CSS and XPath syntax.

Full post : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Find_me:_Using_selectors_and_events

Other useful link : http://www.w3schools.com/jquery/jquery_ref_selectors.asp

Monday, December 19, 2011

Hello jQuery / Getting Started with jQuery

We start with an empty html page or .aspx page.This page just loads the .js library (make sure the URL points to where you stored your copy of jquery).As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events as soon as the DOM is ready.
To do this, we register $(document).ready event for the document. Putting an alert into that function does not make much sense, as an alert does not require the DOM to be loaded. So lets try something a little more sophisticated: Show an alert when clicking a link.

Here is script.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
//otherwise, you can use built-in .js file while you use VS 2010.
<script type="text/javascript">
 $(document).ready(function() {
   $("a").click(function() {
     alert("Hello world!");
   });
 });
</script>

//Add the following to the <body>:
<a href="">Link</a>

This should show the alert as soon as you click on the link. Let's have a look at what we are doing: $("a") is a jQuery selector, in this case, it selects all a elements. $ itself is an alias for the jQuery "class", therefore $() constructs a new jQuery object. The click() function we call next is a method of the jQuery object. It binds a click event to all selected elements (in this case, a single anchor element) and executes the provided function when the event occurs.

This is similar to the following code:
<a href="" onclick="alert('Hello world')">Link</a>

The difference is quite obvious: We don't need to write an onclick for every single element. We have a clean separation of structure (HTML) and behavior (JS), just as we separate structure and presentation by using CSS.

Source : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Hello_jQuery

Sunday, December 18, 2011

How to create silde down FAQs using jQuery.

This example will show you how to use jQuery in order to generate easy-to-read and eye-pleasing FAQs, with a slide down effect. we are going to apply a “faq” class to the <dl> element so that it do not affect the other definition lists throughout the page. First of all we need to find and hide all the <dd> elements which are children of any <dl> element with the “faq” class. And then we need to add the toggle effect when a user clicks on a definition title so that when the user clicks on the <dt>, the script navigates the DOM to find the next element (which is going to be the relative <dd>), and it toggles it. You can set the motion’s speed to “slow”, “normal” or “fast”.
FAQs using JQuery

Here is built-in javascript file while you created web site with Visual Studio 2010. Put the below to <head>
tag.
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
Otherwise, you can use the following script reference.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Here is CSS in <head> tag.
<style type="text/css">
    .faq
    {
        margin: 30px;
        background: #d7e7ff;
        padding: 30px 50px 0 30px;
        border: 1px solid #92cdec;
    }
    .faq dt
    {
        font-weight: bold;
        padding: 3px 0 15px 0px;
        position: relative;
        cursor: pointer;
    }
    .faq dd
    {
        padding: 0 0 5px 0px;
        position: relative;
        color: #333;
    }
</style>

Here is javascript to add <head> tag.
<script type="text/javascript">
    $(document).ready(function () {
        $('.faq dd').hide();
        $('.faq dt').click(function () {
            $(this).next().slideToggle('normal');
        });
    });
</script>

Here is form tag.
<form id="form1" runat="server">
    <dl class="faq">
        <dt>Q.How can we check if all the validation control are valid and proper?</dt>
        <dd>A.Using the Page.IsValid () property you can check whether all the validation are done.</dd>
        <dt>Q.If client side validation is enabled in your Web page, does that mean server side code is not run.</dt>
        <dd>A.When client side validation is enabled server emit’s JavaScript code for the custom validators. However,
            note that does not mean that server side checks on custom validators do not execute. It does this redundant
            check two times, as some of the validators do not support client side scripting.
        </dd>
        <dt>Q.How do I send email message from ASP.NET?</dt>
        <dd>A.ASP.NET provides two namespace SystemWEB.mailmessage class and System.Web.Mail.Smtpmail class.</dd>
    </dl>
</form>

That's it what you have to do. Well done!

How to solve "sys is undefined" error while using asp.net ajax update panel.

We have the error "sys is undefined" often when we use asp.net ajax update panel in our ajax enable web site.
The best remedy for this problem is to add the script to the ScriptManager’s Scripts collection and then call our wireups in a Sys.Application.init event handler. It is pretty good practice to separate .js file from source as much as we can.

In .aspx file,
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"
    EnablePartialRendering="true" EnablePageMethods="true">
        <Scripts>
            <asp:ScriptReference Path="Init.js" />
        </Scripts>
    </asp:ScriptManager>
    <br />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
           <%-- your code go here --%>
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

In Init.js file,

//Attach delegate functions to the init event to complete tasks that must
//be performed before objects are created. The add_init accessor binds a
//delegate function to the init event.
Sys.Application.add_init(AppInit);
function AppInit(sender) {  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(End);
}

//The endRequest event is raised after an asynchronous postback is finished
//and control has been returned to the browser. You can use this event to
//provide a notification to users or to log errors.
function End(sender, args) { }

Saturday, December 17, 2011

How to add a client event handler to an ASP.NET control programmatically

You can add client script to controls on an ASP.NET Web page declaratively, as you would to HTML elements (see recent post). Alternatively, you can also add client script events to an ASP.NET Web server control programmatically, which is useful if the event or the code relies on information that is available only at run time. In the page's Init or Load event, call the Add method of the control's Attributes collection. The following code example shows how to add client script to a TextBox control. The client script displays the length of the text in the TextBox control in other TextBox.

Here is form tag.
<form id="form1" runat="server">
     <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    </div>
</form>

In your code-behind,
protected void Page_Load(object sender, EventArgs e)
{
    String displayControlName = TextBox2.ClientID;
    TextBox1.Attributes.Add("onkeyup", displayControlName +
        ".value=" + TextBox1.ClientID + ".value.length;");
}


 That's it. Thank.

How to add a client event handler to an ASP.NET server control declaratively

You can add client script to controls on an ASP.NET Web page declaratively, as you would to HTML elements. In the control's markup, add an attribute for the event, for example, onmouseover or onkeyup. For the attribute's value, add the client script that you want to execute. The following code example shows an ASP.NET Web page that includes client script that changes the button text color when the user passes the pointer over it.
 
Here is javascript.
 <script type="text/javascript">
        var previousColor;
        function MakeRed(e) {
            var targ;
            // e gives access to the event in all browsers
            if (!e) var e = window.event;
            if (e.target) targ = e.target;  //for IE
            else if (e.srcElement) targ = e.srcElement;  //for Firefox
            previousColor = targ.style.color;
            targ.style.color = "#FF0000";

        }
        function RestoreColor(e) {
            var targ;
            if (!e) var e = window.event;
            if (e.target) targ = e.target;
            else if (e.srcElement) targ = e.srcElement;
            targ.style.color = previousColor;
        }
    </script>

 Here is form tag.
<form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button1" onmouseover="MakeRed(event);"
            onmouseout="RestoreColor(event);" />
    </div>
 </form>

See the other example : http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx

Thursday, December 15, 2011

Calling postback event from Javascript in asp.net

Postback is a concept introduced in ASP.NET and is a very handy method. Postback is built into the ASP.NET and .aspx web page support it without writing any statement.
There will be some case where you want to explicitly postback to the server using javascript. It is quite simple to do this.
ASP.NET already creates a client side javascript method as shown below to support Postbacks for the web server controls.

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

So, what you have to do just call this method with appropriate arguments. You can call this as shown below.

<script language='Javascript'>
__doPostBack('__Page', 'YourCustomArgument');
</script>

However, it is not recommended to use this method name directly in the client side. The best approach is, generate this piece of code from the code behind file using ASP.NET. This way, you are safe even if Microsoft later change the name of the method '__doPostBack' to something else in a future release.

Now insert the following code in your .aspx page.

<script type="text/javascript">
    function Jpostback()
    {
        <%= PostBackStr %>
    }
</script>

At runtime, it will be evaluated as:

<script language=’Javascript’>
__doPostBack(‘__Page’, ‘MyCustomArgument’);
</script>

Here is form tag.

<form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Jpostback();" />
</form>

Remember to insert the above script into some Javascript method/event where you want to call the postback, instead of simply inserting into the page as shown above.

To identify and handle the postback in code behind, you need a way to identify your postback in the code behind file. The second argument the doPostback method becomes helpful here.

In your code-behind,

//declare a protected variable
protected string PostBackStr;

//In page load event
protected void Page_Load(object sender, EventArgs e)
{
    /*GetPostBackEventReference() will generate the same piece
    of client side code like __doPostBack that you need to use
    to call the Postback method. */
    PostBackStr = Page.ClientScript.GetPostBackEventReference
    (this, "MyCustomArgument");

    if (Page.IsPostBack)
    {
        String eventArg = Request["__EVENTARGUMENT"];
        if (eventArg == "MyCustomArgument")
        Response.Write("you got it");
    }   
}       

Whenever you press the Button, the page is loaded. To identify it is whether our postback or not, we used the second argument in the __doPostBack method to pass a value and used that in PageLoad to identify (here is "MyCustomArgument").

Original post here

Monday, December 12, 2011

A little about ASP.NET MVC 3 (MVC Overview)

These days, MVC is more popular in enterprise web application environment, since it is easy to develop, flexible to manage and able to control over the rendered HTML for Rich Internet Application (RIA). So, we have to know much about MVC for our career as professional. If you are going to abroad like Singapore to find a job as .net programmer, you need to know MVC at all and it is 7 out of 10 times in interviews. Right now, you see how much it is important in IT industry. Let's start here.

The Model-View-Controller (MVC) pattern is an architectural design principle that separates the components of a Web application. This separation gives you more control over the individual parts of the application, which lets you more easily develop, modify, and test them. ASP.NET MVC is part of the ASP.NET framework. Developing an ASP.NET MVC application is an alternative to developing ASP.NET Web Forms pages; it does not replace the Web Forms model.
The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller.
The MVC framework is defined in the System.Web.Mvc namespace and is a fundamental, supported part of the System.Web namespace.

The MVC framework includes the following components:

Models
. Model objects are the parts of the application that implement the logic for the application s data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server.

Views. Views are the components that display the application s user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Products object.

Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn queries the database by using the values.

The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic) with a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic. For example, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.


Advantages of MVC Model

  • Easier to manage complexity by dividing an application into the models.
  • Enable full control over the rendered HTML.
  • Enable Test Driven Development(TDD).
  • SEO and REST friendly URL (Search Engine Friendly).
  • No ViewState and PostBack events.
  • Follows the stateless nature of web.
  • More easy client-side integration (Javascript/Ajax/Jquery).
  • Extensible and WEB 2.0 Enabled 
The following are the helpful resource.
http://www.asp.net/mvc/mvc3

http://msdn.microsoft.com/en-us/library/gg416514%28v=VS.98%29.aspx

http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-1

Fly on the net with MVC. :P

How to show Confirm message when click Delete button in Gridview

 First of all, you need to know the following javascript methods.

preventDefault method (event) or return false; or returnValue=false;

If an event is cancelable, you can use the preventDefault method and the returnValue property to cancel the event. When an event is canceled, the default action that belongs to the event will not be executed. For example, when the onclick event (the onclick event is cancelable) is canceled for a asp.net server control such as button, then clicking on the Button does not occur autopostback.
The properties and methods mentioned above do not affect the propagation of events. If you need to prevent the propagation of an event in the DOM hierarchy or in asp.net ajax update panel or in page using master page, use the cancelBubble property and the stopPropagation method.

cancelBubble property (event) or stopPropagation method

When an event can bubble up, you can stop its propagation with the cancelBubble property or the stopPropagation method. Use the stopPropagation method in Firefox, Opera, Google Chrome and Safari, because the cancelBubble property is deprecated in those browsers. Internet Explorer also supports the stopPropagation method from version 9. In Internet Explorer before version 9, use the cancelBubble property, because the stopPropagation method is not supported. 

In .aspx,
//javascript is here.
function DeleteConfirm(e) {
    if (confirm('Are you sure to submit?')) {
        return true;
    }
    else {
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
            return false; // or returnValue=false; or e.preventDefault();
    }       
}

 //server control is here.
 <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
    DataKeyNames="id"
    onrowcommand="GridView1_RowCommand"
    onrowcreated="GridView1_RowCreated">
    <Columns>
        <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False"
            ReadOnly="True" SortExpression="id" />
        <asp:BoundField DataField="title" HeaderText="title" SortExpression="title" />
        <asp:TemplateField HeaderText="View">
            <ItemTemplate>
                <asp:Button ID="btnDelete" runat="server" CommandArgument='<%# Eval("id") %>'  CommandName="DeleteRow"
                    Text="Delete" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
 
In code-behind,

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName == "DeleteRow")
    {
        // Coding here
    }
}

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Button btn = e.Row.FindControl("btnDelete") as Button;
        btn.OnClientClick = "return DeleteConfirm(this);";
    }
}
   
Enjoy the programming!

Saturday, December 10, 2011

Implicitly Typed Local Variables (var keyword)

You can use implicitly typed local variables whenever you want the compiler to determine the type of a local variable.
The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.
It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.

The below examples show different ways in which local variables can be declared with var:

// i is compiled as an int
var i = 5;

// s is compiled as a string
var s = "Hello";

// a is compiled as int[]
var a = new[] { 0, 1, 2 };

// expr is compiled as IEnumerable
// or perhaps IQueryable
var expr = from c in customers where c.City == "London" select c;

// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };

// list is compiled as List
var list = new List();

The var keyword may be used in the following cases as well:

* On local variables (variables declared at method scope) as shown in the previous example.

* In a for initialization statement.

for(var x = 1; x < 10; x++)

* In a foreach initialization statement.

foreach(var item in list){...}

* In a using statement.

using (var file = new StreamReader("C:\\myfile.txt")) {...}

Enjoy the programming! :)

Recursion function in JavaScript

Recursion is an important programming technique. It is used to have a function call itself from within itself. One example is the calculation of factorials. The factorial of 0 is defined specifically to be 1. The factorials of larger numbers are calculated by multiplying 1 * 2 * ..., incrementing by 1 until you reach the number for which you are calculating the factorial.
Here is the factorial function again, this time written in JavaScript code with asp.net. If the number is less than zero, reject it. If it is not an integer, round it down to the next integer. If the number is zero, its factorial is one. If the number is larger than zero, multiply it by the factorial of the next lesser number.

Here is javascript.
<script type="text/javascript">
function factorial(aNumber)
{
    // If the number is not an integer, round it down.
    aNumber = Math.floor(aNumber);
    // If the number is less than 0, reject it.
    // If the number is 0, its factorial is 1.
    // Otherwise, call this recursive procedure again.
    if (aNumber < 0)
    {
       return -1;
    }
    else if (aNumber == 0)
    {
      return 1;
    }
    else
    {
      return (aNumber * factorial(aNumber - 1));
    }
}
function Calculate()
{
    var num = $get('<%=txtNum.ClientID%>');
    var dis = $get('lblDisplay');
    dis.innerText = factorial(num.value);
}
</script>

 
Form tag go here.
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:Button ID="btnCal" runat="server" Text="Calculates a factorial" OnClientClick="javascript:Calculate();return false;"/>
        <asp:TextBox ID="txtNum" runat="server"></asp:TextBox>
        <asp:Label ID="lblDisplay" runat="server" Text=""></asp:Label>
    </div>
</form>

I use here ASP.NET AJAX $get method to get the value of textbox and it is safe to use asp.netcontrol.ClientID for asp.net server control. I have to put ScriptManager since I used $get method. Moreover, make sure that it use innerText property for Label. Thank.

Note : it is also important for some interview (due to my experience) :P