Saturday, March 27, 2010

.NET 4.0- A new method StringBuilder.Clear() to clear stringbuilder

With Microsoft.NET 4.0 we have a convenient method called clear method which will clear string builder. This method is very use full where we need to use string builder for multiple string manipulation. So we don’t need to create a separate string builder for it. Let’s take a simple example which will print string builder string before,after clear so we can see how it works. Following is simple console application for this.

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Text.StringBuilder myStringBuilder =
new System.Text.StringBuilder(string.Empty);
myStringBuilder.Append("This is my string");
Console.WriteLine("String Builder Output Before Clear:{0}",
myStringBuilder.ToString());
myStringBuilder.Clear();
Console.WriteLine("String Builder Output After Clear:{0}",
myStringBuilder.ToString());
myStringBuilder.Append("This is my another string");
Console.WriteLine("String Builder Output After new string:{0}",
myStringBuilder.ToString());
}
}
}
Here is a output as expected.Strinbuilder

Technorati Tags: ,
Shout it
kick it on DotNetKicks.com
Share:

Dynamically creating Meta Tag from ASP.NET 2.0/1.1

Search Engine optimization is very important to any web site today you can’t get more visitors except search engine optimization.In asp.net site we can also create dynamic meta tags as per our requirement for each page very easily. I will going to show you the two ways of adding meta tags dynamically one for asp.net 2.0 and other for any asp.net version. Lets look first that way and then we will look another way. First you have to add runat=”Server” in your head tag like following.

<head id="Header" runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
Then you need to write following code to create metatags dynamically.

protected  void Page_Load(object sender, EventArgs e)
{

HtmlMeta keywords = new HtmlMeta();
keywords.Name = "keywords";
keywords.Content = "DotNetJaps-An asp.net blog";
Header.Controls.Add(keywords);

} 
Now let look at another way of doing this.Here you can to create a static function which will return the string and that string contain the dynamic metatags.

public static string SiteMetaTags()
{
System.Text.StringBuilder strMetaTag =
new System.Text.StringBuilder(string.Empty);
strMetaTag.AppendFormat(@"<meta content='{0}' name='Keywords'/>",
"DotNetJaps-An asp.net blog");
return strMetaTag.ToString();
}
Then we have to call that function from asp.net page html like following.

<head >
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<%=SiteMetaTags()%>
</head>
That’s it it will be render as met tag in you asp.net page.Hope this will help you..

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:

How To Access Control On Master Page From Content Page

It a common requirement that you have change the master page content from content page. For example you have welcome label control that is there in master page and you want to change the welcome message after user logged in from the content page. Same way there might be another requirement like you need to bind a menu from content page as per user logged in having rights. In such kind of case use find control() method to access control on master page from the content page.You can find any control of master page like grid view,repeater and other controls. Let’s take above scenario where you have a label called lblWelcome in your master page and you need to change welcome message from content so first we have to create a label in master page like following.

<asp:Label ID="lblWelcome" runat="server"></asp:Label> 
Then with the help of find control method you have to first find the control with id and then you have to typecast that control as label and then you can do same thing as you can do with label.Here our requirement is changing welcome message so we are changing text of it.Like following.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label lblWelcome = Page.Master.FindControl("lblWelcome")
as Label;
lblWelcome.Text = "Welome message from content page";
}

}
So that’s it you can easily access master page control from the content page. Hope this will help you

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:
Thursday, March 25, 2010

Important milestone achieved 1,50,000 Visit completed for blog

I started blogging for fun but when i involved as blogger i understand power of blogging. From blog we can connect to people directly we can find reactions of our post sometimes good some time harsh comment but it was quite learning experience. On this occasion i thank all the dotnetjaps reader for providing great support keep reading my blog i am going to post lots things and nowadays i am posting everyday something new. Previous three years was great for my career as well as for this blog. I never expect huge response from  reader but it was great and inspiring me to do more and more blogging. Thank you very much readers.

Here are some of the most popular post from the site meter.

  1. Singleton class in C#
  2. How to disable right click in Ms Web Browser Control of VB/C#.NET 2005
  3. gradient background control
  4. How to take Screenshot in C#
  5. Enumeration in C#.NET,VB.NET

I once again thanks all the readers from the bottom of my heart  and keep reading this blog.

Technorati Tags: ,,
Shout it
Share:
Wednesday, March 24, 2010

ASP.NET- Using span tag instead of label for performance

In ASP.NET controls used in to the user controls are generate Client Id which unique for the control and If you have so many user controls hierarchy then you will have very long client id like ‘ctl00_CPH_ctl02_BM_userLogin_UserName’.It will increase the Kilo Bytes of html rendered in the browsers. Label control is the control which is used to display text and its render as span tag in the html render by the browser. So in such type of scenario if you have so many label controls then your html is going to increase very much. And overall it will decrease the your application performance.

In asp.net 4.0 we can manage the Client Id via different options i have already posted over here. But for asp.net 3.5 and lower version we have to write our own code for doing that there are two options either we have to create a our own custom control inherited from label which override the ClientID generated by system or we can use the span tag instead of label control because ultimately label control will be rendered as span tag in browser.

We having same scenario in the one of the project we are having so many label controls in one of the form in our page. So it is going to kill our application because rendered HTML will be heavy. So we have decided to use span tag. Now you guys are having questions that how we can manage span text from the server side we have used static string variables for to manage the text of span. Let’s create a simple example to understand how its works.

We have created a static string which will contain the text for the label. We are assigning text in page_load event of page or control then we have used that static string directly in html in between span tag which will have same style sheet as label control. Following is code for that.

protected static string UserName;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//asssign text here for first time
UserName = "User Name";
}
}
Now in the html of user control or page you need to write span tax as follows.
<span class="label"><%=UserName%></span>
That’s it will render span tag in your browser with same look as label and there will not be any id generated for this span tag and ultimately your html rendered in browser will have less Kilo Bytes. We able to reduce 10 to 12 KB bytes of our page via this technique. Hope this will help you too..

Technorati Tags: ,,,
Shout it
kick it on DotNetKicks.com
Share:
Tuesday, March 23, 2010

IIS Error: The process cannot access the file because it is being used by another process.

Recently in our one of the web servers all the sites using port 80 were stopped and when we tried to restart website it was giving error like process cannot access the file because it is being used by another process. After analyzing and diagnosis and searching on internet for the same problem i have found that it was a problem due to port 80 was used by another process. To solve the problem i have following command which will list IPs,PID(Process ID) and port that used by the process. The command is as below.

NETSTAT -ano
After running that command in command in command prompt it will give output like following.

IIS Error, IIS 6.0, IIS 7.0

From that output you can fine which port is used by which PID(Process Id). And then you can find the process from task manager. Process Id column in task manager is not enabled by default so you can do by View Menu->Select Column a following dialog box will appear.

ProcessId

Select PID (Process Identifier) and press OK.Now process Id will appear in task manager and in task manger go to processes tab where you can find out process by checking process id column then select that process right click->click End Process that will kill that process. Now again try to restart the IIS Site it will restart. In my case it was java updater who is using same port 80 and after killing my IIS Sites were ok. Hope this will help you..

Technorati Tags: ,

Shout it
kick it on DotNetKicks.com
Share:
Monday, March 22, 2010

C# 4.0-string.IsNullOrWhiteSpace()

We already have string.IsNullOrEmpty() method to check whether the string is null or empty.Now with Microsoft.NET Framework 4.0 there is a new another method that is called string.IsNullOrWhiteSpace() which will also check whether string is having whitespaces or not with null and empty string.This method is help full where we can check string is having whitespace rather then its empty or null. It will return a true if a string is empty,null or its having whitespaces. Let’s create a simple example and will see how its works. Here we are going test it with 4 options Empty string,Normal String,White spaces and Null String. Following is a code for that.

class Program
{
static void Main(string[] args)
{
string TestString = string.Empty;
Console.WriteLine("Test with empty string:{0}",
string.IsNullOrWhiteSpace(TestString));
TestString = "Normal String";
Console.WriteLine("Test with normal string:{0}",
string.IsNullOrWhiteSpace(TestString));
TestString = " ";
Console.WriteLine("Test with whitespace:{0}",
string.IsNullOrWhiteSpace(TestString));
TestString = null;
Console.WriteLine("Test with null:{0}",
string.IsNullOrWhiteSpace(TestString));
Console.ReadLine();
}
}
Following is a output of the above code here you can see its returning false with Normal string and for all other options its returning true as expected.
image

Shout it
kick it on DotNetKicks.com
Share:
Sunday, March 21, 2010

C#-Constructors,Static Constructors and Destructors Execution in Inheritance

While taking interview for .NET Technologies i often ask about the execution sequence of the constructor and destructor in inheritance But from the my experience i have found that lots of people are still confused with execution sequence of constructor and destructors. Lets create a simple example and learn some basic things that is very important while using inheritance in C#.

  • Constructors will be executed in from parent to child sequence means first parent class constructor will be executed then after that child class constructor will be executed.
  • Destructors execution order is reverse then constructors first it will execute child class destructor and then it will execute the parent class destructor.
  • Static constructors are different then the normal constructors and its executes when first object of class is created it will be executed. Most of people are very confused this kind of scenario in inheritance. Here scenario will be like when the first object of child class created then it will execute the child class static constructor and then after the parent class static constructor is executed. After that it will never got executed.

Lets create a simple class which will illustrate the above worlds. First lets create a class A with constructor,destructor and a static constructor.

public class A
{
static A()
{
System.Console.WriteLine("A Static Constructor");
}
public A()
{
System.Console.WriteLine("A public constructor");
}

~A()
{
System.Console.WriteLine("A Destructor");
}
}
Now we will inherit this class with the another class B which is also having constructor,destructor and a static constructor.
public class B : A
{
static B()
{
System.Console.WriteLine("B Static Constructor");
}
public B()
{
System.Console.WriteLine("B public constructor");
}

~B()
{
System.Console.WriteLine("B Destructor");
}
}
Now lets create two objects of Class B in main function of our console application to see how constructors works and after that we will destroy the object via assigning null values and then forcefully we will do Garbage Collection via GC.Collect() to see how destructors works below is the code for that.
 class Program
{
static void Main(string[] args)
{
B b1 = new B();
B b2 = new B();
//code return to destroy object of a class
b1=b2 = null;
GC.Collect();
Console.ReadLine();

}
}
After running the console application output will be as follows.

Construcotr-Destructor in Ineritance,C#

As you can see static constructors are only executed when the first object of a class is created and Constructors are executed like parent to child way and in reverse destructors are executed from child to parent way. Hope this will help you understand execution sequence of constructor in inheritance.

Shout it
kick it on DotNetKicks.com
Share:

Singleton Class in C#

Singleton pattern is very popular pattern used by programmer. The idea behind the singleton pattern is to have only one instance of a class at any time. This kind of pattern is very useful for for heavy resources like Linq Data Context etc. It is also useful in multithreaded application where different thread of application try to crate instance of one class but it should be thread safe. It can be also useful for global resources and state objects. In singleton class there are two things required. One static variable which hold the instance of class and other is a static method which will return the instance of singleton class. Here is the example of singleton class

 public class MySingleTon
{
private static MySingleTon mySingleTonInstance = new MySingleTon();

private MySingleTon()
{
//private constructor
}
public static MySingleTon GetInstace()
{
return mySingleTonInstance;
}

}
Now we are done with calling single ton class like following.
 MySingleTon objSingleTon = MySingleTon.GetInstace(); 
The above example is not thread safe so it may be possible that different thread can create different instance of classes. To make above singleton class thread safe we need to change code like following.
   public class MySingleTon
{
private static MySingleTon mySingleTonInstance = new MySingleTon();

private MySingleTon()
{
//private constructor
}
public static MySingleTon GetInstace()
{
lock (typeof(MySingleTon))
{
if (mySingleTonInstance == null)
{
mySingleTonInstance = new MySingleTon();
}
return mySingleTonInstance;
}

}
}
Hope this will help you…

Shout it
kick it on DotNetKicks.com
Share:
Saturday, March 20, 2010

Visual Studio 2010-Automatically Adjust Visual Experience.

Visual studio 2010 is great IDE and i am discovering everyday some thing new. Today i have discovered one of fantastic option to increase performance of your visual studio IDE. Visual Studio 2010 has option when we enabled it it will automatically adjust the visual and client experience as per your hardware configuration. It will increase the performance of visual studio and productivity in lower hardware also. You can find that checkbox under Tools->General-> Automatically adjust visual experience based on client performance. There are two checkbox is given one for above and another for Rich User Experience but they may decrease your visual studio performance. Like following.

Visual Studio 2010, User Experience

Shout it
kick it on DotNetKicks.com
Share:

Indexer class in C#

While taking interviews for Microsoft.NET i often ask about indexer classes in C#.NET and i found that most of people are unable to give answer that how we can create a indexer class in C#.NET. We know the array in C#.NET and each element in array can be accessed by index same way for indexer class a object was class can be accessed by index. Its very easy to create a indexer class in C#. First lets looks some points related to indexer class in C#.

  • Indexer class object can be accessed by index only.
  • We can use same mechanism to access object of indexer class as we are doing it for array.
  • You can can specify any valid C# type as return type of indexer classes.
  • You must have to create a property with parameter using this keyword for indexer class.
  • You can also implement multi parameter indexer also.

Let’s create simple indexer class with single parameter and for string type.

 public class MyIndexer
{
private string[] MyIndexerData;
private int SizeOfIndexer;

//declaring cursor to assing size of indexer
public MyIndexer(int sizeOfIndex)
{
this.SizeOfIndexer = sizeOfIndex;
MyIndexerData = new string[SizeOfIndexer];
}

public string this[int Position]
{
get
{
return MyIndexerData[Position];
}
set
{
MyIndexerData[Position] = value;
}
}
}
Now we done with indexer class and lets create object of that indexer class and will see output of our console application also. Following is the code for that.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int indexSize=5;
MyIndexer objMyIndexer = new MyIndexer(indexSize);
for (int i = 0; i < indexSize; i++)
{
objMyIndexer[i] = i.ToString();
Console.WriteLine("Indexer Object Value-[{0}]: {1}",
i, objMyIndexer[i]);
}
Console.ReadKey();
}
}
}
and Here is the output for the indexer class console application.

Indexer Class Example in C#,Indexer Class,C#

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:

Microsoft.NET 4.0/VB.NET 10 Automatic Properties

In C# we are having automatic properties since C# 3.5 framework but now with Microsoft.NET 4.0 Framework VB.NET 10.0 version we are also having automatic properties for VB.NET Also.

Like in C# we can define automatic like following.

Public string TestProperty
{
get;
set;
}
Same way we can define in automatic Property in VB.NET as follows.
Public Property TestProperty As String 
You can use this properties any where in class same as C# automatic property.

Shout it
kick it on DotNetKicks.com
Share:

ASP.NET and Load balancing.

In one of our project the site usage of site was very heavy and we need to migrate it to load balancing server. I have never configured the sites in the load balancing server but it was quite interspersing experience Here are the some points which we need to take care while we move asp.net sites into the load balancing environments. So first we will see what is load balancing.

Following is a load balancing definition from the Google.

In computer networking, load balancing is a technique to distribute workload evenly across two or more computers, network links, CPUs, hard drives, or other resources, in order to get optimal resource utilization, maximize throughput, minimize response time, and avoid overload.

Following are the points which you need to take care when you are deploying your asp.net sites into load balancing server environments.

Machine Key Should be same for both servers: View state and session both are depends on the machine key. If you machine key is not same then you will have problems related to session and view state you may loose your session and view state in between request during post backs. If machine key will not be same then its possible that you can get strange result in Ajax requests. There is a machine key section in web.config where you can specify machine key.

<machineKey validationKey='C44B8B7C521CB5BC7E602BAE6118AA44CD690C7304817129DA27C17E800132A1BD946C6D9AD12F0A5B342840C7D130564195428160B7466146938CA9E3A62686'   decryptionKey='0E9DF2DA7F210B84087690FF0BF25C905182AD81E16A5FA9'   validation='SHA1'/>
Session Configuration: Any web application is not possible without having session as web pages are stateless so you can configure session in load balancing also. There are two configuration which can be used in load balancing environments. One is state service and another is Storing session in SQL Server.

Following is a good link to learn how you can configure sessions state in asp.net application.

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0d9dc063-dc1a-46be-8e84-f05dbb402221.mspx?mfr=true

And here is a good link to configure session on SQL Server.

http://support.microsoft.com/kb/317604

You can configure session state mode in your web.config like following.

<sessionState mode="SQLServer" StateConnectionString="tcpip=127.0.0.1:42424"

SqlConnectionString = "data source=SERVERNAME; user id=sa; password=sa"

cookieless="false" timeout="20" />

enableViewStateMac="false": This is a alternative approach to machine key. This will tell asp.net engine that whether it should check Machine authentication check or not and if you made it false then it will not check for machine authentication. You can define that in your web.config pages section like following.
<system.web>
<pages enableViewStateMac="false" />
</system.web>
Caspol Utility: You can use caspol utility to share some resources on between load balancing servers. Like we have file base cache dependency in our application so we have created a central location(A shared folder for cache files) for the both the server and used Caspol utility to give full trust share on that folder for load balancing servers. Following are some of the good links to which will teach how you can use CasPol utility to for asp.net application

http://blogs.msdn.com/shawnfa/archive/2004/12/30/344554.aspx

http://forums.asp.net/p/1119925/1881331.aspx#1881331

http://www.eggheadcafe.com/software/aspnet/30227544/caspol-addfulltrust.aspx

File Replication:File Replication is also an important features of load balancing you should have replication enabled on the folders of web application so if you upload anything on one server it should replicated to other sites. Following is good link to understand file replication.

http://www.tgrmn.com/web/kb/item28.htm

Sticky Sessions:
In some scenario Sticky session is very useful. In one page our application we have used extensive Ajax and we need that for each request and partial post back it should stay on one server till request completes.To achieve that we can used sticky session. Following are some good links to know about sticky sessions.

http://dev.fyicenter.com/Interview-Questions/JavaScript/What_does_the_term_sticky_session_mean_in_a_web_.html

http://blogs.msdn.com/drnick/archive/2007/07/13/sticky-sessions.aspx

Hope this will help you on deploying your asp.net on load balancing sites. Following are some good links for understanding load balancing in more details

http://technet.microsoft.com/en-us/library/bb742455.aspx
http://support.microsoft.com/kb/323437
http://technet.microsoft.com/en-us/library/cc754833%28WS.10%29.aspx.
http://edge.technet.com/Media/Network-Load-Balancing-NLB-in-Windows-Server-2008/

Shout it

kick it on DotNetKicks.com
Share:
Monday, March 15, 2010

Rename feature in Visual Web Developer 2010/Visual Studio 2010

Visual web developer is great tool and I am playing more and more with it and every time I am discovering some new features of it. Recently I have discovered a very cool feature of it. I want to rename a variable in visual studio 2010 Web Developer express edition and I found a great refractor tool for that which will rename that variable in all the instance and all the methods. First you need to select variable which you want to rename and then you need to Right Click ->Refractor->Rename. You can also invoke that via its shortcut Ctrl + R,Ctrl +R and it will be available For reference see the below screenshot.

Rename variable featuers in visual studio 2010

Once you click the rename which will have a dialog box open which will ask for new name or variable like following.

RenameDilaog option in visual web developer 2010

It is also having options for search in comments and search in string. Search in comment will search and replace in comment and search in string will replace word for any string which contains that variable name. Once you put new name in dialog box it will display a preview of replaced strings like following. Here also you can select where you need to rename and where you don’t want to rename and this is really cool. :)

Preview dialog for visual web developer 2010

Shout it
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews