Er. alokpandey's Blog

“Programming Quotes”

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query, JavaScript, LINQ, PLINQ, SEO, SilverLight, VB, WCF by Alok Kumar Pandey on February 15, 2011
  1. If debugging is the process of removing software bugs, then programming must be the process of putting them in. –  Edsger Dijkstra

  3. The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.  – Tom Cargill

  5. “There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.”-  C.A.R. Hoare

  7. Measuring programming progress by lines of code is like measuring aircraft building progress by weight. – Bill Gates

  9. “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” – Martin Golding

  11. “The trouble with programmers is that you can never tell what a programmer is doing until it’s too late.” – Seymour Cray

  13. Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. – Rick Cook

  15. “Most of you are familiar with the virtues of a programmer. There are three, of course: laziness, impatience, and hubris.” – Larry Wall

  17. “Sometimes it pays to stay in bed on Monday, rather than spending the rest of the week debugging Monday’s code.” – Christopher Thompson

  19. Walking on water and developing software from a specification are easy if both are frozen. –Edward V Berard


How CRUD Is Your Design?

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query, JavaScript, LINQ, PLINQ, SEO, SilverLight, VB, WCF by Alok Kumar Pandey on February 9, 2011

If you’re a software developer or know one well, the acronym CRUD — Create, Read, Update and Delete — is burned into your vocabulary. These are some of the foundational elements of good software development, and each provides ways to keep your audience engaged.

When you take any one of these elements away from your users, there’s a good chance you’ll diminish the value of their experience. Here’s why.


When your audience isn’t allowed or doesn’t know how to contribute, they become passive bystanders. Your website or application no longer provides an interaction or dialogue and it probably won’t lead to a meaningful user experience.

The more you treat your audience as equals, the better. If you’re a news community like Newsvine, invite your users to create news. If you’re a information community like Wikipedia, invite your audience to create information. If you sell products like Amazon, make ratings and reviews an important part of the interface.


Confidence erodes when people can’t see data they’ve added to a website or application. They scratch their heads, wondering: Did it work? Did I do it right?

When uncertainty creeps in, people tend to blame themselves or the tool they’re using. Both scenarios are problematic, so show users where their data goes and how they can get back to it in the future.


“There are just some things you can’t take back.” This philosophy applies in the real world, but it should be avoided in a website or application.

People get nervous when they think an error they’ve made will become a permanent part of the system. So be liberal with your editing tools, and don’t hide them behind drop-downs, roll-overs or tool-tips.


People don’t like screwing up, especially in public. The ability to remove data will bring a serious dose of confidence to anyone creating content within a system. If you show them they can’t make a mistake, they’ll be much more likely to participate and give even more data.

CRUD As A Measure Of Control

There are scenarios where CRUD isn’t relevant: activity streams, automated recommendations, etc. These types of content can be interesting, exciting and even addictive, but be careful not to let them take over your website or application. Once your audience’s threshold of perceived control is lost, they’ll loose interest and move on.

So… How do you keep your audience engaged? How do you encourage them to participate? Remember, the amount of data that can be created, read, updated or deleted on your website is directly related to how in-control your audience will feel.

Leave a comment below to discuss how CRUD can make our designs more effective.


10 ways to show you’re a programming rockstar

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query, JavaScript, LINQ, PLINQ, SEO, SilverLight, Uncategorized, VB, WCF by Alok Kumar Pandey on January 27, 2011

It seems nowadays that programmers are a dime a dozen, but how do you pick the best programmers from the rest of the crowd.

It’s not just about coding (although that is a big factor). It’s about building your skill set over the years and nurturing them so you can stand out from the programming “collective.”

What characteristics makes them stand out? Are they easy to get along with? How long have they been programming? Are they teaching you things you never knew were possible? Here’s how to find out if you are a programming rock stars!

  1. Master your language and tools. Whether it’s Visual Studio, Eclipse, or even Aptana, your programming tools should be second nature to you when developing that next web application. Just like a plumber or carpenter, if you don’t have the proper tools, you won’t get the job done right.
  2. Enhance your tools and environment. With that said, even though you’ve mastered your tools, always strive to find ways to enhance your environment. This may include plug-ins to Visual Studio or Eclipse or a code generation tool that works along side your environment. If you’re not looking for better ways to enhance your productivity, you may be working yourself into an early grave.
  3. Research new technologies. While your primary language may do everything you need, make time to research your craft and experiment with new frameworks that wrap around your existing technologies. For example, while programming in web forms with C#, I heard about a new framework from Microsoft called MVC. Since I’ve started working with MVC, I’ve been programming in MVC for more than 2 years now and I haven’t looked back or regretted my decision since.
  4. Leverage your existing code you wrote. Programmers who write code and then immediately disregard it are missing out on the most exceptional tip on this list: start building your library of routines and techniques. If you are in a corporate environment, yes, you will have a corporate library to pull from for your projects. If you are an individual programmer, yes, you will have your own collection of routines or libraries that you can use in your “outside” projects. As the object-oriented saying goes, the routines are reusable.
  5. Automate like crazy. If you’ve been around the programming block for a while, you know that there are always quicker ways to accomplish certain tasks. It’s now getting to the point in this industry where if someone asks you for a web site, you can build one relatively quick. Then they start asking for features. It’s the features part that makes the difference and slows you down.
  6. Perform proper analysis. New developers always shoot first (start coding) and ask questions later. Take the time to analyze the project and ask as many questions as you can. The more questions you ask upfront, the better your ability to complete a more thorough and clear design of your application.
  7. Perform Unit Testing. Along with preceding your coding with proper analysis, always finish your coding by performing unit tests. This not only tests the quality of your code but will also let you know when your system fails on regression testing. Unit Testing should be the “checks and balances” of your programming.
  8. Extend your reach. Most developers keep to their code and that’s all they do. Break out of your comfort zone and read up on usability studies, how to document your code better, and/or using better design techniques. Expanding your skills into other areas will do three things: 1. Make you more visible to other people; 2. Make you more valuable to others because of your thirst for knowledge; and 3. Provide you with more opportunities than just programming.
  9. Communicate effectively. This is in regards to project management, coding, documentation, and impromptu meetings. If you can’t explain an extremely awesome cool coding technique to your peers or communicate why a particular feature shouldn’t be in the project to a project manager because of a time constraint, you may need to work on your verbal skills instead of your coding skills.
  10. Make time to assist others. You will seem as a definite team player by taking the time to help a fellow programmer in need. Help them understand a new concept or technique that is unclear to them and they will be grateful for the help and see you as a definite resource and go to guy.

As you can see, there are a lot of factors to take into account when deciding who is a programming rock star and how they will be perceived by other team members or by clients.

Come to think of it, you could even use some of these factors for general interview questions.

Did I miss any factors? What skills or characteristics do you think makes a programming rock star?


What if Visual Studio supported achievements

Posted in ASP.NET (C# & VB), C#, LINQ, PLINQ, SEO, SilverLight, VB by Alok Kumar Pandey on January 26, 2011

What if Visual Studio supported achievements, just like games on Steam, Xbox or PS3? Bragging to your coworkers about which one you’ve just unlocked, imagine that! Here’s a little proposed list for some of them. .NET / C# flavored, of course.

  • Falling Down – Created a new SharePoint project
  • Job Security – Written a LINQ query with over 30 lines of code
  • The Sword Fighter – 5 Consecutive Solution Rebuilds with zero code changes
  • Shotgun Debugging – 5 Consecutive Solution Rebuilds with a single character change
  • The Mathematician – Defined 15 local variables with a single character name
  • The Academic – Written 1000 lines of F#
  • Spaghetti Monster – Written a single line with more than 300 characters
  • Wild One – Mixed tabs and spaces for indentation more than 5 times in a single line
  • The Organizer – Created a Solution with more than 50 projects
  • The Portal – Created a circular project dependency
  • The Multitasker – Have more than 50 source files open at the same time
  • The Code Keeper – Uninstalled Resharper because it made you redundant
  • Pasta Chef – Created a class with more than 100 fields, properties or methods
  • Procedural Programmer – Created a method with more than 10 out parameters
  • Steam Powered – Added Visual Studio as a Steam game
  • The Poet – Written a source file with more than 10,000 lines
  • The Enterprise – Build Solution took more than 10 minutes
  • Highway to Hell – Successfully created a WCF service
  • The Explainer – Written a comment with more than 100 words
  • TPS Reports – Created a Crystal Reports Project
  • Rage Quit – ALT+F4 after a failed bug fix
  • Ooooh Shiny – Written 100 extensions methods
  • Look Ma – Written an infinite Fibonacci generator using yield
  • The Engineer – Killed a zombie with The Wrench
  • The Architect – Created 25 Interfaces in a single project
  • The Right Way – Test method is longer than the tested method
  • The Defender – Checked every argument for null exceptions
  • Pokemon Programming – Caught all the exceptions
  • Black Magic – Implemented a RealProxy
  • Gimme back my ASM – Used ILGenerator
  • I’m Sorry – Created a new Visual Basic Project
  • The SEO Expert – ASP.NET MVC Routing table with more than 100 routes
  • The Matrix – Windows Forms with more than 100 controls
  • The Daredevil – UpdatePanels nested more than 3 layers deep
  • Just a Test – Nested multiline C-style comments that caused a compilation error
  • Warm Bath – Successfully consumed a non .NET SOAP web service
  • Old School – Defined more than 100 static objects
  • The Cloner – Copy-pasted more than 50 lines
  • The Dependency – Referenced more than 30 projects
  • Paying the bills – Imported a Visual Basic project
  • First Hit – Included a library into your project and it actually compiled
  • Paula – Define a firstname field with value Brillant
  • Every Option Considered – Created an enum with more than 30 values

String Format for DateTime [C#]

Posted in ASP.NET (C# & VB), C#, LINQ, SilverLight, VB, WCF by Alok Kumar Pandey on January 2, 2011
String Format for DateTime [C#]

// create date time 2008-03-09 16:05:07.123 DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123); String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24 String.Format("{0:m mm}", dt); // "5 05" minute String.Format("{0:s ss}", dt); // "7 07" second String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M. String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone

// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

Standard DateTime Formatting

Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi­mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
U UniversalSorta­bleDateTimePat­tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)

(*) = culture independent

11 tips for better code

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query, JavaScript, LINQ, PLINQ, SilverLight, VB, WCF by Alok Kumar Pandey on December 22, 2010

11 tips for better code

There are several reasons why you should write clean and readable code. Most importantly, every code is written once, but read many times over and over. When you come back to your code next day, you have to read it. When you show your code to someone else, he has to read it. Thus by spending little more time with writing, you save A LOT of time when reading it again.Lets see some of the basic rules
1- keep methods short2- never ever ever reuse a variable for different purpose3- use self-descriptive variable and method names4- define variables as close as possible to the place of their usage5- no magic numbers6- be friend with your language7- don’t fight the convention8- watch out for premature optimization9- always refactor the code after you test it10- don’t get sucked into overengineering11- learn new things by prototyping

Now, let’s look up at each point in more detail
1. Keep methods shortEven though many people obey this rule, it is still very important. Method should always fit on the screen. When you have to scroll, it takes away your concentration and you can’t see whole context. Optimal length is 5-20 lines, depending on the situation. Of course getters/setters are usually one-line methods, but they’re more like accessors than actual methods.
2. Never ever ever reuse a variable for different purposeOne variable should be used only for one purpose.  By making variable constant (const in C++, final in Java), you also help the compiler with optimization and make your code scream This variable is not going to change, which makes the code a lot more readable.
3. Use self-descriptive variable and method namesAnyone should be able to understand your code by just looking at it. You should almost never use abbreviations, except for the most idiomatic ones likesrc – sourcepos – positionprev – previousIf you think writing descriptive names is not worth the time, just comparen, ns, nsisdwith numTeamMembers, seatCount, numSeatsInStadium
4. Define variables as close as possible to the place of their first usage
While building a house, you don’t want your hammer to be on the other side of the yard. Instead, you keep your tools as close as possible. The same applies to foo = 3;int bar = 5;// bunch of code that use “bar”// but doesn’t care about “foo”// …
baz(foo);This could be easily refactored toint bar = 5;// bunch of code that use “bar”// but doesn’t care about “foo”// …
int foo = 3;baz(foo);This becomes a real issue when the code between declaration and first usage is very long (more than one screen). It is much harder to keep the context in your mind, when you have to scroll a lot to find out what given variable is.
5. No magic numbers
Whenever you compare something against constant value, it should be defined as constant. There is nothing worse than debugging your teammate’s code with things likeil < 4384What about this instead?inputLength < MAX_INPUT_LENGTH
6. Be friend with your language
Learning new language is always fun, you can learn to do things in new cool way. There is one big downside of being pro in one language while learning other one though. Say you’re Java developer trying to learn Ruby. You should learn how to do things the Ruby way, instead of trying to apply your skill in doing things the same way you’d do them in Java.You need to write 5 times “Hello world!”. In Java, you would do something like.for (int i = 0; i < 5; i++) {  System.out.println(“Hello world!”);}In Ruby, you might be tempted to writefor i in (0..5)  puts “Hello world!”endWhich seems OK, but there is a much better way
5.times { puts “Hello world!” }
7. Don’t fight the convention
Many languages have many different conventions. In general, people most probably know is Code Conventions for Java. Lets look at some of those conventions.method names should always begin with lower-case letter, followed by CamelCase (veryLongVariableName)class names should always be in CamelCaseconstant names should be all in upper case with underscores (MY_CONSTANT)open brace should be on the same line as if condition
Breaking any of conventions should have a valid reason, never do it just because you don’t like it. If you decide to change some convention inside your team, that’s OK, but you might have problem when sharing code with other not so enlightened programmers.8. Watch out for premature optimizationPremature optimization is root of all evil, at least that’s what TV said … First thing you should care about is to write understandable code. It doesn’t have to be fast the first time you write it.All optimization is premature unless the program is slow. If you want to optimize something, at first you need to find out where the problem is. Thats why we have profilers.Trying to optimize something without finding source of the problem always ends up in breaking something, or at least your code may turn out to be unreadable. If you think that something is slow, don’t just blindly start rewriting the code, find a proof first.Don’t solve problems that don’t exist.
9. Always refactor the code after you test it
Nothing is perfect. Even though you might think you’re writing a perfect code, try looking at it few months later. You will probably fell like “wtf is that?”.Good way to improve the quality of your code is to refactor it after you test it. By testing I mean assuring that it works, which can be done either automatically or manually.First of all, you need your code to work. Don’t write it perfect the first time, just make it work. Then refactor it to make it perfect. For those of you that  know something about Test Driven Development, this might seem very familiar. The key here is to get used to the whole refactoring thing. If you’re using powerful IDE like IntelliJ IDEA, your life will be a lot easier while refactoring.
After you try refactoring, you will probably make a mistake and break something. That’s why it is good to write automated tests. Any time you refactor, you can just run all test suites and see exactly what went wrong.10. Don’t get sucked into overengineeringWhen I first read about design patterns, I thought I found The Holy Grail. It all seems to be thought out, working perfectly and making design easy to understand, because you can just say “I used an observer pattern”, instead of explaining it all.So where is the problem? Because it all looks so natural and easy, you start using design patterns for everything. Why not make this class singleton? And what about creating another factory?Then instead of writing simple 80 line script, you end up with 10 class + 15 interface monster with bunch of generics and annotations, where 97% of the code doesn’t do anything.Design patterns are very useful tool to simplify the design, which doesn’t mean using them everywhere you can. You should use them, but don’t abuse them.
11. Learn new things by prototyping
Programming is all about learning new things. When you learn new library or language, you suddenly have the urge to throw away all old code and rewrite it from scratch. There are lots of reasons why you don’t want to do that.Adding a new library or framework to existing application is a similar problem. Say you’re writing a javascript web application, and in the middle of everything, you discover jQuery. Now you have sudden urge to throw away all your javascript and write it in jQuery, even though you haven’t used it yet.The best way to go is to first create a lot of simple things with jQuery, where you will learn all the stuff you need in your application. You need AJAX? Try it on simple example outside the project and after you fully understand it, throw it away and move into production.

While developing any web site, one should keep some points in mind

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query, JavaScript, LINQ, PLINQ, SilverLight, VB by Alok Kumar Pandey on November 9, 2010

1) Set debug=false under compilation as follows:

<compilation default Language=”c#” debug=”false”>

2) Use Server.Transfer instead of Response.Redirect.

3) Always check Page.IsValid when using Validator Controls

4) Use Foreach loop instead of For loop for String Iteration.

5) Use Client-Side Validation. (but not all the time you have to validate even on the server side)

6) Check “Page.IsPostBack”. To avoid repetition code execution.

7) GIF and PNG are similar, but PNG typically produces a lower file size. (True, but some browsers not supporting PNG format)

8) Use the AppOffline.htm when updating binaries

9) Turn off Tracing unless until required. (by default it’s off, use on the pages where it’s required)

<trace enabled=”false” requestLimit=”10″ pageOutput=”false” traceMode=”SortByTime” localOnly=”true”/>

10) Precompiled pages and disable AutoEventWireup; setting the AutoEventWireup attribute to false in the Machine.config file.

11) Turn off Session State, if not required.

<sessionstate timeout=”20″ cookieless=”false” mode=”Off” stateconnectionstring=”tcpip=″ sqlconnectionstring=”data source=;Trusted_Connection=no”>

12) Select the Release mode before making the final Build for your application.

This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

13) Disable ViewState when not required.


14) Avoid frequent round trips to the Database.

15) Use Caching to improve the performance of your application.

16) Validate all Input received from the Users.

17) Use Finally Method to kill resources. (But not in the case of using)

18) The String and Stringbuilder Magic.

It is nice to use Stringbuilder instead of String when string are Amended. Strings occupy different memory location in every time of amended where stringbuilder use single memory location

19) Never use object value directly; first get object value in local variable and then use. It takes more time then variable reading.

20) Avoid Exceptions: Use If condition (if it is check proper condition)

21) Code optimization:  Avoid using code like x = x +1; it is always better to use x+=1.

22) Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned

23) Before doing a bulky ASP code processing, you can check to make sure Response.IsClientConnected.

24) As always, avoid session variables because each ASP page runs in a different thread and session calls will be serialized one by one. So, this will slow down the application. Instead of session variables you can use the QueryString collection or hidden variables in the form which holds the values.

25) Enabling buffering will improve the performance, like

<% response.buffer=true %>

Then use:

<% response.flush=true %>

26) Use Repeater control instead of DataGrid , DataList, Because It is efficient, customizable, and programmable.

27) Data listing is more time consume when large data are retrieve from database.

Paging will display only particular data but take load of all data.

Fetch only data that is needed for current page.

28) Avoid Inline JavaScript and CSS

29) Use single css file instead of multiple css file.

Try your best to combine all your CSS based classes into a single .css file as lot of .css files will cause a large amount of requests, regardless of the file sizes.

.css files are normally cached by browsers, so a single and heavy .css file doesn’t cause a long wait on each page request.

Inline .css classes could make HTML heavy, so again: go ahead with a single.css file.

30) Reduce cookie size

31) Compress CSS, JavaScript and Images

Online compressors are available; to compress file please refers following web and Replace your file content with optimize code. for CSS compression . For JS Compression

32 .Use Cache appropriately

i. Page output caching:

<%@ OutputCache Duration=”3600″ VaryByParam=”none” %>

ii. Page fragment caching:

Write a Page output caching code into each User Control

iii. Data caching:

32) Don’t make the member variables public or proteted, try to keep private and use public/protected as properties.

33) Use strString=string.Empty instead of strString=”” . [And perhaps instead of strString=null also (?)]

34) Make your page files as light as possible. That is try to avoid unnecessary markups, e.g. use div elements instead of tables.

35) Write static messages in div and make it visible when necessary. This is faster than letting server set Text property of your label or div.

36) Retrieve data from database at once, if possible. Don’t add up to database trip as far as possible. For this, combine the datafields from different tables and select them.

47) Use short ID name for WebControl.


Performance tuning tips for database developers

Posted in ASP.NET (C# & VB), C#, LINQ, PLINQ, VB, WCF by Alok Kumar Pandey on November 1, 2010

Performance tuning is not easy and there aren’t any silver bullets, but you can go a surprisingly long way with a few basic guidelines.

In theory, performance tuning is done by a DBA. But in practice, the DBA is not going to have time to scrutinize every change made to a stored procedure. Learning to do basic tuning might save you from reworking code late in the game.

Below is my list of the top 15 things I believe developers should do as a matter of course to tune performance when coding. These are the low hanging fruit of SQL Server performance – they are easy to do and often have a substantial impact. Doing these won’t guarantee lightening fast performance, but it won’t be slow either.

  1. Create a primary key on each table you create and unless you are really knowledgeable enough to figure out a better plan, make it the clustered index (note that if you set the primary key in Enterprise Manager it will cluster it by default).
  2. Create an index on any column that is a foreign key. If you know it will be unique, set the flag to force the index to be unique.
  3. Don’t index anything else (yet).
  4. Unless you need a different behaviour, always owner qualify your objects when you reference them in TSQL. Use dbo.sysdatabases instead of just sysdatabases.
  5. Use set nocount on at the top of each stored procedure (and set nocount off) at the bottom.
  6. Think hard about locking. If you’re not writing banking software, would it matter that you take a chance on a dirty read? You can use the NOLOCK hint, but it’s often easier to use SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED at the top of the procedure, then reset to READ COMMITTED at the bottom.
  7. I know you’ve heard it a million times, but only return the columns and the rows you need.
  8. Use transactions when appropriate, but allow zero user interaction while the transaction is in progress. I try to do all my transactions inside a stored procedure.
  9. Avoid temp tables as much as you can, but if you need a temp table, create it explicitly using Create Table #temp.
  10. Avoid NOT IN, instead use a left outer join – even though it’s often easier to visualize the NOT IN.
  11. If you insist on using dynamic sql (executing a concatenated string), use named parameters and sp_executesql (rather than EXEC) so you have a chance of reusing the query plan. While it’s simplistic to say that stored procedures are always the right answer, it’s also close enough that you won’t go wrong using them.
  12. Get in the habit of profiling your code before and after each change. While you should keep in mind the depth of the change, if you see more than a 10-15% increase in CPU, Reads, or Writes it probably needs to be reviewed.
  13. Look for every possible way to reduce the number of round trips to the server. Returning multiple resultsets is one way to do this.
  14. Avoid index and join hints.
  15. When you’re done coding, set Profiler to monitor statements from your machine only, then run through the application from start to finish once. Take a look at the number of reads and writes, and the number of calls to the server. See anything that looks unusual? It’s not uncommon to see calls to procedures that are no longer used, or to see duplicate calls. Impress your DBA by asking him to review those results with you.

If you take these 15 steps, you’ve made a really good first pass.

There’s more to learn next time as we build a model of how your application, the network, and SQL Server all offer the potential for bottlenecks. We will also look at the potential for improving performance and some more steps that you can take without stepping too far into the land of the DBA.


LINQ To SQL Very Slow Performance Without Compile (CompileQuery)

Posted in ASP.NET (C# & VB), C#, LINQ, PLINQ, VB by Alok Kumar Pandey on October 24, 2010


At my company, we have been running a web project.  This is a new project so we’ve had the good fortune to be able to use the latest Microsoft technologies. After spending all day running performance analysis tools and basically performing a full audit of the 6 hour process, we sadly concluded that our time was being eaten up by LINQ to SQL processing.  My experience has always been that anything you do on the compiled code side is usually overwhelmed by database access times, usually at least ten to one.  Well, I learned a lot yesterday.

The Problem

Since I already know the answer, I put together a very trivial problem to solve.  What I want to do is execute one simple SQL statement over and over.   I’m going to query just one table that actually has no records in it just to make sure the database really has nothing to do.  I’m going to make this connection on my Laptop with a SATA SSD running Sql Server 2005  locally.  I’m going to run that simple query first calling just ADO.NET (bare bones using best practices), Then using LINQ to SQL in the way I’ve always used it (and I would say 99% of the other developers out there), then I’m going to compile that LINQ to SQL and run it again.  Actually, I’m going to iterate 2000 times for each of the three conditions.

So, here is the simple SQL I’m executing:

  dbo.LinqTest.FileName = 'MyVal'

The Shocking Results

Or, for those graphically challenged (like search engines), Here is the actual data.

Test Description Seconds Execution for 2000 Iterations
ADO.NET 0.48
Linq2Sql Not Compiled 18.14
Linq2Sql Compiled 0.87

In English, this says that

  • LINQ to SQL is  37 times slower than running a raw ADO.NET Sql query
  • LINQ to SQL compiled 1.8 times slower than running a raw ADO.NET Sql query

I’ve read in several places that compiling your LINQ will help, but I have never heard anyone say how drastic the speed improvement can be.  For example, saying using a compiled query offers nearly twice the performance of a non-compiled query, and goes on to say that it brings the performance to within 93% of using a raw data reader.   Well, suffice it to say I never ran the test myself.  I could have lived with twice, but not 37 times.

How to Compile you SQL (seems like a duh kind of thing)

It’s actually not very hard.  I’m attaching the Visual Studio 2008 project that I ran this test with to this post so you can run it for yourself as well as see an example of how to write the compiled LINQ code.  Below is the method that actually does the work.  I won’t include in this article the actual ADO.NET and LINQ to SQL not compiled code, but you can see those for yourself in the attached solution.

   1:  /// <summary>
   2:  /// This method compiles the LINQ to SQL query and 
   3:  /// then executes it the number of iterations passed
   4:  /// in.  
   5:  /// </summary>
   6:  /// <param name="iterations">Number of iterations</param>
   7:  /// <returns>time in seconds of execution</returns>
   8:  private static double 
   9:  TestDataAccessSpeedLinq2SqlCompiled(int iterations)
  10:  {
  11:Func<DataClassesDataContext, string, IQueryable<LinqTest>> compiledQuery =
  12:          CompiledQuery.Compile((DataClassesDataContext meta,string fileNameForSearch) =>
  13:                                (from myData in meta.LinqTests
  14:                                 orderby myData.Id
  15:                                 where myData.FileName.Equals(fileNameForSearch)
  16:                                 select myData));
  18:      var metaNew = new DataClassesDataContext();
  19:      DateTime startTime = DateTime.Now;
  20:      for (int i = 0; i < iterations; i++)
  21:      {
  22:          IOrderedQueryable<LinqTest> query = 
  23:              (IOrderedQueryable<LinqTest>) 
  24:              compiledQuery(metaNew,string.Format("abcde{0}", i));
  25:          List<LinqTest> newList = query.ToList();
  26:      }
  27:      return 
  28:     DateTime.Now.Subtract(startTime).Duration().TotalSeconds;
  29:  }

Essentially, line 11 is compiling the code into an instance variable called compileQuery.  Using this instance variable, you can now execute the  LINQ query in a compiled form while still passing in variable data such as fileNameToSearch.  Again, the important thing to note is that one line 24 compiledQuery is already compiled so the IOrderedQueryable result is obtained without having to recompile the LINQ statement.


So, from this, it seems that you should always compile your LINQ to SQL queries.  Well, that’s not quite true.  What I’m recommending is that if you have a reason to execute the same query over and over you should strongly consider compiling.  If for example, you are just making a LINQ to SQL call once, there is no benefit because you have to compile it anyway.  Call it ten times?  Well, you will have to decide for yourself.

Forewarned is forearmed!  good luck and hope this helps.



Posted in ASP.NET (C# & VB), C#, LINQ, PLINQ, SilverLight by Alok Kumar Pandey on October 10, 2010

The ASP.NET releases history tightly correlates with the .NET Framework releases:

Date Version Remarks New ASP.NET related features
January 16, 2002 1.0 First version

released together with Visual Studio .NET

  • Object oriented web application development supporting Inheritance, Polymorphism and other standard OOP features
    • Developers are no longer forced to use Server.CreateObject(…), so early-binding and type safety are possible.
  • Based on Windows programming; the developer can make use of DLL class libraries and other features of the web server to build more robust applications that do more than simply rendering HTML (e.g. exception handling)
April 24, 2003 1.1 released together with Windows Server 2003

released together with Visual Studio .NET 2003

  • Mobile controls
  • Automatic input validation
November 7, 2005 2.0 codename Whidbey
released together with Visual Studio 2005 and Visual Web Developer Express
and SQL Server 2005
  • New data controls (GridView, FormView, DetailsView)
  • New technique for declarative data access (SqlDataSource, ObjectDataSource, XmlDataSource controls)
  • Navigation controls
  • Master pages
  • Login controls
  • Themes
  • Skins
  • Web parts
  • Personalization services
  • Full pre-compilation
  • New localization technique
  • Support for 64-bit processors
  • Provider class model
November 21, 2006 3.0
November 19, 2007 3.5 Released with Visual Studio 2008 and Windows Server 2008
  • New data controls (ListView, DataPager)
  • ASP.NET AJAX included as part of the framework
  • Support for HTTP pipelining and syndication feeds.
  • WCF Support for RSS, JSON, POX and Partial Trust
  • All the .NET Framework 3.5 changes, like LINQ etc.
August 11, 2008 3.5 Service Pack 1 Released with Visual Studio 2008 Service Pack 1
  • Incorporation of ASP.NET Dynamic Data
  • Support for controlling browser history in an ASP.NET AJAX application
  • Capability to combine multiple Javascript files into a single file for more efficient downloading
  • New namespaces System.Web.Abstractions and System.Web.Routing
April 12, 2010 4.0 Release with Visual Studio 2010 Parallel extensions and other .NET Framework 4 features