Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for the ‘CodeProject’ Category

No more pain to configure WCF 4 services

Posted by Ramani Sandeep on November 18, 2011

Developer who has worked with ASP.NET Web Services (ASMX) and WCF always feels that using predecessor was much more easier. It just because WCF configuration is much more complex as compare to ASP.NET Web Service.

WHY ??????

With ASMX, you were able to define a [WebMethod] operation and the runtime automatically provided a default configuration for the underlying communications. When moving to WCF 3.x, on the other hand, developers have to know enough about the various WCF configuration options to define at least one endpoint.

In an effort to make the overall WCF experience just as easy as ASMX, WCF 4 comes with a new “default configuration” model that completely removes the need for any WCF configuration. If you don’t provide any WCF configuration for a particular service, the WCF 4 runtime automatically configures your service with some standard endpoints and default binding/behavior configurations. This makes it much easier to get a WCF service up and running, especially for those who aren’t familiar with the various WCF configuration options.

Let’s discuss some of the standard configuration options that WCF 4 support :

1) Default Endpoints
2) Default Protocol Mapping
3) Default Binding Configurations
4) Default Behavior Configurations

1) Default Endpoints

With WCF 3.X, if you try to host a service without configured endpoints, ServiceHost instance will throw an exception informing you that you need to configure at least one endpoint. With WCF 4, this is no longer the case because the runtime automatically adds one or more ‘default endpoints’ for you.

Now question comes in mind, How this is done by WCF 4?

Answer to Question is like : When Host application calls Open method on ServiceHost instance, it build internal service description from the application configuration file. Than it check the count of configured endpoints. if it is still zero than it will call “AddDefaultEndpoints” public method and method will adds one default endpoint per base address for each service contract implemented by the service.

Clear or Confused ??

Lets take one example to be more clear on it.

If the service implements two service contracts and you configure the host with a single base address, AddDefaultEndpoints will configure the service with two default endpoints (one for each service contract). However, if the service implements two service contracts and the host is configured with two base addresses (one for HTTP and one for TCP), AddDefaultEndpoints will configure the service with four default endpoints.

I Hope now its clear….if still not…please go thru the link provided for more details on it.

-> New Features in WCF 4 that Will Instantly Make You More Productive
(http://www.code-magazine.com/Article.aspx?quickid=1006061)

2) Default Protocol Mapping

In .Net 4.0 framework, default protocol mapping between transport protocol schemes and the built in WCF bindings are as follows :


   <protocolMapping>
      <add scheme="http" binding="basicHttpBinding" bindingConfiguration="" />
      <add scheme="net.tcp" binding="netTcpBinding" bindingConfiguration=""/>
      <add scheme="net.pipe" binding="netNamedPipeBinding" bindingConfiguration=""/>
      <add scheme="net.msmq" binding="netMsmqBinding" bindingConfiguration=""/>
   </protocolMapping>

You can override these mappings at machine level by adding this section to machine.config file and modify the bindings as per your needs.

If you want to override this mappings at application level than you can override the above section in application/web configfile.

3) Default Binding Configurations

In WCF 3.x , binding can be done like this :


<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicBindingMtom" messageEncoding="Mtom"/>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="HelloService">
        <endpoint address="mtom" binding="basicHttpBinding"
                  bindingConfiguration="BasicBindingMtom"
                  contract="IHello"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>

Here “BasicBindingMtom” binding configuration overrides the defaults for BasicHttpBinding by changing the message encoding to “Mtom”. However this binding will effect only when you apply it to a specific endpoint thru “bindingConfiguration” attribute.

With WCF 4, binding can be done like this :


      <basicHttpBinding>
        <binding messageEncoding="Mtom"/>
      </basicHttpBinding>

No name attribute required. This feature gives you a simple mechanism to define a standard set of binding defaults that you can use across all your services without imposing any complexities of binding configurations.

4) Default Behavior Configurations

With WCF 4, it is possible to define default behavior configurations for services and endpoints.


    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

Above configuration turns on the metadata for any service that doesn’t come with explicit behavior configuration.

In WCF 4, Behavior configuration also support inheritance model. It means that if application defines a behavior using same name as one already defined in machine.config, the application specific behavior configuration will get merged with machine configuration.

With these new additions in the WCF 4, it will be easier for developers to configure the services. I am sure that many developers will feel relaxed by having these new features in WCF and also start using it. Thats all from my side for this post.

Hope this will help !!!

Jay Ganesh ……

Posted in CodeProject, WCF, Web Services | Tagged: , , , , , , , , | 2 Comments »

DataContract Vs MessageContract

Posted by Ramani Sandeep on October 19, 2011

1. Comparison:

Data Contracts:

WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service.

you can say “Data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged”. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Message Contracts:

Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Whereas data contracts enable interoperability through the XML Schema Definition (XSD) standard, message contracts enable you to interoperate with any system that communicates through SOAP.

Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.

2. Why use MessageContract when DataContract is there?

Data contracts are used to define the data structure. Messages that are simply a .NET type, lets say in form of POCO (plain old CLR object), and generate the XML for the data you want to pass.

Message contracts are preferred only when there is a need to “control” the layout of your message(the SOAP message); for instance, adding specific headers/footer/etc to a message.

sometimes complete control over the structure of a SOAP message is just as important as control over its contents. This is especially true when interoperability is important or to specifically control security issues at the level of the message or message part. In these cases, you can create a message contract that enables you to use a type for a parameter or return value that serializes directly into the precise SOAP message that you need.

3. Why we use MessageContract to pass SOAP headers ?

Passing information in SOAP headers is useful if you want to communicate information “out of band” from the operation signature.

For instance, session or correlation information can be passed in headers, rather than adding additional parameters to operations or adding this information as fields in the data itself.

Another example is security, where you may want to implement a custom security protocol (bypassing WS-Security) and pass credentials or tokens in custom SOAP headers.

A third example, again with security, is signing and encrypting SOAP headers, where you may want to sign and/or encrypt some or all header information. All these cases can be handled with message contracts. The downside with this technique is that the client and service must manually add and retrieve the information from the SOAP header, rather than having the serialization classes associated with data and operation contracts do it for you.

4. Can’t mix datacontracts and messagecontracts.

Because message-based programming and parameter-based programming cannot be mixed, so you cannot specify a DataContract as an input argument to an operation and have it return a MessageContract, or specify a MessageContract as the input argument to an operation and have it return a DataContract. You can mix typed and untyped messages, but not messageContracts and DataContracts. Mixing message and data contracts will cause a runtime error when you generate WSDL from the service.

Hope this will help !!!

@@@ Happy Diwali @@@

Posted in CodeProject, WCF, Web Services | Tagged: , , , , | Leave a Comment »

ServiceContractGenerator vs ServiceDescriptionImporter

Posted by Ramani Sandeep on October 13, 2011

Recently, I have worked with WCF. During this , I have developed one tool that help us to run any web service (.asmx) and wcf service (.svc) by just using URL of it. It was totally dynamic process. In this process, I have learn how to fetch method list , parameter names and how to invoke method dynamically. During this process I came across the terms called ServiceDescriptionImporter and ServiceContractGenerator. So I feel that I should share what these terms means and difference between them with my readers. so here it goes…

ServiceDescriptionImporter :

The ServiceDescriptionImporter class allows you to easily import the information contained in a WSDL description into a System.CodeDom.CodeCompileUnit object.

By adjusting the value of the Style parameter, you can instruct a ServiceDescriptionImporter instance either to generate a client proxy class that provides the functionality of the Web service by transparently calling it or to generate an abstract class that encapsulates the functionality of the Web service without implementing it.

The code in the resulting CodeCompileUnit object can then either be called directly or exported in the language of your choice.

ServiceContractGenerator:

The System.ServiceModel.Description.ServiceContractGenerator type generates service contract code and binding configurations from System.ServiceModel.Description.ServiceEndpoint description objects.

ServiceContractGenerator vs ServiceDescriptionImporter:

–>ServiceDescriptionImporter is the class that is used by the “Add Web Reference” dialog in VS and the “wsdl.exe” tool in the SDK to generate “asmx” style client web service proxies.

ServiceContractGenerator is the WCF equivalent, for the “Add Service Reference” dialog in VS and the “svcutil.exe” tool in the SDK.

–> ServiceDescriptionImporter uses the asmx client infrastructure (System.Web.Services.Protocols.SoapHttpClientProtocol and friends).

ServiceContractGenerator uses the WCF client infrastructure (System.ServiceModel.ClientBase and friends).

Hope this will help !!!

Posted in CodeProject, WCF, Web Services | Tagged: , , | Leave a Comment »

Tips/Tricks – Hide popup when click on background part

Posted by Ramani Sandeep on March 5, 2011

Whenever we use ajax ModalPopupExtender to show popup window, we always get into the situation where we need to hide the popup based on background click. CancelControlID property helps to close popup by clicking on control specified in it. But what if we required to close it by clicking background of popup? So here is some workaround to achieve it.

The modal popup extender automatically creates a div HTML element that is used for the background. so we can hide the popup by :

  1. Fetching the background div ID and
  2. Add one event handler (click) to that div

Once we follow two steps , we can able to hide the popup on background click. I hope this is simple. so Lets start…

How to fetch div HTML element used for the background :

To get the ID of the background div, add “_backgroundElement” to the name of your ModalPopupExtender runtime ID. Why, because modal popup extender automatically creates a div HTML element with ID which contains :

ModalPopupExtender ID + “_backgroundElement”

i.e. “ctl00_mpeTest_backgroundElement” , here mpeTest is our ModalPopupExtender’s ID

Now our task to fetch that div ID, here is the jQuery code that can help us to achieve it :

   var modalWindow = '<%= mpeTest.ClientID %>';
   var backgroundElement = $get(modalWindow + '_backgroundElement');

Here ‘mpeTest‘ is the ID of ModalPopupExtender.

Add event handler to the background div :

Here is the code to add click event to backgroundElement :

  var modalWindow = '<%= mpeTest.ClientID %>';
  var backgroundElement = $get(modalWindow + '_backgroundElement');
  $addHandler(backgroundElement, 'click', hideModalPopupViaClient);

hideModalPopupViaClient‘ is the javascript function name which will be called when we click on background of the popup window.

Example :

Here is the complete listing with all part of code along with css, javascript and ASPX page code with controls used in it.

Listing #1 : style sheet classes used for modalpopup and its background


 <style>
        .modalBackground
        {
            background-color: gray;
            filter: alpha(opacity=70);
            -moz-opacity: 0.70;
            opacity: 0.70;
        }
        .modalPopup
        {
            background-color: #fff;
            border-width: 1px;
            border-style: solid;
            border-color: #000;
            width: auto;
            height: auto;
            text-align: center;
        }
    </style>

Listing #2 : jQuery script specify how we can show/hide modalpopup


 <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        function ShowPopup() {

            //show modal popup window
            var modalWindow = '<%= mpeTest.ClientID %>';
            $find(modalWindow).show();

            //add event handler to hide the modal popup when user click background of the popup window
            var backgroundElement = $get(modalWindow + '_backgroundElement');
            if (backgroundElement) $addHandler(backgroundElement, 'click', hideModalPopupViaClient);

            return false;
        }

        function hideModalPopupViaClient() {

            //hide modal popup window
            var modalPopupBehavior = $find('<%= mpeTest.ClientID %>');

            if (modalPopupBehavior) {
                modalPopupBehavior.hide();
            }
        }
    </script>

I have given enough explaination in above section , so no need to describe it again.

Listing #3 : ASPX page content , where I have taken ModalPopupExtender and set few property of it to let it work.


<ajaxtoolkit:ToolkitScriptManager ID="scriptManager" runat="server"></ajaxtoolkit:ToolkitScriptManager>

<asp:ImageButton ID="imgBtnTour" runat="server" ImageUrl="~/Images/movie_icon.jpg"
            Width="80" OnClientClick="return ShowPopup();" />

<asp:Button runat="server" ID="btnHiddenPopUp" Style="display: none" />

<ajaxtoolkit:ModalPopupExtender ID="mpeTest" runat="server" TargetControlID="btnHiddenPopUp"
            PopupControlID="panSaving" BackgroundCssClass="modalBackground" DropShadow="true"
            RepositionMode="RepositionOnWindowResize" CancelControlID="imgClose" />

<asp:Panel runat="server" CssClass="modalPopup" ID="panSaving" Style="display: none">
    	<table cellpadding="0" cellspacing="0" border="0">
         	<tr>
                    <td style="padding: 5px 5px 0px 0px" align="right">
                        <asp:Image ID="imgClose" runat="server" ImageUrl="~/Images/close.png" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <h1>
                            This is modal popup message</h1>
                    </td>
                </tr>
            </table>
</asp:Panel>

Thats it !!!

Hope this will help !!!

Jay Ganesh

Posted in Ajax Toolkit, CodeProject, JQuery, Tips and Tricks | Tagged: , , , , | 1 Comment »

Parallelism in .NET – PLINQ

Posted by Ramani Sandeep on February 10, 2011

Introduction

Most .NET developers today are familiar with LINQ, the technology that brought functional programming ideas into the object-oriented environment. Parallel LINQ, or ‘PLINQ’, takes LINQ to the next level by adding intuitive parallel capabilities onto an already powerful framework.

PLINQ is a query execution engine that accepts any LINQ-to-Objects or LINQ-to-XML query and automatically utilizes multiple processors or cores for execution when they are available. The change in programming model is tiny, meaning you don’t need to be a concurrency guru to use it.

Using PLINQ is almost exactly like using LINQ-to-Objects and LINQ-to-XML. You can use any of the operators available through C# 3.0 syntax or the System.Linq.Enumerable class, including OrderBy, Join, Select, Where, and so on.

LINQ-to-SQL and LINQ-to-Entities queries will still be executed by the respective databases and query providers, so PLINQ does not offer a way to parallelize those queries. If you wish to process the results of those queries in memory, including joining the output of many heterogeneous queries, then PLINQ can be quite useful.

Using AsParallel method :

The AsParallel method is the doorway to PLINQ. It converts data sequence into a ParallelQuery. The LINQ engine detects the use of a ParallelQuery as the source in a query and switches to PLINQ execution automatically. You are likely to use the AsParallel method every time you use PLINQ.

Sample code 1 : Sequential LINQ execution


	var customers = new[] {
		new Customer { ID = 1,  FirstName = "Sandeep"  , LastName = "Ramani" },
		new Customer { ID = 2,  FirstName = "Dharmik"  , LastName = "Chotaliya" },
		new Customer { ID = 3,  FirstName = "Nisar"    ,  LastName = "Kalia" } ,
		new Customer { ID = 4,  FirstName = "Ravi"     , LastName = "Mapara" } ,
		new Customer { ID = 5,  FirstName = "Hardik"   , LastName = "Mistry" }
		new Customer { ID = 6,  FirstName = "Sandy"    , LastName = "Ramani" },
		new Customer { ID = 7,  FirstName = "Jigar"    , LastName = "Shah" },
		new Customer { ID = 8,  FirstName = "Kaushal"  , LastName = "Parik" } ,
		new Customer { ID = 9,  FirstName = "Abhishek" , LastName = "Swarnker" } ,
		new Customer { ID = 10, FirstName = "Sanket"   , LastName = "Patel" }
		new Customer { ID = 11, FirstName = "Dinesh"   , LastName = "Prajapati" },
		new Customer { ID = 12, FirstName = "Jayesh"   , LastName = "Patel" },
		new Customer { ID = 13, FirstName = "Nimesh"   , LastName = "Mishra" } ,
		new Customer { ID = 14, FirstName = "Shiva"    , LastName = "Reddy" } ,
		new Customer { ID = 15, FirstName = "Jasmin"   , LastName = "Malviya" }
		new Customer { ID = 16, FirstName = "Haresh"   , LastName = "Bhanderi" },
		new Customer { ID = 17, FirstName = "Ankit"    , LastName = "Ramani" },
		new Customer { ID = 18, FirstName = "Sanket"   , LastName = "Shah" } ,
		new Customer { ID = 19, FirstName = "Amit"     , LastName = "Shah" } ,
		new Customer { ID = 20, FirstName = "Nilesh"   , LastName = "Soni" }       };

	var results = from c in customers
		      where c.FirstName.StartsWith("San")
		      select c;

Sample code 2 : Parallel LINQ execution


	var customers = new[] {
		new Customer { ID = 1,  FirstName = "Sandeep"  , LastName = "Ramani" },
		new Customer { ID = 2,  FirstName = "Dharmik"  , LastName = "Chotaliya" },
		new Customer { ID = 3,  FirstName = "Nisar"    ,  LastName = "Kalia" } ,
		new Customer { ID = 4,  FirstName = "Ravi"     , LastName = "Mapara" } ,
		new Customer { ID = 5,  FirstName = "Hardik"   , LastName = "Mistry" }
		new Customer { ID = 6,  FirstName = "Sandy"    , LastName = "Ramani" },
		new Customer { ID = 7,  FirstName = "Jigar"    , LastName = "Shah" },
		new Customer { ID = 8,  FirstName = "Kaushal"  , LastName = "Parik" } ,
		new Customer { ID = 9,  FirstName = "Abhishek" , LastName = "Swarnker" } ,
		new Customer { ID = 10, FirstName = "Sanket"   , LastName = "Patel" }
		new Customer { ID = 11, FirstName = "Dinesh"   , LastName = "Prajapati" },
		new Customer { ID = 12, FirstName = "Jayesh"   , LastName = "Patel" },
		new Customer { ID = 13, FirstName = "Nimesh"   , LastName = "Mishra" } ,
		new Customer { ID = 14, FirstName = "Shiva"    , LastName = "Reddy" } ,
		new Customer { ID = 15, FirstName = "Jasmin"   , LastName = "Malviya" }
		new Customer { ID = 16, FirstName = "Haresh"   , LastName = "Bhanderi" },
		new Customer { ID = 17, FirstName = "Ankit"    , LastName = "Ramani" },
		new Customer { ID = 18, FirstName = "Sanket"   , LastName = "Shah" } ,
		new Customer { ID = 19, FirstName = "Amit"     , LastName = "Shah" } ,
		new Customer { ID = 20, FirstName = "Nilesh"   , LastName = "Soni" }       };

	var results = from c in customers.AsParallel()
		      where c.FirstName.StartsWith("San")
		      select c;

With the simple addition of the AsParallel() extension method, the .NET runtime will automatically parallelize the operation across multiple cores. In fact, PLINQ will take full responsibility for partitioning your data into multiple chunks that can be processed in parallel.

PLINQ partitioning is out of the scope for this article, but if you’re curious about the inner workings of it, this blog post from Microsoft’s own Parallel Programming team does a great job of explaining the details.

When you will run the above sample queries , you might get same output but possibly in different order. Here Sample code 1 is an example of Sequential LINQ execution, while Sample code 2 is an example of Parallel LINQ execution.

Limitations

  1. PLINQ only works against local collections. This means that if you’re using LINQ providers over remote data, such as LINQ to SQL or ADO.NET Entity Framework, then you’re out of luck for this version.
  2. Since PLINQ chunks the collection into multiple partitions and executes them in parallel, the results that you would get from a PLINQ query may not be in the same order as the results that you would get from a serially executed LINQ query.

However, you can work around this by introducing the AsOrdered() method into your query, which will force a specific ordering into your results. Keep in mind, however, that the AsOrdered() method does incur a performance hit for large collections, which can erase many of the performance gains of parallelizing your query in the first place.

Sample code 3 : Preserving the Order of PLINQ Query Results Using the AsOrdered Method


	var results = from c in customers.AsParallel().AsOrdered()
		      where c.FirstName.StartsWith("San")
		      select c;

Controlling Parallelism

1) Forcing Parallel Execution :

In some cases, PLINQ may decide that your query is better dealt with sequentially. You can control this by using the WithExecutionMode extension method, which is applied to the ParallelQuery type. The WithExecutionMode method takes a value from the ParallelExecutionMode enumeration. There are two such values: the default (let PLINQ decide what to do) and ForceParallelism (use PLINQ even if the overhead of parallel execution is likely to outweigh the benefits).

Here is sample code which demonstrates the use of this method :


	var results = from c in customers.AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism)
		      where c.FirstName.StartsWith("San")
		      select c;

2) Limiting the Degree of Parallelism :

You can request that PLINQ limit the number of partitions that are processed simultaneously using the WithDegreeofParallelism extension method, which operates on the ParallelQuery type. This method takes an int argument that states the maximum number of partitions that should be processed at once; this is known as the degree of parallelism. Setting the degree of parallelism doesn’t force PLINQ to use that many. It just sets an upper limit. PLINQ may decide to use fewer than you have specified or, if you have not used the WithExecutionMode method, may decide to execute the query sequentially.

Here is sample code which demonstrates the use of this method :


	var results = from c in customers.AsParallel().WithDegreeOfParallelism(2)
		      where c.FirstName.StartsWith("San")
		      select c;

3) Generating and Using a Parallel Sequence :


	IEnumerable<int> evens
		= ((ParallelQuery<int>) ParallelEnumerable.Range(0, 50000))
			.Where(i => i % 2 == 0)
			.Select(i => i);

Above code uses the Range method to create a sequence of 50,000 integers starting with the zero. The first argument to the method is the start index; the second is the number of values you require. Notice that we have cast the result from the Range method to a ParallelQuery. If we don’t do this, LINQ doesn’t recognize the sequence as supporting parallel execution and will execute the query sequentially.

4) Generating and Using a Repeating Sequence :


	int sum = ParallelEnumerable.Repeat(1, 50000)
			.Select(i => i)
			.Sum();

The static Repeat method takes an object and a count and creates a sequence where the object is repeated the specified number of times.

That’s all

Thats all for this article, I have tried to cover all important topic related to PLINQ. I hope this article will help you to start with PLINQ and gain some knowledge from it.

Hope this will helps !!!

Jay Ganesh

Reference links :

  • MSDN – Parallel LINQ – link
  • Difference between plinq and linq - link

Shout it

Posted in ASP.NET 4.0, CodeProject, Linq | Tagged: , , , , , , , , | 4 Comments »

Check File type at client side – jQuery

Posted by Ramani Sandeep on February 4, 2011

Whenever we use fileupload control on web pages , the common requirement is to validate its file type and size.

we usually find it difficult to validate file size on client side rather than at server side. As of now there is no alternative script found that can achieve this. There are certain alternatives to achieve above validation on client side but that are not browser compatible & as security level changes in browser it stop functioning, so we still not at that level of trust that we can check file size at client side using jQuery/javascript.

Although it is possible to validate filetype using jquery/javascript and i m looking to do some coding for you to achieve the same. i hope this will help some developers to validate file type at client side rather than checking it on server.

Here is the javascript code that achieve above functionality :


 <script src="Js/jquery-1.4.2.min.js" type="text/javascript"></script>

    <script type="text/javascript" language="javascript">

        function FileTypeValidate() {

            //get filepath from fileupload control on the page
            var fileUpload = $('#<%=FileUpload1.ClientID %>').val();

            //extracting part of the filename from dot
            var extension = fileUpload.substring(fileUpload.lastIndexOf('.'));

            //valid file type - static
            var ValidFileType = ".jpg , .png , .bmp";
            //or fetch it from config file for flexibility ,
	    //we can save valid file type list in web.config also & fetch it during validation process
            var ValidFileTypeConfig = '<%=ConfigurationManager.AppSettings["ValidFileType"].ToString() %>';

            //check whether user has selected file or not
            if (fileUpload.length > 0) {

                //check file is of valid type or not
                if (ValidFileType.toLowerCase().indexOf(extension) < 0) {
                    alert("please select valid file type...");
                }
                else {
                    alert("file type is valid...");
                    return true;
                }
            }
            else {
                alert("please select file for upload...");
            }
            return false;
        }
    </script>

Above code explain itself a lot so no need to discuss further on it.

Here is the html markup that shows controls on the page :


    <form id="form1" runat="server">
     <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Upload" OnClientClick="return FileTypeValidate();" />
     </div>
    </form>

This is very simple but very common scenario for the web applications & very effective if managed properly…

Thats it, hope this will help !!!

Jay Ganesh

Posted in CodeProject, JavaScript, JQuery | Tagged: , , , | 1 Comment »

How to Open Large XML files without Loading the xml Files?

Posted by Ramani Sandeep on December 21, 2010

Working with Xml files in Memory is always a performance issue. It become more important to look into the processing of Xml files which are heavy in size (lets say more than 3 GB). So questions comes in mind that how to process such heavy Xml files.

When we think of working with any XML file, we normally think of using

  • XMLDocument
  • DataSet.ReadXml()
  • XPathDocument

When we use the above options, we are loading the files into the system memory.

The problem is that, if the size of the xml file is for e.g. 5 GB to 7 GB, we have to load the complete file in System’s Memory. This will cost us systems memory and will throw “System out of Memory Exception”.

The best approach to process such large files is to avoid loading the files into the memory.

Microsoft has provided with XmlTextReader class. XmlTextReader helps us to process the xml file line by line. In this way we are not loading the complete xml file into the memory but processing the file line by line, node by node.

Here is code snippet that shows an example of how to use XMLTextReader class: -

XmlTextReader myTextReader = new XmlTextReader(filename);
myTextReader.WhitespaceHandling = WhitespaceHandling.None;
while (myTextReader.Read())
{
	if (myTextReader.NodeType == XmlNodeType.Element &&
		myTextReader.LocalName == "Reward" &&
		myTextReader.IsStartElement() == true)
        {
        	ProcessRewardNode(myTextReader);
                myTextReader.Skip();
	}
}

Here is method implementations of ProcessRewardNode :

private void ProcessRewardNode(XmlTextReader RewardReader)
{
	XmlDocument RewardXmlDoc = new XmlDocument();
	RewardXmlDoc.LoadXml(RewardReader.ReadOuterXml());
	// we can use xpath as below
	myID = RewardXmlDoc.SelectSingleNode("Reward/myID").InnerText;
}

Here code itself tells you lots of things, so i am not discussing it more here. you can look into MSDN of XMLTextReader for more information.

Hope this will helps !!!

Jay Ganesh

Posted in ASP.NET 3.5, CodeProject | Tagged: , , , | 2 Comments »

Sorting Table Columns with jQuery

Posted by Ramani Sandeep on September 2, 2010

Background

I always heard about sorting table data & read lots of article that explain how to achieve it using jquery. You will also find lots of plugins available for sorting table data like Table sorter, Flexigrid , jqGrid and many more. Along with sorting feature it also support many more features like paging, resizable columns, cool themes, search and many more… But I feel that there must be one more feature in this library to sort table columns so that user will have full flexibility by playing with table arrangement along with column data. It might be possible that some of the library support this features or if not then planning to add it in their upcoming releases..

Sample Code

This code consist of GridView which shows Employee Name as Column along with some data. Now when user press sort button column will be sorted in ascending order along with data.

Here I have tried to achieve this features using some of the jQuery code without need of any library. Only thing we need here is jQuery library.

Step 1 : Add jQuery file Reference inside the tag of the page

<script src="Js/jquery-1.4.2.js" type="text/javascript"></script>

Step 2 : Next we need to drag and drop gridview on the page & set AutoGenerateColumns property to false. Specify the ID of the grid “gvEmployees”.

<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" Width="500">
   <Columns>
      <asp:BoundField DataField="Sandeep" HeaderText="Sandeep" />
      <asp:BoundField DataField="Nishar" HeaderText="Nishar" />
      <asp:BoundField DataField="Dharmik" HeaderText="Dharmik" />
      <asp:BoundField DataField="Ravi" HeaderText="Ravi" />
      <asp:BoundField DataField="Jigish" HeaderText="Jigish" />
      <asp:BoundField DataField="Kapil" HeaderText="Kapil" />
   </Columns>
</asp:GridView>

Step 3 : Drag and drop one button on the page and give its ID=”btnSortColumn” and Text=”Sort Column”.

<asp:Button ID="btnSortColumn" runat="server" Text="Sort Column" />

Step 4 : write jQuery script for the button click event, which will sort table column along with data.

       $('#btnSortColumn').click(function() {

            //Get all the rows of employee grid
            var rows = $('#gvEmployees tr');

            //Start sorting column along with data
            rows.eq(0).find('th').sort(function(a, b) {

                return $.text([a]) > $.text([b]) ? 1 : -1;

            }).each(function(new_Index) {

                //Original Index
                var original_Index = $(this).index();

                //Reorder Header Text
                rows.each(function() {
                    var th = $(this).find('th');
                    if (original_Index !== new_Index)
                        th.eq(original_Index).insertAfter(th.eq(new_Index));
                });

                //Reorder Column Data
                rows.each(function() {
                    var td = $(this).find('td');
                    if (original_Index !== new_Index)
                        td.eq(original_Index).insertAfter(td.eq(new_Index));
                });

            });
            return false;
        });

Code itself explain lots of things,

Here ‘rows’ variable contain collection of Employee row. Next we find out the column name using header tag (th) and call the sort function of javascript to call the sorting mechanism.

rows.eq(0).find('th').sort(function(a, b)
{
    return $.text([a]) > $.text([b]) ? 1 : -1;
})

When such a function is passed into array.sort(), the array elements are sorted based on the relationship between each pair of elements “a” and “b” and the function’s return value. The three possible return numbers are: <0 (less than 0), 0, or >0 (greater than 0):

  • Less than 0: Sort “a” to be a lower index than “b”
  • Zero: “a” and “b” should be considered equal, and no sorting performed
  • Greater than 0: Sort “b” to be a lower index than “a”

To sort an array numerically and ascending for example, the body of your function would look like this:

function sortfunction(a, b){
return (a - b) //causes an array to be sorted numerically and ascending
}

th.eq(original_Index).insertAfter(th.eq(new_Index));

Will insert every table header element ( th ) from original place to new place.

td.eq(original_Index).insertAfter(td.eq(new_Index));

Will insert every table data element ( td ) from original place to new place.

Step 5 : Now we have done with aspx page coding , but what about data filling logic. here it goes. Call data biding function of the gridview in Page Load event.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridData();
        }
    }

    private void BindGridData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Sandeep");
        table.Columns.Add("Nishar");
        table.Columns.Add("Dharmik");
        table.Columns.Add("Ravi");
        table.Columns.Add("Jigish");
        table.Columns.Add("Kapil");
        table.Rows.Add("20", "25", "45", "33", "22", "12");
        table.Rows.Add("40", "15", "15", "13", "12", "40");

        gvEmployees.DataSource = table;
        gvEmployees.DataBind();
    }

Here i have created dynamic datatable & filled some data rather than making Database connection & fetch data. but you can do what ever you want to bind grid.

Step 6 : Everything is setup now just press F5 & see the output of the page.

Before Sorting Column

After Sorting Column

Browser Support

I have tested this code on Firefox 3.6.8 & IE 8. you can also test it on any browser, i am sure that this code will run on all the latest browser.

Hope this will help !!!

Jay Ganesh

Reference

http://www.javascriptkit.com/javatutors/arraysort.shtml
http://api.jquery.com/insertAfter/

Shout it

kick it on DotNetKicks.com

Posted in CodeProject, JQuery | Tagged: , , , | 11 Comments »

 
Follow

Get every new post delivered to your Inbox.

Join 37 other followers