Pages

Wednesday, December 21, 2011

Cyclic Redundancy Check Error in hard disks

This issue can occur in hard disks once you try to copy or move files in the hard disk from one location to another.

It might prompt you to format the disk in order to proceed using the hard disk.

One of the reasons for this issue can be bad sectors in a damaged hard disk. If your file or folder which is corrupted is in a bad sector of the disk, then recovering those data would be difficult or sometimes, IMPOSSIBLE!

To recover your data you can try Windows copy, xcopy commands with options.

To repair the disk, use Windows CHKDSK /R command.

How to troubleshoot this issue?

Monday, December 19, 2011

Instruction prefetching!

Recently we came across an issue where our application will take relatively more time to process in the first time after some idle time than the subsequent executions that happen later.

So, the concept behind that strange behaviour is prefetching

First time the application is loaded from the memory it will cache that for further subsequent processing. Once the application is no longer requested by the user, it will dump the cache.

So, after some idle time it will have to load the application from the memory itself, thus causing some delay in the initial execution.

I might be terribly wrong here, but I was delighted to find out the reason for this weird issue, so I'm posing this for my own reference!

So, read @ your own risk! :P

How to pass arguments to a Windows batch file?

You can pass an argument to Windows batch file (.bat) using %1 in the batch file.
Ex: echo %1

Then, in command prompt you need to give argument (ex: > test.bat Jay) This will replace %1 in the batch file.

This willl display "jay" in command prompt.

Wednesday, November 16, 2011

ANTLR warning "Multiple token rules can match input such as "Xa, Xi, Xe ", Tokens Xi, Xe were disabled for that input"

Have you come across the following warning when you build ANTLR grammer files?


This is due to a failure in NFA > DFA conversion. Creating DFA for the parser is not performed as expected. For NFA conversion, the default time-out value is set to 1000. You need to increase this value to fix the above issue using the following statement when you are building the grammer.

-Xconversiontimeout t (t standas for time-out value)

Monday, November 14, 2011

How to troubleshoot "The breakpoint will not currently be hit. No symbols have been loaded for this document." issue when debugging?

If you are a Visual Studio developer, I'm sure you might have got this error atleast onece in your life. And I would call this as the "Most frustrating issue that can happen to any developer"

Because, you need to troubleshoot this may be for few days just to get a single breakpoint enabled.

As far as I know there is no clear cut solution for this issue. So, first try the following:
First Clean the solution ( Build > Clean Solution)
If it does not work, delete Bin and Obj folders and Build
Still no luck? Restart the Visual Stidio IDE

If non of these options work for you, go to Debug > Windows > Modules. It will show you the path which the symbols are loaded. You can check the symbol status there.

Tuesday, October 25, 2011

Do we need to pass a reference type argument to a method using REF keyword? - Part 02

Consider the following reference type variable x:
ArrayList x = new ArrayList()

Here, assume memory location of x is 2110 and it points to the memory location of the new object which can be 1110.

So, if you pass x variable to a method by reference without giving REF keyword, a copy of the reference, which resides in memory location 3110 is passed to the method with the value of 1110 which points to the same object.

But if you pass x variable to a method with REF keyword the original reference itself will be copied which in this case 2110.

For more info: when we should use REF keyword? - Part 01

Monday, October 24, 2011

How to give quotation mark in C# String?

Use backslash ahead of the string you need to quote
Ex: string quotationMark = "\" Hi! \"";

Sunday, October 23, 2011

How to fix System.BadImageFormatException in 64-bit OS?

If you try to refere a dll which has a file format which CLR does not support, you will get this exception. In 64 bit OS, this can happen due to dll is having some 32 bit parts (COM components etc.)  and it is being loaded as a 64 bit module.

To avoid that, you need to do the following:
  1. In Visual Studio, right click the project.
  2. In project properties, go to 'Build' tab
  3. In General section, select Platform target as x86 (default is 'Any CPU')
  4. Recompile the project and execute

Wednesday, October 19, 2011

Why you should not create indexes unnecessary?

Even though indexes improve performance in retrieval, they compromise the performance of inserts and updates.

Why adding a column is more costly than adding a record?

When you are adding a column, a schema lock is placed on the table, so that any connections to the table cannot be made during that time. So, if you can't afford any down time in your system [Always ON], this will definitely be a disadvantage.

Why we should not normalize data?

Since normalization has some well known advantages such as improved indexing, compact databases with less additional records and update performance improvement, I thought of writing about the disadvantages of normalization.

- More Joins - The more joins you use, it will cause more locks to the database, so we should avoid multiple joins when ever possible.

- Performance degrade in data retrieval (SELECT)

Because of that in data warehousing which is used for reporting and analysing, we normally use un-normalized form of data as number of retrievals are greater than inserts and updates.

Thursday, October 6, 2011

Advantage of having .mdf and .ldf files in two different disks

In SQL Server you can specify the path to database file (.mdf) and log file(.ldf).

When it comes to a server with high no. of transactions and full recovery mode, it is beneficial to have  these two paths in two different disks.

Then it will reduce Avg. Disk Queue Length, which is the average number of both read and write requests that were queued for the selected disk during the sample interval, thus resulting a significant improvement in terms of performance.

Simple facts about TempDB

  • When you create a temp table using # prefix that table will be created in TempDB.
  • TempDB is newly created when ever SQL Server is restarted.
  • Certain oprations cannot be performed on TempDB such as backup and restore, changing collation, changing schama name, drop the database etc.

SQL Server named instances: Why? Why not?

SQL Server can have one server instance per computer which is the default instance as well as multiple named instances with isolated databases and connections in the same server from SQL Server 2000 onwards. You can access named instances by server name\instance name (Ex: Galle\I01)

Why we need to have multiple named instances other than having one default instances per machine?
  • Maximum hardware utilization: Ex: If SQL your server version is designed to use only maximum 2GB RAM and your hardware supports 4GB RAM, you can optimize RAM usage by having two instances in the same server.
  • Isolation of databases which have no dependency over each other.
  • Better security seperation
Why we should not use them?

So the drawbacks of this approach are performance issues, difficulty to write cross database queries, using different ports for each instance , resource contention on memory and CPU.

Monday, September 26, 2011

How to use FXCop?

  1. Install FXCop. Setup can be found here: C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\FXCop\FxCopSetup.exe
  2. Go to All Programs > Microsoft FXCop > Microsoft FXCop version
  3. Create a new project. File >  New project
  4. Right click on the project and add .exe as target
  5. Click "Analize" (Project > Analize or F5)
  6. The result will be displayed in Active window


Tuesday, September 20, 2011

Join Hints in SQL: Invade the query optimizer!

You can use join hints to tell the query optimizer how you want join operation to be performed. Depending on your preference, it will come up with an execution plan.

There are four types of join hints, namely LOOP, HASH, MERGE and REMOTE.

You may need to decide which join hint would optimize your query based on the type and size of data you are processing.

How ever, it is advisible not to use this feature frequently, unless you have a significant performance improvement, as SQL Server tries it's best to use the best possible join hint by default, mostly it is LOOP.

I have given some execution plans related to different Join hint types below:

SQL Joins @ a glance!

Friday, September 16, 2011

When we should use REF keyword to pass a reference type argument?

If a value type (ex: int) is passed to a method, by default a copy of the value is being passed as argument and any change applied to that variable will not be applied to the original variable. If you want those changes to be there in original variable, you need to pass the argument using REF keyword.

Any programmer would be familiar with this scenario.

Do we need to pass a reference type argument to a method using REF keyword?

It depends on the type of change you are willing to do in your method.

If we only want to change the state of the object the REF keyword is not required.
But if you want to assign a new value to the variable in method and if it should represent in original variable, you should use REF keyword.

Why?

In C#, everytihng is passed by value. Even if it is a reference type, copy of the reference is passed to the variable by default. However, if you use REF keyword, the original reference will be passed to the method, thus representing all the changes you do in the method variable in the original variable.

Example:

public class Student
      int ID {get; set;}

Student stud1 = new Student(1);

// Assign a new object (Stud2) with ID = 2 - assign object to a new object

changeObjectByVal ( stud1);  // stud1 ID value remains as 1
changeObjectByRef ( ref stud1);  // stud1 ID value will be 2

// Change ID value to 3 - changing the object's state

changeObjectAttrByVal (stud1);  //  stud1 ID value will be 3
changeObjectAttrByRef (stud1);  //  stud1 ID value will be 3

Wednesday, September 14, 2011

Case insensitive string comparison

What will happen if you compare following two strings using equality operator (==)?

string a = "jayani";
string b = "Jayani"

a == b - False
It will say that two strings are not the same.

But what if you want to compare them in a case insensitive manner?
You can use String.Compare method for that.

String.Compare(a, b, true); // This will return zero which indicates that strings are similar.

Third parameter asks to do a case insensitive comparison.

Tuesday, September 13, 2011

My first day with LINQ! :)

Today I got to know about LINQ - Language Integration Query, in the same way Marie Curie found Radium (I think I can remember the correct story..May be not her!)

I had two arrays in my hand and I wanted to compare them and see whether they are equel. But I can't use the object's Equels method as it compares the memory location rather than  the value as Array is a reference type.

I could easily write a for-loop to achieve this but I wanted something new other than the old-fashioned for-loop...

There, I found LINQ!!! (Well.. I know I did not invent that, but Radium is also something that already existed rite? :P)

I could use LINQ join to achieve this. Here's the query I used:

private static bool CompareArrayOrder(string[] arr1, string[] arr2){

var q = from a in arr1
join b in arr2 on a equals b
select a;
return(arr1.Length == arr2.Length && q.Count() == arr1.Length);}

LINQ is something that you can map data with your objects such as arrays.

So, why use LINQ instead of for loop?

For the time being, what I know is, it ROCKS and COOLER than using for loops!
Other than that it makes your code simpler and less cumbersome thus making it easier to read.

Does StringBuilder always better than String in string concatenation?

No.

Why?

Use StringBuilder if you are creating a long string using a loop, when the number of string are high.
Do not use StringBuilder for small number of strings becuase, it makes the code less manageable and StringBuilder contains more logic than string, when it comes to processing the string.

Monday, September 12, 2011

Avoid using unnecessary objects

Why?
  • It is NEVER free.
  • To avoid unnecessary memory allocation
  • Avoid frequent garbage collection

Thursday, September 8, 2011

Circular dependancies in Visual Studio

If you add project A as a reference in project B, you can't add project B as a reference in project A if both projects are in same solution.
Because, Visual Studio explicitly disable circular dependancies among projects in a solution.


Error you get when you create a circular dependancy in a Visual Studio solution

It is a bad practice to allow circular dependancies between .dlls, because in the above scenario, if you change A you need to rebuild B and since B is changed you need to rebuild A and vise versa, thus creating an infinite loop which can cause a memory leak in the server.

Template parameters in SSMS 2008

You can add templates to varios features in SQL such as stored procedures, tables etc.

Ex:

If you want to replace the values which actual values,
  1. Go to Query in menu bar
  2. Select Specify Values for Template Parameters (short cut keys: ctrl+shift+m)
  3. The available parameters for the template will be displayed.
  4. Specify values in Value column
  5. Click OK.

    
    Specify values for template parameters in SSMS 2008
    

Why Trim() function ignore specified characters?

Trim() function in String will trim the preceding and trailing characters of a given character array until it finds a character which is not there in the given array.

Example:
char[] t = new char[] { 1, 2, 3}

trim("12external319test23");

result is "external319test".

So, if it is posible to have spaces, commas etc. as leading or trailing characters in addition to the defined character set, add them also to the character array, before you call Trim() function.

Tuesday, September 6, 2011

Expressions and precedence in AST

When it comes to expressions, the higher priority items are being called by lower priotrity items. So, higher priority items reside in leaf level of the AST and they get executed first. Once all the sub trees get executed, parent trees will execute. First, ANTLR will look for the lowest priority item, which is in the top level and then it executes the higher priority item which is down the line, the following a top-down parsing strategy.

Lexer rules

Lexer will generate a collection of meaningful tokens using a mere charater stream.

Following statement represents a single line comment.

COMMENT : '--' (~('\r' '\n'))* NLfrag { $channel = HIDDEN; } ;

fragment NLfrag : ('\r' '\n'? '\n') ;  
  • COMMENT - An individual token
  •    '--' - Starting point of the single line comment - a single Match() statement
  •    (~('\r' '\n'))* - Comment can be followed by zero of more times of new line characters, tab characters etc. - A loop
  •    $channel = HIDDEN - Do not show this token to parser! -
  • NLfrag - Calls another token - recursively calls mNLfrag() function
  • '\n'? - Newline is optional

How to change the compatibility level of a database

If any feature is not supported in your current database compatibility level, you will get a syntax error saying you can change it in SSMS.
  1. In SSMS 2008, go to the database in object explorer under Databases folder.
  2. Right click the database you want to change the compatibility level.
  3. In Properties, Options select the option you want in Compatibility level drop down.

Sunday, September 4, 2011

Difference between UNION and UNION ALL

Both UNION and UNION ALL statements can be used in SELECT clause to retrieve a set of records which is in a given column in both tables.

For example, consider the following example:

















Here, you can see that there are two tables with a column which is of same data type, StudentName and EmployeeName.

Say we want to find out both the students and employees in this organization, we can use UNION clause and it will return a distinct set of student and employees. If a person is a student as well as an employee, his/her name will appear only once.

But if you use UNION ALL, that person's name will appear twice.

See the results below:

Thursday, September 1, 2011

Difference between COUNT and COUNT_BIG

COUNT will return an int value where as COUNT_BIG will return a big int value.

Difference between COUNT(*) and COUNT(1)

COUNT (*) will return rows related to all the columns with null values. COUNT(1) will return the row count of the first column without null values.

Wednesday, August 31, 2011

Stack Overflow Exception

Today I got a stack overflow exception, because I have written a recursive function to be called each time with the same conditions thus creating an infinite recursion.

Why Stack Overflow?
This exception occurs when too much memory is used by call stack and consequently it is running out of the allocated memory space. Call stack contains the execution flow of the computer program.

Friday, August 26, 2011

Why stored procedures?

When you compile a stored procedure, SQL Server will create an execution plan and cache it in the server memory. So, next time you don't have to recompile it, thus reducing overhead on server.

Parameter options for SQL stored procedures

Output parameters
You can use output parameters to get the values back to the caller of the procedure using OUT or OUTPUT keyword with the parameter.

@dtmRegDate test.datetime OUT
Assign a default value to a parameter
If you are not passing a value as an argument this value will be set.



Table valued parameters


You can define a table data type and pass an argument of that type (table with some data) to a stored procedure

@dtmRegDate datetime = '1/2/2011',

Tuesday, August 23, 2011

Why you should not set an extreme value as server time-out?

Time out value is there to limit the amount of processing time allocated for requests. If you assign a larger value as time out, it will stay more time in the queue. So, even though you can always get over from a time out issue by increasing the time out value, ideally what needs to be done is ensure that your application is well optimized so that it will execute within less duration than the specified time out value. It will enhance the server performance.

Dev best practices: Meaningful variable names

Always learn to use meaningful and more descriptive variable names.
Ex: Do not use "arr" to name an Array, use "itemCollection" instead!

How to increase the no. of active connections in a JDBC connection pool?

What is a connection pool?

Connection pool handles the connections to a database requested from a particular web server process. It caches the database connections, so that connections can be reused thus improving the performance.

If you are running out of connections you will get the following server error:
"Host connection pool not found"

How to increase the number of connections in connection pool?

In "installation folder" \tomcat\conf\Catalina\localhost\ROOT.xml file set the maxActive attribute to the prefered value.

Tuesday, August 16, 2011

Add default values in to a new column for existing rows

If you want to add a new column with a default constraint to a table and insert the default value to all the existing rows, use WITH VALUES expression as given below:

Monday, August 15, 2011

SET ANSI_NULLS ON!

If you set ANSI_NULLS ON, and if you have null as any of the two operands in your comparison statement, SQL Server will return 0, even if you have results with null values that match the given condition.

Thursday, August 11, 2011

Using StringBuilder for string concatenation

It is being said that you should always use StringBuilder object to append strings. But you can simply do the same thing using an overloaded + or += operator. Once you compile the program, compiler will tranform the + operator to String.Concat.

So why we should use StringBuilder?

The reason is String is an immutable object, which means if you create a string once you cannot change it again. So, if you keep appending several strings, it will create lot of unnessasary temporary strings in memory.
To clean them up, garbage collection needs to run more often - resulting an additional overhead.

Unlike String, StringBuilder is mutable, so it will reduce the no of temporary objects you create in memory.
Consequently, it will make appending faster than the String.

Avoid unneccassary scope allocation

If you have variables which are not used outside the class, but declared as Public, you should avoid that practice. Declare them as Private. Also, if you have variables which are accesed only with in a particular method, do not declare them in class scope. Define them only in method scope.

Either way we can access the variables to get what we want. Then, why we need to follow this?

Why?

It optimizes memory allocation. For arguments, memory is allocated as stack frames. Once you go out of the scope of variable, the memory allocated for that variable is released. So, more scope you allocate for variables, more memory will be required to hold them.

Auto generate a local resource file

Local resource files are specific to a particular web page. The base resource file which will be the default option if the resource file for the requested locale is named as Test.aspx.resx. The locale specific files are named as Test.aspx.en.resx or Test.aspx.en-gb.resx (with the culture).

You can create a base resource file using the following steps:
  1. In Visual Studio, go to the web page (Ex: Test.aspx)
  2. Tools > Generate local resource
  3. The resource file will be generated under App_LocalResource folder
  4. In mark up, you can see the new attribute "meta:resourcekey" which will be used to reference the text values.

SQL Server R2 books online

Easy way to search about SQL keywords, functions, new features etc. and their applications.

Download link:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=9071

All Programs > Microsoft SQL Server 2008 > Documentation and Tutorials > SQL Server Books Online

Wednesday, August 10, 2011

Add duplicate key to a hash table

There cannot be duplicate keys in a hash table. So, adding a duplicate key to the collection using the Add method will give you an exception.

But, you can override an exsisting key with the same key name and a different value as given below:
hashTable[duplicateKey] = newValue;

Tuesday, August 9, 2011

SQL Cursors

SQL cursors can be used to process multiple rows in one query, one row at a time.

Sample SQL query

-- Disable the message of no. of rows affected in output window
SET NOCOUNT ON

-- Declare variables to store a value in a column related to one row at a time
DECLARE @topicID char(11)
DECLARE @topic char(11)

-- Declare the statement to get result set (a select statement)
DECLARE c1 CURSOR READ_ONLY
FOR
SELECT Topic_PK, TopicTitle
FROM Topic
WHERE Topic_PK < 50

-- Execute the select statement and populate the result set
OPEN c1

-- Get a row from the result set (column values defined in select statement in to the declared variables)
FETCH NEXT FROM c1
INTO @topicID, @topic

-- If there are no more rows to return
WHILE @@FETCH_STATUS = 0

BEGIN

PRINT 'Topic = ' + @topicID + @topic
FETCH NEXT FROM c1
INTO @topicID, @topic

END

-- Release resources
CLOSE c1
DEALLOCATE c1

How do you create a procedure with a cursor output parameter?

CREATE PROCEDURE OpenCrsr
(
         @OutCrsr CURSOR VARYING OUTPUT
)
AS...

To be continued ...

How do you use a loop instead of using a cursor?

Why you need to do that?

Monday, August 8, 2011

"Browse..." button in Windows forms

Since there is no such "Browse..." button in Windows forms, I created something equivalent using the following method:

Add a button control and set the text as "Browse...".
In the button click event,

OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory =  "c:\\";

openFileDialog1.RestoreDirectory = true;

if (openFileDialog1.ShowDialog() == DialogResult.OK)

if ((myStream = openFileDialog1.OpenFile()) != null)                           
 txt_FilePath.Text = openFileDialog1.FileName;
 myStream.Close();

Then add a text box control(txt_FilePath) infront of the button and set the text property to file path.

Sunday, August 7, 2011

How does your web site perform?

I found a cool site to test my web site's performance: http://www.webpagetest.org/
All you have to do is give them the URL of your site. I did a performance test test for my .NET 007 site. :)

Performance review

First byte time, Keep-Alive (no of objects in the request), GZip text (Compressing objects), Compress images, cache static, combine css/java script, Use a CDN - mine is Google - , minify JS(use gzip), proper cookie usage
Above statistics will show how to improve performance by minimizing no of objects, compressing images and java script files, minimizing requests for java script or css files by combining them in a one file etc. with the url and performance gain if you optimize the site.

Also, there will be a full optimization check list for each request.

Page speed optimization check






 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Content break down by MIME type

Gaphical representation of the requests for different content such as images, java script files, css pages are given here.




Content break down by domain

Requests for the web site by different domains and the no. of bytes are shown.

Screen shots

Screen shots of the web site during different stages in page rendering are also given with a summery of what actually happened during rendering.

Finally, this is my result:
http://www.webpagetest.org/result/110807_TW_18Q13/

Precedence in ASP.NET themes

If you specify a theme in page directive or web config, it takes precedence over the design properties given in the control itself.

Difference between skin file and style sheet (CSS)

Both skin files and style sheets come under ASP.NET themes (App_Themes) to give your site a consistent and customized look and feel. It is a convenient method for a developer to apply design across the web site with minimal effort.

Difference between skin file and CSS file
  • Skin file has .skin file extension and style sheet has .css file extension.
  • Skin file can be used on ASP.NET server controls, where as style sheets are used in standard HTML mark up elements.
  • Skin file is rendered from IIS server. CSS is rendered from the client's browser. (That's why when you apply CSS elements, you get browser specific issues.)
Example for Skin file

-asp:GridView runat="server" SkinId="gridviewSkin" BackColor="White" -
-AlternatingRowStyle BackColor="Blue" /-
-/asp:GridView-
 
Example for CSS file

body
{
          background-color :#F0F0F0;
}

Friday, August 5, 2011

How database records reside in memory?

A physical database file (.mdf) is logically divided in to data pages. A data page can go up to 8 KB. SQL Server stores records(rows) in a data page. One row cannot splitt across two data page and because of that a row can grow up to 8 KB only. If an index is added in to the table and ASC or DESC is specified, records are sorted according that order.

Wednesday, August 3, 2011

Create a graph visualization using ANTLR

You can use Graphviz software to generate a graphical version of a tree or graph.
Download link: http://www.graphviz.org/Download..php


Create the parse tree
  1. First, create ANTLR StringTemplates for tree and edges. (design specification for the image)
  2. Get the file content and create an AntlrFileStream to be given as an input to the lexer.
  3. Then create a token stream using the lexer and invoke the rules to parse the tree.
Generate the dot file

Create an instance of ANTLR DotTreeGenerator.
Create the output file.
 StringTemplate st = dotTreeGenerator.ToDOT(ParsedTree, new CommonTreeAdaptor(), _treeStringTemplate, _edgeStringTemplate);
You can create .dot file using this string template. (Ex: test.dot)


Generate image of the graph

Give the .dot file as input and specify the output format. (Ex: .png)
Execute the following command:
dot.exe -Tpng test.dot -O test.png

An image of the input graph will be created with the given design specifications.

Sample image generated for SQL query is given below:

CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255)
)

Tuesday, August 2, 2011

What's new in ASP.NET 4.0: ViewStateMode

View state is used to persist application data between page requests using client side resources.
If scalability is a major concern over performance, this will be a better mechanism to persist data as storing data in the page itself will reduce the contention on the server, thus allowing more user requests.

However, transfering data between request is costly if you are adding lengthy text to the view state.
So, disabling view state when not required will improve the performance of the application.

You can enable or disable the view state using EnableViewState and ViewStateMode properties in page or control level. Also you can use EnableViewState in web.config to manage it in application level.

How ViewStateMode works?

If you EnableViewState = true in page level, by default ViewStateMode is set as inherit in controls in that page which will enable view state for all the control. By changing the ViewStateMode of the page, you can configure the behaviour for controls as you wish.
However, if you set Page.EnableViewState = false, the view state is disabled no matter the value given in the ViewStateMode. 
You can set Page.ViewStateMode = enabled and Control.EnableViewState = false and Control.ViewStateMode = disabled to disable view state for selected controls.

You can do the vice versa, to disable view state for page and it's controls and then enable view state for selected controls.

Monday, August 1, 2011

What View Engine does?

View engine will handle the rendering of HTML content. (View in MVC)

One gaze @ ASP.NET Page life cycle!

Install IIS 7.5 in Windows Server R2

IIS 7.5 is not installed in Windows Server R2 by default. This is how to install it manually.
  1. All Programs > Administrative Tools > Server Manager > Roles Summery
  2. Roles Summery > Add Roles > Add Roles wizard
  3. Select Web Server (IIS)
  4. Select the roles you want (Ex: WebDav publishing) in Role Services
  5. Add Role Services required for ASP.NET Application Development such as ISAPI Filters, ISAPI Extentions and .NET Extensibility.

ASP.NET request processing in a nut shell!

In IIS 6.0 a seperate worker process (w3wp.exe) is created for each application pool which is known as "IIS worker process isolation" , where as in IIS 5.0, there can be more than one application in a worker process. (aspnet_wp.exe)

Thursday, July 28, 2011

Computed column expressions in SQL

SQL table column can be defined as a computed column expression, which is not a physical column in that table, unless specifically given as PERSISTED. The value is derived from some other columns in the same table.

Why it should be persisted?

If you have to calculate the value in each time a user request for it, then it will consume more processor time. So, making it "persistent" will save data in the disk which will reduce CPU contention.

However, if there is a concern on the disk space limitations, leaving it non-persistent would be ideal.

Monday, July 25, 2011

Which C# collection you should use to meet your requirement?

If you want sequential access to your collection, use stack (LIFO) or queue (FIFO). If you need to access each element by index you can use an ArrayList or List.

Using HashTable and Dictionary classes you can access an item in the collection by key.

If you want to sort the list. you can use SortedList or SortedDictionary and customize the way items are sorted using the IComparer interface.

Thursday, July 21, 2011

Difference between UNIQUE constraint and PRIMARY KEY constraint

You can use a UNIQUE constraint if you want to give uniqueness to a column which is not primary key.

You can have more than one UNIQUE constraints in a table, where as there can be only one PRIMARY KEY in a table.

To modify a PRIMARY KEY constraint, you need to drop it and re-create.

Also, PRIMARY KEY column should be NOT NULL and UNIQUE constraints can be null.

If CLUSTERED or NONCLUSTERED is not specified for a PRIMARY constraint, the default value will be CLUSTERED.

If no clustered indexes are specified for UNIQUE constraint, NONCLUSTERED is set as default value.

Since a table can have only one clustered key, if you define a PRIMARY constraint and if it is not NONCLUSTERED, you can't specify a UNIQUE constraint as CLUSTERED.

Sunday, July 17, 2011

What's new in ASP.NET 4.0: Simplified default web config

With the invention of new CLR, ASP.NET 4.0 has simplified the application level web.config file by moving most of the configurations to machine.config.

Some of the eliminated items are:
httphandlers, http modules, assembly binding

How to add custom browser definition files?

ASP.NET uses browser definition files to determine the capabilities of the browser (Ex: JavaScript, cookies, ActiveXControls etc.) which request comes from. Accordingly it will create the mark up as the response to client.

Browser definition files are located in, C:\WINDOWS\Microsoft.NET\Framework\\CONFIG\Browsers\

To add a custom browser definition file, copy the *.browser file to the above location and run Aspnet_regbrowsers.exe tool.

You can add custom browser files in App_Browsers folder in ASP.NET web site as well.

MIME types in HTTP content

HTTP response contains a content type (Ex: text/html) which describes the type of resource which is sent back to the browser. This is a MIME (Multipurpose Internet Mail Extensions) type.

MIME type contains two parts which the first part represents the resource type and the next part represents the resource sub type.

The common MIME types contains the following:


  • Text - HTML, Plain text, XML

  • Image - jpeg, png

  • Audio

  • Video

  • Application

The browser will process the content based on it's MIME type.


To be continued...

Web communication @ a glance!




Thursday, July 14, 2011

Add an executable to Windows right click menu for a file type






To give a customized menu as given above:


  1. Go to My Computer


  2. In Tools > Folder Options, Go to File Types


  3. Select the file type you want to add the menu item to (Ex: for *.sql - Microsoft SQL Server Query File)


  4. Click "Advanced"


  5. Click "New"


  6. In New Action, give the name you want to appear in right click menu in Action field


  7. Give the absolute path to the executable in "Application used to perform action" field


  8. Click OK.

Monday, July 11, 2011

Get the performance of an application running in Windows


  1. Open Perfomance monitor (Run > Perfmon)

  2. Add new counter (Right click > Add Counters)

  3. Select "Process" as Performance object.

  4. Select the required counters from the list. (Click "Explain" to get the definition for each counter)

  5. Available - executing process instances will be displayed in "Select instances from list"

  6. Select the process related to your application.

  7. Click Add.

All in one 2!



All in one!



Tuesday, June 28, 2011

Create a setup for Visual Studio project

In Visual Studio 2008,


  1. Go to File > New Project > Project Types: Other Project Types > Set up and Deployment >

  2. Select Setup Wizard

  3. Give a name to setup file and location

  4. Click OK

In Setup Project Wizard,



  1. Select "Create a setup for a Windows application"

  2. Browse for additional files such as config file

  3. If there are any dependancies with the other projects in the same solution, specify that as well

  4. Click Finish
In the Visual Studio build the project,
The setup file will be created in Release/ Debug folder in Setup folder of the project.

You can execute the setup file to start installation. Default installation location will be "C:\Program Files\{Solution name}\.."

To run the executable in Windows command prompt, go to the program files folder and give exe. name with the arguments (if any)
Ex: C:Program Files\Test > Test.exe arg1=1 arg2=2 arg3=3

Thursday, June 23, 2011

Get assembly information - CLR header



In Visual Studio command prompt execute the following command:
corFlags.exe {Assembly name - with file path}





Get assembly information - Meta data version



  1. Run Ildasm.exe command in VisualStudio command prompt. (in VisualStudio tools)

  2. Click File > Open > browse for the assembly in file system > Open

  3. Double click "Manifest"

Check the installed .NET versions in machine

  1. Go to Windows Registry. - Type Regedit in Run prompt
  2. Check the following registry entry:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\ NDP

Capture first chance exceptions

First chance exceptions will not be captured unless you manually set it to throw in Visual Studio.
But the exception type will display as output. (View > Output - ctrl+w O)

How to throw a first chance exception?

Debug > Exceptions > Add... > Type: Common Language Runtime Exceptions > Name: {name of the exception} > OK > Tick the checkbox in Thrown column > OK

Now, once the exception occurs, it will be thrown in run time.