Pages

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)