Thursday, December 17, 2009

K-MUG Session on 19th Saturday at Technopark, Trivandrum





next K-MUG User group session on 19th Saturday. More details can be located under event page of Kerala Microsoft Users Group (K-MUG) web site.

Wednesday, June 10, 2009

How to Scale your entire App and its Elements to your Browsers Size

Wow, Today I found the answer of the question "How to Scale your entire App and its Elements to your Browsers Size?" And the answer of the question "How to Scale your entire App and its Elements to your Browsers Size?" And the answer provided to me is by the silverlight 2.0. I always wonder that how can i scale my application to different browser sizes... and to different screen resolutions I found some PHP sites which were scalable according to the browser size but was unable to handle the same in my ASP.net applications... I have Hear-ed a lot about the silverlight and its applications but never give a thought to it and now finally when my client needs the scalable sites then i have no other option left with me i have to search it and thought to go ahead with silverlight and today only i get all the essentials for the silverlight and started to find the solution and to my wonders i found the solution so simple and easy... Here I would like to share it with you all...

Saturday, April 18, 2009

Fast clean way to check if an array contains particular element in C# 3.0

A good to know that really fast and the most elegant way to check if an array contains particular element in C# 3.0 seems to be using Contains() extension method.

using System;
using System.Diagnostics;
using System.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
int[] data = new int[10000000];

Random rand = new Random();
for (int i=0; i{
data[i] = rand.Next();
}

int value = data[data.Length/2];
ContainsViaForEachLoop(data, value);
ContainsViaForLoop(data, value);
ContainsViaContainsExtMethod(data, value);
ContainsViaAnyExtMethod(data, value);
Stopwatch watch = new Stopwatch();
watch.Start();
if (ContainsViaForEachLoop(data, value))
{
watch.Stop();
Console.WriteLine("foreach loop search:\t\t{0} ms",
watch.ElapsedMilliseconds);
}
watch.Reset();
watch.Start();
if (ContainsViaForLoop(data, value))
{
watch.Stop();
Console.WriteLine("for loop search:\t\t{0} ms",
watch.ElapsedMilliseconds);
}
watch.Reset();
watch.Start();
if (ContainsViaContainsExtMethod(data, value))
{
watch.Stop();
Console.WriteLine("Contains() method search:\t{0} ms",
watch.ElapsedMilliseconds);
}
watch.Reset();
watch.Start();
if (ContainsViaAnyExtMethod(data, value))
{
watch.Stop();
Console.WriteLine("Any() method search:\t\t{0} ms",
watch.ElapsedMilliseconds);
}
}
public static bool ContainsViaForEachLoop(int[] data, int value)
{
foreach (int i in data)
{
if (i == value)
{
return true;
}
}
return false;
}
public static bool ContainsViaForLoop(int[] data, int value)
{
for (int i=0; i{
if (data[i] == value)
{
return true;
}
}
return false;
}
public static bool ContainsViaContainsExtMethod(int[] data, int value)
{
return data.Contains(value);
}
public static bool ContainsViaAnyExtMethod(int[] data, int value)
{
return data.Any(i => i == value);
}
}
}

Accessing the properties of the event sender

I was Having two Controls in the Sender one dropdown list and other is a Radio Button List
the Access the object Sender

if (sender is DropDownList)
hiddenSelectedOptionID.Value = ddlOptions.SelectedValue;
if (sender is RadioButtonList)
hiddenSelectedOptionID.Value = rblTypes.SelectedValue;

Screenshot in 2 Clicks using .NET

Step 1: Fire up Visual Studio 2008 and Create a new Windows Application.
Step 2: From the toolbox, add a ‘ContextMenuStrip’ and a ‘NotifyIcon’ to the form.
Step 3: Choose an icon for the’ NotifyIcon’ using the Icon property. Change the ‘ContextMenuStrip’ property of the NotifyIcon to ‘contextMenuStrip1’ (which we added in Step 2)
Step 4: Add a new menu item to ContextMenuStrip1 control named “Grab Screenshot” as shown in the screen below:














Now double click this MenuItem and add the following code to its click event:
C#
private void grabScreenShotToolStripMenuItem_Click(object sender, EventArgs e)
{
Bitmap bmpSS = null;
Graphics gfxSS = null;

try
{
bmpSS = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);

gfxSS = Graphics.FromImage(bmpSS);

gfxSS.CopyFromScreen(
Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);

SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "JPeg Image*.jpg";
saveDialog.Title = "Save Image as";
saveDialog.ShowDialog();
if (saveDialog.FileName != string.Empty)
bmpSS.Save(saveDialog.FileName, ImageFormat.Jpeg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}



Note: Make sure you import System.Drawing and System.Drawing.Imaging namespaces.
In the code above, we create a new Bitmap which is equal to the width and height of the primary screen and then we create a new graphics using the Bitmap. We then use the CopyFromScreen() to capture the screen. Once this step is done, we create an object of SaveFileDialog and display it to the user to choose the location and save the file as an .jpeg image.
Step 5: Add the following code to the Form load event which will hide the form and remove it from taskbar.
C#
private void Form1_Load(object sender, EventArgs e)
{
this.ShowInTaskbar = false;
this.WindowState = FormWindowState.Minimized;
this.Hide();
}



Now run the program and right click the Icon that appears in your status bar. Click on the ‘Grab ScreenShot’ and save the screenshot to the desired location.

The next time you want a screenshot, remember it’s just two clicks away!
The entire source code of this article can be downloaded from here.

Tuesday, April 14, 2009

toolbar powered by Conduit

Saturday, April 4, 2009

Configuring NHibernate with ASP.NET

Object/Relational Mappers (OR/Ms) are getting increasing attention by .NET developers. By encapsulating many patterns that span from data access to data mapping and entity management, these tools often help developers overcome the so called impedance mismatch between the relational model at the base of the most used database engines and the object model supported by many programming languages.
One of the main benefits provided by OR/Ms is the increased speed in development that results from having a built-in implementation of many typical tasks related to data access, retrieval and mapping of data to objects – in a database-agnostic way.

read the Artilce on dotnetslackers.com
read also Implementing the Singleton Pattern in C#

Thursday, March 26, 2009

Tips to improve Performance of Web Application

Tips to improve Performance of Web Application
Introduction

This article list out Performance tips to improve performance of Web applications . I have divided total tips into 3 modules based on where we use. 1.Web.config. 2. Web applications. 3. Database operations.
In Web.config

1. Turn off Tracing unless until required.



2. Turn off session state in web.config file or at least for a page if there is no sessions.

3 set debug=false



4. Increase the Pool "Packet size" for transferring large blob or image fields

In connection string set "Packet Size= Required number". Performance decreases if the Packet size is huge for small amount of data transfers.
In web applications

1. Per-Request Caching

2. Cache API (Data set)

3. Background Processing (sending mails through timer 5-min)

4. Page Output Caching

5. Run IIS 6.0

6. Use Gzip Compression

7. Disable View State of a Page or Datagrid if possible.

An example of View State might be a long form that users must fill out: if they click Back in their browser and then return, the form will remain filled. When this functionality isn't used, this state eats up memory and performance. Perhaps the largest performance drain here is that a round-trip signal must be sent across the network each time the page is loaded to update and verify the cache. Since it is on by default, you will need to specify that you do not want to use View State with

<@% EnabledViewState = false %>.

8. Use Response.Redirect (".aspx",false) instead of response.redirect(".aspx"). It

Reduces CLR Exceptions count.

9 String Builder in place of string when ever needed

When a string is modified, the run time will create a new string and return it, leaving the original to be garbage collected. Most of the time this is a fast and simple way to do it, but when a string is being modified repeatedly it begins to be a burden on performance: all of those allocations eventually get expensive. To solve this Use String Builder when ever needed.

10. Fragment caching

Cache the "User controls" whenever those are repeated in several forms in a project.

11. Avoid Throwing Exceptions. It is very expensive.

Finding and designing away exception-heavy code can result in a decent perf win. Bear in mind that this has nothing to do with try/catch blocks: you only incur the cost when the actual exception is thrown. You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.

12. Change into Release mode

Select the Release mode before making the final Build for your application. By default it is in Debug mode.

13. Use Finally Method to kill resources.

Ideal Finally block:

If Not SqlDr Is Nothing Then SqlDr.Close() End If

If Not sqlcon Is Nothing Then Sqlcon.Close() End If

14. Validate all Input received from the Users.

Use Client Side Validations as much as possible. However, do a check at the Server side too to avoid the infamous Javascript disabled scenarios.

15. Avoid Recursive Functions / Nested Loops

16. Enable Option Strict and Option Explicit for your pages.

With Option Strict on, you protect yourself from inadvertent late binding and enforce a higher level of coding discipline.

Option Explicit is less restrictive than Option Strict, but it still forces programmers to provide more information in their code. Specifically, you must declare a variable before using it.

17. Use early binding in Visual Basic or JScript code.

Visual Basic 6 does a lot of work under the hood to support casting of objects, and many programmers aren't even aware of it. In Visual Basic 7, this is an area that out of which you can squeeze a lot of performance. When you compile, use early binding. This tells the compiler to insert a Type Coercion is only done when explicitly mentioned. This has two major effects:

a. Strange errors become easier to track down.

b. Unneeded coercions are eliminated, leading to substantial performance improvements.

When you use an object as if it were of a different type, Visual Basic will coerce the object for you if you don't specify. This is handy, since the programmer has to worry about less code.

18. Use Response.Write for String concatenation

Use the HttpResponse.Write method in your pages or user controls for string concatenation.

This method offers buffering and concatenation services that are very efficient. If you are performing extensive concatenation, however, the technique in the following example, using multiple calls to Response.Write, is faster than concatenating a string with a single call to the Response.Write method.

19. Avoid unnecessary round trips to the server

a. Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed. I think Scott's article gave great information on how to implement Ajax Atlas and control.

b. Use Client Side Scripts. Client site validation can help reduce round trips that are required to process user's request. In ASP.NET you can also use client side controls to validate user input.

c. Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page first time loaded and not in response to client postbacks.

If Not IsPostBack Then

LoadJScripts()

EndIf

d. In some situations performing postback event handling are unnecessary. You can use client callbacks to read data from the server instead of performing a full round trip.

20. Minimize the Use of Format()

When you can, use toString() instead of format(). In most cases, it will provide you with the functionality you need, with much less overhead.

21. Optimize Assignments

Use exp += val instead of exp = exp + val. Since exp can be arbitrarily complex, this can result in lots of unnecessary work. This forces the JIT to evaluate both copies of exp, and many times this is not needed. The first statement can be optimized far better than the second, since the JIT can avoid evaluating the exp twice.

22. Include Return Statements with in the Function

Explicitly using return allows the JIT to perform slightly more optimizations. Without a return statement, each function is given several local variables on stack to transparently support returning values without the keyword. Keeping these around makes it harder for the JIT to optimize, and can impact the performance of your code. Look through your functions and insert return as needed. It doesn't change the semantics of the code at all, and it can help you get more speed from your application

23. Use For Loops for String Iteration

The tradeoff for this generalization is speed, and if you rely heavily on string iteration you should use a For loop instead. Since strings are simple character arrays, they can be walked using much less overhead than other structures.

Foreach is far more readable, and in the future it will become as fast as a For loop for special cases like strings. Unless string manipulation is a real performance hog for you, the slightly messier code may not be worth it.

24.Precompiling pages and disabling AutoEventWireup

By precompiled pages, users do not have to experience the batch compile of your ASP.NET files; it will increase the performance that your users will experience.

Also setting the AutoEventWireup attribute to false in the Machine.config file means that the page will not match method names to events and hook them up (for example, Page_Load). If page developers want to use these events, they will need to override the methods in the base class (for example, they will need to override Page.OnLoad for the page load event instead of using a Page_Load method). If you disable AutoEventWireup, your pages will get a slight performance boost by leaving the event wiring to the page author instead of performing it automatically.

25. Use Jagged Arrays instead of rectangular Arrays

The v1 JIT optimizes jagged arrays (simply 'arrays-of-arrays') more efficiently than rectangular arrays, and the difference is quite noticeable. Here is a table demonstrating the performance gain resulting from using jagged arrays in place of rectangular ones in both C# and Visual Basic

26. Put Concatenations in One Expression

If you have multiple concatenations on multiple lines, try to stick them all on one expression. The compiler can optimize by modifying the string in place, providing a speed and memory boost. If the statements are split into multiple lines, the Visual Basic compiler will not generate the Microsoft Intermediate Language (MSIL) to allow in-place concatenation.

27. Avoid Unnecessary Indirection

When you use byRef, you pass pointers instead of the actual object. Many times this makes sense (side-effecting functions, for example), but you don't always need it. Passing pointers results in more indirection, which is slower than accessing a value that is on the stack. When you don't need to go through the heap, it is best to avoid it.

28. Use Charw

Use charw instead of char. The CLR uses Unicode internally, and char must be translated at run time if it is used. This can result in a substantial performance loss, and specifying that your characters are a full word long (using charw) eliminates this conversion.

29. Use Binary Compare for Text

When comparing text, use binary compare instead of text compare. At run time, the overhead is much lighter for binary.

30. Partial Classes (or Split classes)

Partial classes can improve code readability and maintainability by providing a powerful way to extend the behavior of a class and attach functionality to it.

One of the language enhancements in .NET 2.0-available to both VB2005 and C# 2.0 programmers-is support for partial classes. In a nutshell, partial classes mean that your class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. During compile time, it simply groups all the various partial classes and treats them as a single entity.

One of the greatest benefits of partial classes is that they allow a clean separation of business logic and the user interface (in particular, the code that is generated by the Visual Studio Designer). Using partial classes, the UI code can be hidden from the developer, who usually has no need to access it anyway. Partial classes also make debugging easier, as the code is partitioned into separate files. This feature also helps members of large development teams work on their pieces of a project in separate physical files.

31. Use "array Lists" in place of arrays.

An ArrayList as everything that is good about an array PLUS automatic sizing, Add, Insert, Remove, Sort, BinarySearch. All these great helper methods are added when implementing the IList interface, the specifics of which are explored in the next section. The downside of an ArrayList is the need to cast objects upon retrieval.

32. Use "For each" Instead of For.

While writing this sample, we forgot to subtract one from people.Length. It was an immediately obvious mistake, but it could have been avoided by using

For Each.

When you use "For each" with an array, as you did here, the compiled Intermediate Language (IL) code is identical to the code you wrote as a For. Unless you require more complex behavior, such as iterating in reverse or iterating over every other item, always be sure to use For Each to iterate over arrays and most collections. The language-specific compiler handles this expansion and you reap the benefit. Your code will be less prone to off-by-one bugs, and it will be much easier to read.

33. Appropriate data type based on the requirement.

Use binary, int16, int32, int64 in place of integer according to the need..
In Database Operations

1. Return Multiple Resultsets

Using a single Data Reader we can execute multiple queries simultaneously.

http://www.ondotnet.com/pub/a/dotnet/2002/12/16/multiresultsets_1202.html?page=1

2. Paged Data Access through SP

3. Connection Pooling and Object Pooling

Connection pooling is a useful way to reuse connections for multiple requests, rather than paying the overhead of opening and closing a connection for each request. It's done implicitly, but you get one pool per unique connection string. If you're generating connection strings dynamically, make sure the strings are identical each time so pooling occurs. Also be aware that if delegation is occurring, you'll get one pool per user. There are a lot of options that you can set for the connection pool, and you can track the performance of the pool by using the Perfmon to keep track of things like response time, transactions/sec, etc.

4. Parameters while Inserting/Updating

5. Use SqlDataReader Instead of Dataset wherever it is possible

a. For retrieving large data from DB

b. Data with no relations.

6. Turn off Features You Don't Use

A pooled transactional object must enlist its connection into the current transaction manually. To enable it to do so, you must disable automatic transaction enlistment by setting the connection string Enlist property to False.

Turn off automatic transaction enlistment if it's not needed. For the SQL Managed Provider, it's done via the connection string:

SqlConnection conn = new SqlConnection("Server=mysrv01;Integrated Security=true; Enlist=false");

When filling a dataset with the data adapter, don't get primary key information if you don't have to (e.g. don't set MissingSchemaAction.Add with key):

public DataSet SelectSqlSrvRows(DataSet dataset,string connection,string query)

{

SqlConnection conn = new SqlConnection(connection);

SqlDataAdapter adapter = new SqlDataAdapter();

adapter.SelectCommand = new SqlCommand(query, conn);

adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

adapter.Fill(dataset);

return dataset;

}

7. Keep Your Datasets Lean

Only put the records you need into the dataset. Remember that the dataset stores all of its data in memory, and that the more data you request, the longer it will take to transmit across the wire.

8. Use Sequential Access as Often as Possible

With a data reader, use CommandBehavior.SequentialAccess. This is essential for dealing with blob data types since it allows data to be read off of the wire in small chunks. While you can only work with one piece of the data at a time, the latency for loading a large data type disappears. If you don't need to work the whole object at once, using Sequential Access will give you much better performance.

9. CommandBehavior.CloseConnection

We don't need to specify explicitly something like close because we specified this in SqlCommand.ExecuteReader as CommandBehavior.CloseConnection. This option automatically closes the connection after we have finished with our work. Any exceptions thrown will be caught and displayed in the error message.

http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c5153/

10. Inefficient queries. Queries that process and then return more columns or rows than necessary waste processing cycles that could best be used for servicing other requests. Queries that do not take advantage of indexes may also cause poor performance.

11. Retrieving too much data. Too much data in your results is usually the result of inefficient queries. The SELECT * query often causes this problem. You do not usually need to return all the columns in a row. Also, analyze the WHERE clause in your queries to ensure that you are not returning too many rows. Try to make the WHERE clause as specific as possible to ensure that the least number of rows are returned.

12. Inefficient or missing indexes. Query efficiency decreases when indexes are missing because a full table scan must be performed. Also, as your data grows, tables may become fragmented. Failure to periodically rebuild indexes may also result in poor query performance.

13. Unnecessary round trips. Round trips significantly affect performance. They are subject to network latency and to downstream server latency. Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance. Keep round trips to an absolute minimum.

14. Too many open connections. Connections are an expensive and scarce resource, which should be shared between callers by using connection pooling. Opening a connection for each caller limits scalability. To ensure the efficient use of connection pooling, avoid keeping connections open and avoid varying connection strings.

15. Failure to release resources. Failing to release resources can prevent them from being reused efficiently. If you fail to close connections before the connections fall out of scope, they are not reclaimed until garbage collection occurs for the connection. Failing to release resources can cause serious resource pressure and lead to shortages and timeouts.

16. Transaction misuse. If you select the wrong type of transaction management, you may add latency to each operation. Additionally, if you keep transactions active for long periods of time, the active transactions may cause resource pressure. Transactions are necessary to ensure the integrity of your data, but you need to ensure that you use the appropriate type of transaction for the shortest duration possible and only where necessary.

17. Overnormalized tables. Overnormalized tables may require excessive joins for simple operations. These additional steps may significantly affect the performance and scalability of your application, especially as the number of users and requests increases.

18. Avoid Moving Binary Large Objects Repeatedly

Avoid moving BLOB data more than one time. For example, if you build a Web application that serves images, store the images on the file system and the file names in the database instead of storing the images as BLOBs in the database.

Storing the images as BLOBs in the database means that you must read the BLOB from the database to the Web server and then send the image from the Web server to the browser. Reading the file name from the database and having the Web server send the image to the browser reduces the load on the database server. It also reduces the data that is sent between the database and the Web server. This can significantly affect performance and scalability.

18. Use the ConnectionState property.

Avoid relying on an error handler to detect connection state availability. When you can, use the ConnectionState.Open or ConnectionState.Close method to check the state before use.

19. Reduce Serialization

Dataset serialization is more efficiently implemented in .NET Framework version 1.1 than in version 1.0. However, Dataset serialization often introduces performance bottlenecks. You can reduce the performance impact in a number of ways:

a. Use column name aliasing. The serialized data contains column names so that you can use column name aliasing to reduce the size of the serialized data.

b. Avoid serializing multiple versions of the same data. The DataSet maintains the original data along with the changed values. If you do not need to serialize new and old values, call AcceptChanges before you serialize a DataSet to reset the internal buffers.

c. Reduce the number of DataTable objects that are serialized. If you do not need to send all the DataTable objects contained in a DataSet, consider copying the DataTable objects you need to send into a separate DataSet.

20. Cancel Pending Data

When you call the Close method, the method does not return until all the remaining data has been fetched. If you know you have pending data when you want to close your DataReader, you can call the Cancel method before you call Close to tell the server to stop sending data.

This approach does not always result in a performance improvement, because Cancel is not guaranteed to make the server stop sending data. Control information is still exchanged after the call to Cancel, and the control information may or may not be interleaved with leftover data. Therefore, before you restructure your code to call Cancel before Close, test Cancel to learn if it actually helps in your particular scenario and to learn if you really need the extra performance at the expense of readability.

Note If you need output parameters, do not call Close until you have retrieved the output parameters. After you retrieve the output parameters, you can then call Close.

21. Consider SET NOCOUNT ON for SQL Server

When you use SET NOCOUNT ON, the message that indicates the number of rows that are affected by the T-SQL statement is not returned as part of the results. When you use SET NOCOUNT OFF, the count is returned. Using SET NOCOUNT ON can improve performance because network traffic can be reduced. SET NOCOUNT ON prevents SQL Server from sending the DONE_IN_PROC message for each statement in a stored procedure or batch of SQL statements.

For example, if you have eight operations in a stored procedure, eight messages are returned to the caller. Each message contains the number of rows affected by the respective statement. When you use SET NOCOUNT ON, you reduce the processing that SQL Server performs and the size of the response that is sent across the network.

Note: In Query Analyzer, the DONE_IN_PROC message is intercepted and displayed as "N rows affected.

22. Do Not Use CommandBuilder at Run Time

CommandBuilder objects such as SqlCommandBuilder and OleDbCommandBuilder automatically generate the InsertCommand, UpdateCommand, and DeleteCommand properties of a DataAdapter. The CommandBuilder objects generate these properties based on the SelectCommand property of the DataAdapter. CommandBuilder objects are useful when you are designing and prototyping your application. However, you should not use them in production applications. The processing required to generate the commands affects performance. Manually create stored procedures for your commands, or use the Visual Studio® .NET design-time wizard and customize them later if necessary.

23. Pool Connections

Creating database connections is expensive. You reduce overhead by pooling your database connections. Make sure you call Close or Dispose on a connection as soon as possible. When pooling is enabled, calling Close or Dispose returns the connection to the pool instead of closing the underlying database connection.

You must account for the following issues when pooling is part of your design:

a. Share connections. Use a per-application or per-group service account to connect to the database. This creates a single pool or a small number of pools, and it enables many client requests to share the same connections.

b. Avoid per-user logons to the database. Each logon creates a separate pooled connection. This means that you end up with a large number of small pools. If you need a different user for each connection, disable pooling or set a small maximum size for the pool.

c. Do not vary connection strings. Different connection strings generate different connection pools. For example, using different capitalization, extra spaces, or different ordering of attributes causes connections to go to different pools. The SQL Server .NET Data Provider performs a byte-by-byte comparison to determine whether connection strings match.

d. Release connections. Do not cache connections. For example, do not put them in session or application variables. Close connections as soon as you are finished with them. Busy connections are not pooled.

e. Passing connections. Do not pass connections between logical or physical application layers.

f. Consider tuning your pool size if needed. For example, in the case of the .NET Framework Data Provider for SQL Server, the default minimum pool size is zero and the maximum is 100. You might need to increase the minimum size to reduce warm-up time. You might need to increase the maximum size if your application needs more than 100 connections.

g. Connection pools are managed by the specific database provider. SqlClient, OleDB client, and third-party clients may provide different configuration and monitoring options.

The following list details the pooling mechanisms that are available, and it summarizes pooling behavior for the .NET Framework data providers:

h. The .NET Framework Data Provider for SQL Server pools connections by using a pooling mechanism implemented in managed code. You control pooling behaviors such as lifetime and pool size through connection string arguments.

i. The .NET Framework Data Provider for Oracle also pools connections by using a managed code solution.

j.The .NET Framework Data Provider for OLE DB automatically uses OLE DB session pooling to pool connections. You control pooling behavior through connection string arguments.

k. The .NET Framework Data Provider for ODBC uses ODBC connection pooling.

24. Do Not Explicitly Open a Connection if You Use Fill or Update for a Single Operation

If you perform a single Fill or Update operation, do not open the connection before you call the Fill method, because the DataAdapter automatically opens and closes the connection for you. The following code fragment shows how to call Fill.

The SqlDataAdapter automatically opens the connection, runs the selected command, and then closes the connection when it is finished. This enables the connection to be open for the shortest period of time.

Note that if you need to perform multiple file or update operations, you need to open the connection before the first Fill or Update method and close it after the last one. Alternatively, you could wrap multiple Fill or Update operations inside a C# using block to ensure that the connection is closed after the last use

25. Explicitly Close Connections

Explicitly call the Close or Dispose methods on SqlConnection objects as soon as you finish using them to release the resources that they use. Do not wait for the connection to fall out of scope. The connection is not returned to the pool until garbage collection occurs. This delays the reuse of the connection and negatively affects performance and scalability. The following are guidelines to consider. These guidelines are specific to SqlConnection because of the way it is implemented. These guidelines are not universal for all classes that have Close and Dispose functionality.

a. Using either the Close method or the Dispose method is sufficient. You do not have to call one method after the other. There is no benefit to calling one method after the other.

b. Dispose internally calls Close. In addition, Dispose clears the connection string.

c. If you do not call Dispose or Close, and if you do not use the using statement, you are reliant upon the finalization of the inner object to free the physical connection.

d. Use the using statement, instead of Dispose or Close, when you are working with a single type, and you are coding in Visual C#®. Dispose is automatically called for you when you use the using statement, even when an exception occurs.

e. If you do not use the using statement, close connections inside a finally block. Code in the finally block always runs, regardless of whether an exception occurs.

f. You do not have to set the SqlConnection reference to null or Nothing because there is no complex object graph. Setting object references to null or to Nothing is usually done to make a graph of objects unreachable.

Note: Closing a connection automatically closes any active DataReader objects that are associated with the connection.

26. Using the "using" statement

The using statement can be used to specify a boundary for the object outside of which, the object is destroyed automatically. The runtime invokes the Dispose method of the objects that are specified within this statement when the control comes out of this block. This is why this is a preferred choice when using exceptions for managing resources in .NET. Refer to the following code that uses the "using" statement:

string connectionString = ...; // Some connection string

using (SqlConnection sqlConnection = new SqlConnection(connectionString))

{

sqlConnection.Open();

//Some code

}

Note that when the end of the using block would be encountered, the Dispose () method will be immediately called on the instance. Note that when the Dispose() method is called on this connection instance, it checks to see if the connection is opened; if open it would close it implicitly prior to disposing off the instance.

27. The EnforceConstraints property of the dataset to false to turn off the constraints checking. Then use BeginLoadData and EndLoadData methods to turn off the index maintenance for faster processing in a dataset that needs to be populated from the database.

28. When you are no longer using an object it can be disposed, which is when the dispose method is called. When an object is disposed it should release any resources it is holding. I.e. closing database connections, destroying large structures it might be holding like a Data Table etc. The object itself is still in memory though and periodically .net will "garbage collect" which is when it removes all unused (ie disposed) objects from memory. It is this garbage collection that is when the finalize event is called, ie just before it is to be physically removed from memory.
Posted by Deepak S at 2:12 AM 0 comments
Tuesday, February 10, 2009
Javascript Validation in ASP.net
Javascript Validation in ASP.net

Hi friends, here is a simplest way of javascript client side validation for an asp.net registration for ,all you need to do is place this code inside script tag and change thename of Controls to your control names.

function validateregform()
{

if (document.getElementById("<%=txtName.ClientID%>").value=="")
{
alert("Name Field can not be blank");
document.getElementById("<%=txtName.ClientID%>").focus();
return false;
}

if(document.getElementById("<%=txtEmail.ClientID %>").value=="")
{
alert("Email id can not be blank"); document.getElementById("<%=txtEmail.ClientID%>").focus();
return false;
}
var emailPat = /^(\".*\"[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}][A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
var emailid=document.getElementById("<%=txtEmail.ClientID%>").value;
var matchArray = emailid.match(emailPat);
if (matchArray == null)
{
alert("Your email address seems incorrect. Please try again.");
document.getElementById("<%=txtEmail.ClientID%>").focus();
return false;
}

if(document.getElementById("<%=txtWebURL.ClientID %>").value=="")
{
alert("Web URL can not be blank");
document.getElementById("<%=txtWebURL.ClientID%>").value="http://" document.getElementById("<%=txtWebURL.ClientID%>").focus(); return false;
}
var Url="^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$" ;
var tempURL=document.getElementById("<%=txtWebURL.ClientID%>").value;
var matchURL=tempURL.match(Url); if(matchURL==null)
{
alert("Web URL does not look valid");
document.getElementById("<%=txtWebURL.ClientID%>").focus();
return false;
}

if (document.getElementById("<%=txtZIP.ClientID%>").value=="")
{
alert("Zip Code is not valid");
document.getElementById("<%=txtZIP.ClientID%>").focus();
return false;
}
var digits="0123456789";
var temp;
for (var i=0;i<%=txtzip.clientid%>").value.length;i++)
{
temp=document.getElementById("<%=txtZIP.ClientID%>").value.substring(i,i+1);
if (digits.indexOf(temp)==-1) {
alert("Please enter correct zip code");
document.getElementById("<%=txtZIP.ClientID%>").focus(); return false;
}
} return true;
}
Here validateregform contains four functions to validate name,email,web url and zip code.

Check if Caps Lock is ON (Asp.Net)

checkCapsLock
function checkCapsLock(e) {
var myKeyCode = 0;
var myShiftKey = false;
var myMsg = 'Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

// Internet Explorer 4+
if (document.all) {
myKeyCode = e.keyCode;
myShiftKey = e.shiftKey;

// Netscape 4
} else if (document.layers) {
myKeyCode = e.which;
myShiftKey = (myKeyCode == 16) ? true : false;

// Netscape 6
} else if (document.getElementById) {
myKeyCode = e.which;
myShiftKey = (myKeyCode == 16) ? true : false;

}

// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
if ((myKeyCode >= 65 && myKeyCode <= 90) && !myShiftKey) {
alert(myMsg);

// Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
} else if ((myKeyCode >= 97 && myKeyCode <= 122) && myShiftKey) {
alert(myMsg);

}
}

call:
asp:TextBox ID="txtPassword" runat="server" MaxLength="16" TextMode="Password" onKeyPress="checkCapsLock(event)

How to copy structure and data of one table into another table(2 Db's)?

How to copy structure and data of one table into another table(2 Db's)?

SELECT * INTO db2.dbo.test FROM db1.dbo.test

Wednesday, March 25, 2009

Disable all previous date in calender control using ASP.NET C#

Disable all previous date in calender control using ASP.NET C#



protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date <= DateTime.Today.Date)
{
e.Day.IsSelectable = false;

}
}

Remove asp menu items

Remove asp menu items

((Menu)(MenuName)).Items.Remove(((Menu)(MenuName)).Items[1]);

Dynamically Add Watermark On Image ASP.NET C#

Dynamically Add Watermark On Image ASP.NET C#
How to create watermark on image. you can simply create watermarks text on image
//used namespaces

//using System.IO;
//using System.Drawing.Drawing2D;
//using System.Drawing;
//using System.Drawing.Imaging;

///Locate Image from Image folder.
System.Drawing.Image objImage = System.Drawing.Image.FromFile(Server.MapPath("images/Copy.jpg"));
//Taken Actual width anf height From Image
int height = objImage.Height;//height
int width = objImage.Width;//Width
//Create a Bitmap Image
System.Drawing.Bitmap bitmapimage = new System.Drawing.Bitmap(objImage, width, height);// create bitmap with same size of Actual image
//Convert in to a Graphics object
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmapimage);
//Creating Brushe
System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(113, 255, 255, 255));
g.DrawString("Raju.M C# Programmer Kerala,India.Dynamic WaterMark sample", new Font("Arial", 18, System.Drawing.FontStyle.Bold), brush, 0, 100);
Response.ContentType = "image/jpeg";//setting ContentType
bitmapimage.Save(Response.OutputStream, ImageFormat.Jpeg);//save image with dynamic watermark

Thursday, March 19, 2009

ASP.NET 2.0 error: Unable to start debugging on the web server.

There may be different causes for this type of Error :
One way of Occurace is due to ... [UrlScan]
UrlScan version 2.5 is a security tool that restricts the types of HTTP requests that Internet Information Services (IIS) will process. By blocking specific HTTP requests, the UrlScan security tool helps prevent potentially harmful requests from reaching the server. UrlScan 2.5 will install on servers running IIS 4.0 and later.

RUN > Search > For Files and Folders > Type - 'UrlScan.ini' (without quotes)
Open the ini file in a Notepad , there will be different section in this file .. such as UseAllowVerbs,UseAllowExtensions ..etc . Check whether .asp is there in deny section. if so delete that..also include that in allow section..then check the AllowVerbs section..add Debug there..

Happy Coding ..

App_Offline.htm

if you place a 'app_offline.htm' file with this name in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application. ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the app_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

This provides a convenient way to take down your application while you are making big changes or copying in lots of new page functionality (and you want to avoid the annoying problem of people hitting and activating your site in the middle of a content update). It can also be a useful way to immediately unlock and unload a SQL Express or Access database whose .mdf or .mdb data files are residing in the /app_data directory.

Once you remove the app_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and life will continue along as normal.

Wednesday, March 18, 2009

Params Modifier

In some cases you might need a function which takes an arbitrary number of parameters.This
could of course be done by accepting an array or a list as a parameter, like this:
static void GreetPersons(string[] names) { }
However, calling it would be a bit clumsy.
In the shortest form, it would look like this: GreetPersons(new string[] { "John", "Jane", "Tarzan" });
It is acceptable, but it can be done even smarter, with the params keyword:
static void GreetPersons(params string[] names) { }
Calling it would then look like this:
GreetPersons("John", "Jane", "Tarzan");
Functions with params can even take other parameters as well, as long as the parameter with the params keyword are the last one. Besides that, only one parameter using the params keyword can be used per function.

What are steps to load a .NET code in SQL SERVER 2005

Write the managed code and compile it to a DLL/Assembly.After the DLL is compiled using the “CREATE ASSEMBLY” command you can load the assemby into SQL SERVER. Below is the create command which is loading “mycode.dll” into SQL SERVER using the “CREATE ASSEMBLY” commandSyntax

CREATE ASSEMBLY AssemblyName FROM ‘C:/MyAssmbly.dll’

Tuesday, March 17, 2009

Enable/Disable All Buttons in a GridView using JavaScript

First the code gets an instance of the GridView using the
getElementById, then create a collection of all input controls in the GridView. Next it loops through each input control and checks the type (this is necessary because input controls include not only submit buttons but also things like textboxes). Finally we either enable or disable the submit button.


function DisableGridButtons()
{

var gridView = document.getElementById("gridview1");
var gridViewControls = gridView.getElementsByTagName("input");
for (i = 0; i < gridViewControls.length; i++)
{
// if this input type is button, disable
if (gridViewControls[i].type == "submit")
{
gridViewControls[i].disabled = true;
}
}

}

Monday, March 16, 2009

Yes/No buttons in the place of Ok/ Cancel buttons using Javascript and Vb script

Place this VB Script in ur aspx page
Function makeMsgBox(tit,mess,icon,buts,defs,mode)
butVal = icon + buts + defs + mode
makeMsgBox = MsgBox(mess,butVal,tit)
End Function

then copy this to your Js File


function Confirm(msg)
{
ie4 = document.all;
ie5 = document.all;
if(ie4 ie5)
{
// if its IE4+ call the VB Script
retVal =
makeMsgBox("Patient Attachment",msg,1,1,1,1);
// which button was pressed?
if(retVal == 6)
{
return true;
}
else
{
return
false;
}
}
else
{
return Confirm(msg);
}
}

Call the js function Confirm()

Confirm('Do you want to delete details now ?')


Friday, March 13, 2009

Comparing Dates in JavaScript

function CompareDates()

{

var str1 = document.getElementById("Fromdate").value;

var str2 = document.getElementById("Todate").value;

var dt1 = parseInt(str1.substring(0,2),10);

var mon1 = parseInt(str1.substring(3,5),10);

var yr1 = parseInt(str1.substring(6,10),10);

var dt2 = parseInt(str2.substring(0,2),10);

var mon2 = parseInt(str2.substring(3,5),10);

var yr2 = parseInt(str2.substring(6,10),10);

var date1 = new Date(yr1, mon1, dt1);

var date2 = new Date(yr2, mon2, dt2);

if(date2 <> date1)

{

alert("To date cannot be greater than from date");

return false;
}

else

{
alert("Submitting ...");

document.form1.submit();
}

}

__________________________________________________

Usgin Split() Function


var ArrayEffectiveDate = document.getElementById('calEffectiveDate').value.split("/");
var ArrrayExpiryDate = document.getElementById('calExpiryDate').value.split("/");
var dt1 = ArrayEffectiveDate[1];
var mon1 = ArrayEffectiveDate[0];
var yr1 = ArrayEffectiveDate[2];
var dt2 = ArrrayExpiryDate[1];
var mon2 = ArrrayExpiryDate[0];
var yr2 = ArrrayExpiryDate[2];
var date1 = new Date(yr1, mon1, dt1);
var date2 = new Date(yr2, mon2, dt2);
if(date2 <= date1)
{
alert("Expiry Date should be greater than Effective Date");
return;
}

Thursday, March 12, 2009

Rounded rectangle Windows Form

in Kerala Microsoft Users Group, Shoban Kumar posted a question, how to create a rounded rectangle windows form, for his Codeplex project jata.

The implementation is like the following
1) Go to the Form’s Paint event.
2) create a Graphical path object.
3) Add rectangles and lines.
4) Set the Form’s region using the Graphical path.

You can download the code from here.

How to create ASPX Page Dynamically - A Step Ahead Series?

Introduction

In a simple creating an aspx page dynamically is a very tedious job. Whenever we think for dynamically creation scenarios stuck in mind about the overload to server etc. But with the help of this article one can attain the same as easily as creating another simple aspx page.
Need and Requirement

Now next words came to mind that what is the need to create an aspx page dynamically? Let me explain it:
You need to create a page, based on selected requirement at the moment.
Need to create a page from static html contents.
Having huge data, need to represent in an individual page and its tough to store in database.
Article ScenarioAs stated above, I choose a scenario where you are running a technical community and need to the template where member of your site will able to write some static html contents.

Explanation

http://stuff4mdesktop.blogspot.com/2009/02/how-to-create-aspx-page-dynamically.html

Changing authentication mode and enabling sa using osql

Changing authentication mode and enabling sa using osql Few days back, I tried to install SQL Server Management studio express in my machine, because of some strange reasons, it is getting rollbacked everytime. I don’t know why I am getting that error. Then for some development purpose I have to use sa, or sql authentication in SQL 2005 instead of Windows. If I do have SQL Server Management studio, it is pretty easy job. But using osql and registery settings we can achive the same.

Changing SQL Server authentication mode.

Note: Backup registry before making any changes.
Open Registry editor using RegEdit command.
Goto the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.x\MSSQLServer, locate a subkey with name “LoginMode”.
If LoginMode subkey is 1, then the SQL Server is confingured to Window authentication, and if it is 2 then it is Mixed mode authentication.

Go to services and stop all the sql server related services, before making the change.
Double click on the LoginMode subkey, in the DWORD Editor dialog, set the value as 2.
Restart all the SQL related services
This procedure will change the authentication mode to mixed mode, so that we can use “sa” user for login. But by default “sa” may not be enabled.

Enabling sa account


Go to command promprt type “osql -S localhost\SqlExpress -E”
This will authenticate you with windows authentication, to the local sql express. You will get 1> sign for accepting the Sql commands
You need to give sa a stong password because of security reasons.

You can do this by this was “sp_password @old = null, @new = ‘complexpwd’, @loginame =’sa’; ” and type “go”
Type “ALTER LOGIN sa ENABLE” and “GO”, will enable the sa account.

Type quit, and try login using sa, like this “osql -S localhost\SqlExpress -U sa -P mypassword”.

If everything worked fine, you will get a prompt 1>