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);
}

Drag and Drop in Siliverlight using Mouse

Recently I started working with Silverlight. It is really a wonderful tool from Microsoft and I am too excited about it. It gives developer the power to create impressive looking user interface. In this tutorial I will focus on drag and drop functionality in Silverlight using mouse. You can download complete source code from SilverLightMouseEvents.zip.

First create a new Silverlight Application project, here is how your project will look like:-



I have added event handlers for MouseLeftButtonDown,MouseLeftButtonUp,MouseMove and LostMouseCapture. I also added a canvax and a button in MainPage.xaml. Here is the code of MainPage.xaml after adding events:-

<UserControl x:Class="SliverLightMouseEvents.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="491" 
             MouseLeftButtonDown="UserControl_MouseLeftButtonDown" 
             MouseLeftButtonUp="UserControl_MouseLeftButtonUp" 
             MouseMove="UserControl_MouseMove" 
             LostMouseCapture="UserControl_LostMouseCapture">

    <Canvas x:Name="mainCanvas" Width="640" Height="480" >
        <Button Content="AddRectangle" Width="100" Height="30" Margin="12,258,378,12" Click="Button_Click" />
    </Canvas>
</UserControl>

On the button click I have added a rectangle to mainCanvas. Here is how it is done:-

private void Button_Click(object sender, RoutedEventArgs e)
{
    //Creating a rectangle
    Rectangle rectangle = new Rectangle()
    {
        Stroke = new SolidColorBrush(Colors.Black),
        Width = 100,
        Height = 100,
        Fill = new SolidColorBrush { Color = Color.FromArgb(200, 146, 5, 23) }
    };


    //Set its initial position
    Canvas.SetLeft(rectangle, 100);
    Canvas.SetTop(rectangle, 100);

    //Adding it to mainCanvas
    mainCanvas.Children.Add(rectangle);
}

Now first we have to handle MouseLeftButtonDown event. Here is the code:-

private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    //If mouse button is down and control on which button is pressed is rectangle
    if (e.OriginalSource.GetType() == typeof(Rectangle))
    {
        this.isMoving = true;

        //Calculate the current mouse's relative position
        clickOffset.X = e.GetPosition(mainCanvas).X - Canvas.GetLeft((Rectangle)e.OriginalSource);
        clickOffset.Y = e.GetPosition(mainCanvas).Y - Canvas.GetTop((Rectangle)e.OriginalSource);

        //Generate Mouse Events even if mouse is moved outside control's area
        CaptureMouse();
    }
}

One thing which you should remember when doing drag and drop is CaptureMouse() function. Many user will move their mouse outside your application while draging and if you do not write CaptureMouse() when mouse is outside you will recieve no events from mouse.

Now here is the code which I wrote in MouseMove event:-
private void UserControl_MouseMove(object sender, MouseEventArgs e)
{
    if (this.isMoving) //If mouse button is down
    {
        if (e.OriginalSource is Rectangle) //if control is rectangle
        {
            Rectangle rect = e.OriginalSource as Rectangle; //Get the original control

            //Changing its color so we can get the feel of selection
            rect.Fill = new SolidColorBrush { Color = Color.FromArgb(100, 146, 5, 23) };

            //Calculate the distance form initial mouse down and adjust top,left accordingly
            Canvas.SetLeft(rect, e.GetPosition(mainCanvas).X - clickOffset.X);
            Canvas.SetTop(rect, e.GetPosition(mainCanvas).Y - clickOffset.Y);
        }
    }
}

In above code, I adjusted the top,left of the Rectangle as per position of mouse.

Now when user release the mouse button, MouseLeftButtonUp event is fired. Here is the code which I written in MouseLeftButtonUp event:-

private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    //if mouse is moving
    if (this.isMoving)
    {
        //if control is rectangle on which mouse is moving
        if (e.OriginalSource is Rectangle)
        {
            //Change rectangle color back to normal
            Rectangle rect = e.OriginalSource as Rectangle;
            rect.Fill = new SolidColorBrush { Color = Color.FromArgb(200, 146, 5, 23) };
        }
        //Set moving to false
        this.isMoving = false;

        //Stop listening mouse events which are outside current control's boundary
        ReleaseMouseCapture();
    }
}

Finally here is the code of LostMouseCapture event, if you remove this code from my sample, it will behave weired when mouse goes outside control's area:-

private void UserControl_LostMouseCapture(object sender, MouseEventArgs e)
{
    if (this.isMoving)// if Previously mouse is clicked down
    {
        this.isMoving = false; //mark that mouse is now moved up
    }
}

Finally here is the output of the application:-