$(document).ready(), pageLoad() and Sys.Application.add_init()

When I have basic understanding of AJAX and jQuery, I thought that $(document).ready(), pageLoad() and Sys.Application.add_init() are equivalent and they does the same job. In most of the samples they seems to behave in same way and I wondered that why there are too many ways to do the same thing. So I did bit research on this and I am sharing that with the developer community.

jQuery's $(document).ready()
This function is called when DOM is ready. Generally if browser supports DOMContentLoaded event, $(document).ready() will fire after this event. If browser do not support DOMContentLoaded, then when document achieve readyState, then $(document).ready() will be fired. If above two events are not available in Brower's event model then window.onload event is used to fire $(document).ready() event.

If you are using jQuery, then my No. 1 recommendation is this function as this will work on
all browsers. Here is a sample how you can use this function:-
$(document).ready(function () {
//Your code here
});

Application.Init
This event is fired only once when page is loaded first time. Remember, that if you are using update panel then this method will not be called whenever update panel refresh your page. So, this is best event when you want initialization which should be done only once and not after every update panel refresh.
<script type="text/javascript">
    Sys.Application.add_init(function () {
        // Your code here
    }); 
script>

ASP.NET AJAX's pageLoad() Method
As we all know java scripts runs as a single thread, pageLoad method uses a trick, it calls a setTimeout() function of JavaScript with 0. So, whenever DOM is ready and JavaScript execution is started, you  pageLoad() will be triggered.

Now, use this method when you want to call your code every time when your update panel gets refresh.
<script type="text/javascript">
    function pageLoad() {
        // Your code here 
    } 
script>
 
Note that to use AJAX methods you need to place ScriptManager object on  your page other wise they won't work.

Feel free to comment, Happy Coding !!!

How to dynamically change connection string in web.config

Most of people wonder how they can dynamically change the contents of web.config file. To simplify things I have created couple of functions through which you can change the contents of web.config file. Here is the code to change the contents of web.config file:-
/// <summary>
/// Updates the setting.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public void UpdateSetting(string key, string value)
{
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
    if (config.AppSettings.Settings[key] == null)
    {
        config.AppSettings.Settings.Add(key, value);
    }
    else
    {
        config.AppSettings.Settings[key].Value = value;
    }
    config.Save();
    ConfigurationManager.RefreshSection("appSettings");
}

/// <summary>
/// Updates the connection string.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public void UpdateConnectionString(string key, string value)
{
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
    if (config.ConnectionStrings.ConnectionStrings[key] == null)
    {
        config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(key, value));
    }
    else
    {
        config.ConnectionStrings.ConnectionStrings[key].ConnectionString = value;
    }
    config.Save();
    ConfigurationManager.RefreshSection("connectionStrings");
}

You can update the contents of web.cofig file by simply calling above functions like this:-
protected void Page_Load(object sender, EventArgs e)
{
    UpdateSetting("test", "123");
    UpdateConnectionString("testcon", "12345");
}

Unable to find the requested .Net Framework Data Provider. It may not be installed

Hi guys, I was on my holidays and enjoying something different so I was away for some time. However right now I am back and working on a Sliver light project. In that project I found an interesting situation which I would like to share with you. I was using Enterprise Library 5.0 for my connection string and I was using Oracle.DataAccess for my connection.

Here was the line on which I was getting error:-
dbase = DatabaseFactory.CreateDatabase("MyDB");


After spending some time I checked that every thing seems OK and there is no issue with my web.config file. I tried to replace CreateDatabase and use another way to create database connection in Enterprise Library:-
DbProviderFactory providerFactory =
DbProviderFactories.GetFactory("Oracle.DataAccess.Client");
dbase = new Microsoft.Practices.EnterpriseLibrary.Data
.GenericDatabase("data source=xxx;User id=xxx;Password=xxx;",providerFactory);

Above also did not solved my problem and I started to get another error :-

I checked that either I have installed ODP or not but It was installed in my GAC folder (usually at C:\Windows\assembly). Here is how my GAC folder looks like:-

Now finally I had a clue that what happened. My system have multiple versions of Oracle.DataAccess installed and .net can not decide that which version should be used. So, to Resolve this I have to add a DbProviderFactory in my web.config file. So here is how I added it:-
 <system.data>
    <DbProviderFactories>
    <add name="Oracle Data Provider for .NET"
            invariant="Oracle.DataAccess.Client"
            description="Oracle Data Provider for .NET"
            type="Oracle.DataAccess.Client.OracleClientFactory,
                  Oracle.DataAccess,
                  Version=2.112.1.2,
                  Culture=neutral,
                  PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>

Now last thing, I know that I have to use Oracle.DataAccess but how did I get other information i.e. Version, Culture and PublicKeyToken. To do this simply right click on the Assembly and take it properties. Here is the page that will appear through which you can get all the details:-

Finally my application started working and it connected to database perfectly. Hopefully this will also be useful for you . Do share your comments with me. Happy coding !!!



How to create Tag Cloud, Word Cloud or Weighted List

Tag Cloud, Word Cloud or Weighted List is the visual representation of keywords/tags on websites that shows the importance of keyword/tag. I am sharing a simple code to generate a Tag Could. You can download whole code from this location.

First I have created list of Tags. You can use database to fetch the tags and pass them to this list:-
//Creating a list of Tags
List<string> lst = new List<string>();
lst.Add("C#");
lst.Add("C#");
lst.Add("C#");

lst.Add("Asp .Net");
lst.Add("Asp .Net");
lst.Add("Asp .Net");
lst.Add("Asp .Net");
lst.Add("Asp .Net");
lst.Add("Asp .Net");


lst.Add("Javascript");
lst.Add("Javascript");
lst.Add("Javascript");

lst.Add("Ajax");
lst.Add("Ajax");

lst.Add("jQuery");

After that I used LINQ to find group by count of individual Tag. You can also perform that step on database level if you are reading records from database:-
//Grouping tags and calculate their count using LINQ
var tags = (from l in lst
            group l by l into g
            select new { Name = g.Key, Count = g.Count() });

After that I sort the tags in descending order because normally tags are in alphabetical order.
// Sort tags in descending order
tags = (from t in tags
        orderby t.Name descending
        select t);

Here is the interesting part, here you can define minimum font size and maximum font size for tag cloud. Also I calculated the steps which will be there for minimum and maximum size.
//Minimum Size for Tags, you can set it as per your need
double minSize = 10;

//Maximum Size for Tags, you can set it as per your need
double maxSize = 20;

//Calculating the step in which increament the fonts
double steps = (maxSize - minSize) / (double)tags.Count();

Finally I am creating SPAN tags for each tag item with this code:-
StringBuilder sb = new StringBuilder();
        foreach (var tag in tags)
        {
            //Calculating the Size
            double size = minSize + ((double)tag.Count - 1) * steps;

            //Create the SPAN tag with spefic font size so it looks like cloud
            sb.Append("<span style='font-size:" + size + "pt'>" + tag.Name + " </span>");
        }

And Here is the result of my tag cloud application:-
  
This seems good but not too good to me so I changed one line from my code like this:-
//Create the SPAN tag with spefic font size so it looks like cloud
      sb.Append("<span style='font-size:" + size + "pt'>" + tag.Name + "("+ tag.Count +") </span>");

And here is the result, I get the count after every tag:-
Hopefully this will be useful for you , do share your comments on that. Happy Coding !!!

Improve ASP.Net Performance by effective utilitzation of String

Many people ask me that how they can improve their website's performance? There are many ways through which you can improve the performance of your website but today, I will discuss the performance improvement with Strings.
In my opinion String is the most frequently used data type compared to other data types available. But there is a big problem with string, it is immutable. An immutable object is an object which cannot be modified. So whenever we try to change anything with string a new string object is created. These frequent creations of objects degrade the system's policy.

Avoid using "" as empty string

Every time when you write "" a new string object is created. But if you use string.Empty it will not create any additional string before assignment.
//bad practice
string str = "";

//good practice
string str1 = string.Empty;

Avoid .ToLower()/.ToUpper() for Comparison

Usually developers heavily use .ToLower() or .ToUpper() to perform case insensitive comparison. Instead you should use string.Compare function.
//Bad Practice
string errorCode= "ec-1001";
if (errorCode.ToLower() == "ec-1001")
{

}

//good Practice
string errorCode1 = "ec-1001";
if (string.Compare( errorCode1,"ec-1001",true)==0)
{
}

Also there are situations when we can control the case of a string i.e. generally we add 'M' or 'F' for gender. Now we can ensure that throughout application we either use capital 'M' or small 'm' to define male. A good approach is to use const in such cases.
const string Male = "M";
const string Female = "F";
string myGender = Male;

Avoid multiple string concatenation

Whenever you have to modify a string many times then consider using StringBuilder instead of simple string. Every time when you modify a string, a new object would be created. However, StringBuilder is mutable object and it performs string modifications without creating multiple objects.

//Bad practice
string text = "start";
text += "start 1";
text += "start 2";
text += "start 3";
text += "start 4";
text += "start 5";

for (int i = 0; i < 10; i++)
{
    text += "text " + i;
}

//Good Practice
StringBuilder sb = new StringBuilder();
sb.Append("start");
sb.Append("start 2");
sb.Append("start 3");
sb.Append("start 4");
sb.Append("start 5");

for (int j = 0; j < 10; j++)
{
    sb.Append( "text " + j);
}