Monday, June 30, 2008

C# 3.0 : Convert DataView to DataTable

Convert data from DataView to DataTable in C# 3.0. Use the following method which convert the dataview to datatable.

The var is all about type inference, it’s important to remember this is still static typing. The var keyword informs the compiler that it should try and infer the type of variable; if it can not do this a compile error is generated. One very important aspect of the var keyword is that it can only be used with local variables, and even then are a few cases that are not allowed.

In this below example I used this var keyword instead of specific datatype declared.




   public static DataTable ConvertDataViewToDataTable(DataView dataView)
{
// check whether passed dataview is null or not.
if (null == dataView)
{
throw new ArgumentNullException("DataView", "Null or Invalid DataView");
}


// Create table structure from dataview by using Clone().
var newDataTable = dataView.Table.Clone();
var index = 0;


// Create the same number of column.
var strColNames = new string[newDataTable.Columns.Count];


// Add the column names to datatable.
foreach (DataColumn col in newDataTable.Columns)
{
strColNames[index++] = col.ColumnName;
}


// Fetch all rows from dataview to Enumerator.
var viewEnumerator = dataView.GetEnumerator();


while (viewEnumerator.MoveNext())
{
var dataRowView = (DataRowView)viewEnumerator.Current;


// Create new datarow and fill the values init from dataview.
var dataRow = newDataTable.NewRow();


foreach (var strName in strColNames)
{
dataRow[strName] = dataRowView[strName];
}


// Add the new datarow to the datatable.
newDataTable.Rows.Add(dataRow);


} // while loop end


// Return the created datatable.
return newDataTable;
}


Happy codings!!!

Monday, June 16, 2008

How to improve performance of our web sites


Here's a list which are recommendated for improving front-end performance of a website:

The Exceptional Performance team has identified a number of best practices for making web pages fast inYahoo. The list includes 34 best practices divided into 7 categories.

1. Page Content

  • Make Fewer HTTP RequestsReduce
  • DNS Lookups
  • Avoid Redirects
  • Make Ajax Cacheable
  • Post-load Components
  • Preload Components
  • Reduce the Number of DOM Elements
  • Split Components Across Domains
  • Minimize the Number of iframes
  • No 404s

2. Server Operation

  • Use a Content Delivery Network
  • Add an Expires or a Cache-Control Header
  • Gzip Components
  • Configure ETags
  • Flush the Buffer Early
  • Use GET for AJAX Requests

3. Cookies

  • Reduce Cookie Size
  • Use Cookie-free Domains for Components

4. CSS

  • Put Stylesheets at the Top
  • Avoid CSS Expressions
  • Make JavaScript and CSS External
  • Minify JavaScript and CSS
  • Choose <link> over @import
  • Avoid Filters

5. Java Script

  • Put Scripts at the Bottom
  • Make JavaScript and CSS External
  • Minify JavaScript and CSS
  • Remove Duplicate Scripts
  • Minimize DOM Access
  • Develop Smart Event Handlers

6. Images

  • Optimize Images
  • Optimize CSS Sprites
  • Don't Scale Images in HTML
  • Make favicon.ico Small and Cacheable

7. Mobile

  • Keep Components under 25K
  • Pack Components into a Multipart Document

I got this short list from the book "OReilly High Performance Web Sites" by Steve Souders, Chief Performance Yahoo. Download ebook here.

Happy Programming!!!

Monday, June 9, 2008

AJAX and WebServices in ASP.NET 3.5


Introduction

This article explains the use of webservices in ASP.NET 3.5 AJAX environment and it tells how to call web service methods from a client-side javascript. It also outlines the new System.Web.Script namespace and explores the ways of defining the client-call to a web service method.

Calling WebService methods in AJAX

To improve the web user experience, the AJAX functionality of ASP.NET has included in its new version, new ways of calling the web service methods from client-side javascript. Without submitting or rendering a whole page, AJAX enables you to call a server-side method with no post-back.

The client script can make a request to a web method and pass data as input parameters to the method; and data can also be sent back to the client browser from the server.

To enable your application to call ASP.NET Web services by using client script, the server asynchronous communication layer automatically generates JavaScript proxy classes. A proxy class is generated for each Web service for which an <asp:servicereference> element is included under the <asp:ScriptManager> control in the page.

<asp:ScriptManager runat="server" ID="scriptManagerId">
<Scripts>
<asp:ScriptReference Path="CallWebServiceMethods.js" />
</Scripts>

<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
<asp:ScriptManager runat="server" ID="scriptManagerId">

This proxy class is downloaded to the browser at page load time and provides a client object that represents
the exposed methods of a Web service. To call a method of the Web service, you call the corresponding method of the generated JavaScript proxy class. The proxy class in turn communicates with the Web service. The requests are made asynchronously, through the XMLHTTP object of the browser.

<asp:scriptreference"> element is specified to register a javascript file that is to be used in a web page. Only after registering the CallWebServiceMethod.js file, you can call methods on it.

Calling a Web service method from script is asynchronous. To get a return value or to determine when the request has returned, you must provide a succeeded callback function. The callback function is invoked when the request has finished successfully, and it contains the return value (if any) from the Web method call. You can also provide a failed callback function to handle errors. Additionally, you can pass user context information to use in the callback functions.


JSON – JavaScript Object Notation is the default serialization format using which data transformation takes place between client-server requests. You may disable all currently enabled protocols like HTTP-GET, HTTP-POST, and even XML-SOAP formatting used in the earlier forms of web services. The following settings in the Web.Config file just do the same.

<system.web>

<webServices>

<protocols>

<clear/>

</protocols>

</webServices>

</system.web>


The figure below shows in detail the different layers that lays on both the client and server sides. A request to a web service method passes through these layers. You can see how a method is called on to one of the available proxy object and the web request is handled by an XmlHttp object on the client browser side. On the server side, your request is handled by an HTTP handler as usual and sent for XML/JSON serialization.




Example: Consuming WebService methods in AJAX
Consuming web service methods in AJAX involves two steps. The first step is that there is a slight change in the way you create and define web services. Making calls using client script from a page to the service methods will be the second step.

Step 1: Creating a web service
In the System.Web.Scripts.Services namespace, you may find an attribute class "ScriptSrvice" and this need to be applied to a webservice class so that the web service methods can be invoked from the client script. This would enable the proxy generation script to generate a proxy object that corresponds to the webservice class.

Similarly, in the same namespace, you may find another attribute class "ScriptMethod" and upon applying this attribute to a web method you can specify which HTTP verb is used to invoke a method and the format of the response. This attribute has three parameters described as below:

UseHttpGet: Setting it to true will invoke the method using the HTTP GET command. The default is false. ResponseFormat: Specifies whether the response will be serialized as JSON or as XML. The default is Json.

XmlSerializeString: Specifies whether all return types, including string types, are serialized as XML. The value of the XmlSerializeString property is ignored when the response is serialized as JSON.

Ok... Now, create a new Web Site using the ASP.NET Web Service template in Visual Studio 2008 and modify the webservice class as below.


using System.Web.Script.Services;
namespace AjaxWebService

{
[WebService(Namespace = "http://localhost:49232/AjaxWebService/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class Service : System.Web.Services.WebService
{
string myXmlData = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Book>
<Title>Programming ASP.NET 3.5, AJAX and Web Services</Title>

</Book>";
// This method uses JSON response formatting
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public string getNextBackupDate(int months)
{
return DateTime.Now.AddMonths(months).ToShortDateString();
}


// This method uses XML response formatting
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
[WebMethod]
public string Greetings(string name)
public XmlDocument GetBookTitle()

{
XmlDocument xmlDoc = new XmlDocument();

xmlDoc.LoadXml(myXmlData);
return xmlDoc;
}


// This method uses HTTP-GET protocol to call it

[ScriptMethod(UseHttpGet = true)]
[WebMethod]
public string HelloWorld()

{
return "Hello, world";
}
}

}
Note: The web service created with ScriptService enabled as above will not be tested on the browser by default. You need to modify the settings in the Web.Config file as below to test the above webservice.

<webservices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webservices>

Step 2: Call web service methods using Client Script

Asp.Net Web Service methods can be called from client scripts asynchronously without a postback and without refreshing the full page. Only data is transferred between the server and client browser.

Currently, .NET framework 3.5 supports the web service and client web page available in the same domain (same web site). You cannot call web service methods residing on the Internet or any other system using the VS 2008 Beta 2.

Now add a new “Ajax Enabled Web Page” to the existing web service project and add the controls to the web page as specified in the mark-up below.

Write javascript functions to call the web service methods and callback methods. Calls to Web service methods are made by using the proxy class and a list of parameters, name of the succeeded callback function, the failed callback function, and the user context is passed as additional parameters in the call.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AJAX Web Form</title>
<script type="text/javascript">
function CallNextDate()
{
AjaxWebService.Service.getNextBackupDate(1, OnSucceeded);
}

function CallHelloWorld()
{
AjaxWebService.Service.HelloWorld(OnSucceeded);
}

function CallBookTitle()
{
AjaxWebService.Service.GetBookTitle(OnSuccess, OnFail, "XmlDocument");
}

// This is the callback function that processes the Web Service return value in JSON format.
function OnSucceeded(result)
{
var myresult = document.getElementById("Text1");
myresult.value = result;
}

// This is the callback function that processes the Web Service return value in XML format.
function OnSuccess(result)
{
var myresult = document.getElementById("Text1");
myresult.value = "Title: " + result.documentElement.text;
}

// This is the callback function that processes the Web Service return value in XML format.
function OnFail(error)
{
var myresult = document.getElementById("Text1");
myresult.value = "Service Error: " + error.get_message();
}
</script>

<style type="text/css">
#Text1
{
width: 375px;
}
#Button2
{
width: 140px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service.asmx"/>
</Services>
</asp:ScriptManager>
<br />
Result: <input id="Text1" type="text" /><br />
<br />
<input id="Button1" type="button" value="Get Server Time" onclick="CallNextDate()" />
<input id="Button2" type="button" value="Say Hello World" onclick="CallHelloWorld()" />
<input id="Button3" type="button" value="Get Book Title" onclick="CallBookTitle()" />
</div>
</form>
</body>
</html>



In the above markup, notice how the path attribute in the ServiceReference element of the ScriptManager control points to the web service class. This enables the Web service method to be called from script in the default.aspx page. The inline functions CallNextDate, CallHelloWorld, CallBookTitle are used to call the three web service methods. OnSuccess and OnFail methods are callback methods that get executed as the webservice method execution gets over.

In order to make the client web page working, you need to add the following settings to the Web.Config file.

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>

<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>

</assemblyBinding>
</runtime>

This would redirect the ASP.NET engine to load the current version 3.5 of System.Web.Extensions.dll and other dlls to exploit the built-in AJAX support in ASP.NET 3.5.

Conclusion:

The ASP.NET 3.5 along with the in-built AJAX client-server framework has increased the power of using client scripts to call webservice methods. Most of the settings and javascript code files are loaded automatically when you use Visual Studio 2008. Calling web service methods in the earlier versions of AJAX, ATLAS has few troubles that make the development and debugging little difficult. Now, with ASP.NET 3.5, it has become an inherent part of the much simpler and familiar VS 2008 IDE.

Happy Programming!!!

The tools for web developers

The following is a collection of some useful cost-free tools for web developers.

You wouldn't publish a book without spell-checking it, and you shouldn't publish a webpage without validating it. The following tools will scan your page and give a detailed summary of the errors they find.

  • CSS Validator
    developed by the same organization that created and standardized the CSS language, is the most used and most reliable CSS validator available. It's a free and open source web-based tool that will scan your CSS source and explain any lexical or syntactic errors it finds.

  • HTML Validator
    developed by the same organization that standardized the HTML language, is the most used and most reliable HTML validator available. It's a free and open source web-based tool that will scan your HTML or XHTML source and explain any lexical, syntactic, or structural errors it finds.

  • Link Checker
    developed by the same organization that standardized the HTML and HTTP languages, is a free and open source web-based tool that will scan your website and report any broken links it finds, as well as other relevant information. You may specify an arbitrary number of pages deep to check.

  • Link Checker
    developed by the same organization that standardized the HTML and HTTP languages, is a free and open source web-based tool that will scan your website and report any broken links it finds, as well as other relevant information. You may specify an arbitrary number of pages deep to check.


Here are some useful web development extensions for the Mozilla Firefox web browser.

  • ColorZilla
    is a little tool that sits in your statusbar and offers an eyedropper, color picker, and rudimentary full-page zoom settings. It's useful for quickly grabbing and comparing colors on a webpage. The full-page zoom settings resize the text and images, but backgrounds and other stylistic aspects are left the same.

  • ColorZilla
    is a little tool that sits in your statusbar and offers an eyedropper, color picker, and rudimentary full-page zoom settings. It's useful for quickly grabbing and comparing colors on a webpage. The full-page zoom settings resize the text and images, but backgrounds and other stylistic aspects are left the same.

  • Firebug
    made by the creator of the DOM Inspector, is a powerful and easy-to-use tool for debugging scripts. It includes three main features: a console which lists errors and allows you to execute any arbitrary JavaScript code at any time in the scope of the webpage itself; a debugger which shows you all of the JavaScript source with errors highlighted; and an inspector which allows you to navigate the page's DOM, element styles, computed layout, and associated events.


    Here are some useful web development add-ons for the Internet Explorer web browser.
  • Developer Toolbar
    developed by Microsoft, is the closest thing you'll get to Firefox's Web Developer extension and DOM Inspector in Internet Explorer. It was clearly designed to be familiar to people who have used the Web Developer extension, with most of the same features organized in the same way. It doesn't yet offer live CSS and HTML editing, arguably the most useful features in the Web Developer extension, but it does have a DOM inspector (also modeled after the Firefox equivalent) and an eyedrop color picker, though it doesn't yet have a spectrum color picker. The Developer Toolbar is available for Internet Explorer 6 and 7 with no cost.

    Use the technology!!!

Spry Framework for Ajax

Spry is a JavaScript-based framework that enables the rapid development of Ajax-powered web pages. Not a JavaScript guru? No problem. Spry was designed to feel like an extension of HTML and CSS, so anyone with basic web-production skills can create next-generation web experiences by adding the power of Ajax to their pages.

Spry can be used with any server-side technology (ColdFusion, PHP, ASP.Net etc.). By building the front-end of your web application with Spry you enable a more efficient designer-developer workflow by keeping UI separated from back-end application logic.

For more information and demo read here

Feel the technology!!!