Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for February, 2011

Massive: 400 Lines of Data Access Happiness

Posted by Ramani Sandeep on February 23, 2011

Rob Conery blogs about an interesting lightweight data access he’s writing for WebMatrix that’s focused on simplicity and driving .NET 4 dynamic support for all it’s worth.

Massive is a “wrapper” for your DB tables and uses System.Dynamic extensively. If you try to use this with C# 3.5 or below, it will explode and you will be sad. Me too honestly – I like how this doesn’t require any DLLs other than what’s in the GAC. Yippee.

  • Get a Database. Northwind will work nicely. Add a connection to your database in your web.config (or app.config). Don’t forget the providerName! If you don’t know what that is – just add providerName = ‘System.Data.SqlClient’ right after the whole connectionString stuff.
  • Create a class that wraps a table. You can call it whatever you like, but if you want to be cool just name it the same as your table.
  • Query away and have fun

Read more…

Hope this will helps !!!

Jay Ganesh

About these ads

Posted in ASP.NET 4.0, Web Matrix | Tagged: , , | Leave a Comment »

Partitioning Your Code Base Through .NET Assemblies and Visual Studio Projects

Posted by Ramani Sandeep on February 22, 2011

This article is aimed at

  • Providing a list of DO and DON’T when it comes to partitioning a code base into .NET assemblies and Visual Studio projects.
  • Shedding light on.NET code componentization and packaging.
  • Suggesting ways of organizing the development environment more effectively.

The aim of this is to increase the speed of .NET developer tools, including VS and C#/VB.NET compilers, by up to an order of magnitude. This is done merely by rationalizing the development of a large code base. This will significantly increase productivity and decrease the maintenance cost of the .NET application .

This advice is gained from years of real-world consulting and development work and has proved to be effective in several settings and on many occasions..

Read more …

Hope this will helps !!!

Jay Ganesh

Posted in .Net Framework | 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 »

Common performance issues on ASP.NET web sites

Posted by Ramani Sandeep on February 2, 2011

I spend a lot of my time analysing the performance of web sites and tuning the applications to make the sites run more efficiently and scale better. Overtime I’ve pulled together a checklist of some of the more common performance issues that I see and how to resolve them, and I thought it was about time I shared them here.

Most of the issues I’ve identified are straightforward to fix (many are just configuration changes) and can give significant improvements to the scalability and the responsiveness of your web site. Some of them you may well already be aware of and I’m still amazed how many of the more obvious ones don’t get implemented as a matter of course, but then it keeps me in a job!

This post is broken down into three sections; the first is cold start improvements, or “why does my web site take so long to start up?”. This involves looking at what the IIS worker processes (w3wp.exe) are doing during initialisation, prior to completing the initial client request that caused them to launch.

The second section, which is generally more important, looks at the efficiency of processing requests once the server has “warmed up”, and is hopefully the state that the web site will spend most of its time in!

Finally the third section provides a general discussion around accessing SQL Server and web services from within web applications. These aren’t necessarily quick wins and may involve some changes to interfaces (or even the solutions architecture) to successfully implement, Finally, I’ll reveal the three golden rules for producing fast, scalable applications that I’ve derived from my investigations.

For each issue, I’ve included a brief description and references to where more information on the issue can be obtained and how to resolve it.

Read more…

Hope this will help !!!

Jay Ganesh

Posted in ASP.NET, Performance | Tagged: , , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 124 other followers