Pages

Wednesday, August 21, 2013

how to generate random number when you click on refresh button in .net?

This article will explain how to generate a random number

Add new item it solution explorer

drag and drop the text box and label
.aspx page:
design mode:
aspx
source:
<table><tr><td>RANDOM NUMBER:</td><td><asp:TextBox ID="txtrobocomp" runat="server"  Font-Names="Vivaldi"
                        Font-Size="X-Large" Font-Bold="True" BackColor="#CC99FF" ForeColor="#CC0066"
                        Width="148px" Height="33px"></asp:TextBox></td></tr>

code in .aspx.cs page:
private int RandomNumber(int min, int max)
    {
        Random rd = new Random();
        return rd.Next(min, max);
    }

    private string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random rd = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rd.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    } 

The output will be seen like this

random
After refreshing the page randomnumber will be generated
Place a refresh button in .aspx page
Image will shown like this
refresh
code in .aspx.cs page
in page load event
 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(RandomNumber(10, 99));
            builder.Append(RandomString(3, true));
            builder.Append(RandomString(2, false));
            txtrobocomp.Text = builder.ToString();
        }
    }
code in refresh button click event
 protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            //if (!Page.IsPostBack)
            //{
                StringBuilder builder = new StringBuilder();
                builder.Append(RandomNumber(10, 99));
                builder.Append(RandomString(3, true));
                builder.Append(RandomString(2, false));
                txtrobocomp.Text = builder.ToString();
            //}
         }

the output will be like this
 
After clicking on refresh button the same as our captcha image
the output will be like this the random number is changed in particular text box
If you click on refresh button the random number will be generated by using the code above we can generate a random number and refresh button it will be seen like our captcha image

I hope you understand this article and will be useful. 

Access data from any database using Dbprovider class in .net

In this article we will see how to implement uniform data access mechanism to support various database platforms. Before going to discussion we will discuss little importance of that and few related topic like factory design pattern.

Let’s discuss what the advantages of uniform data access mechanism. OK, think about a product which your company is developing for their customer. Now, in requirement analysis part customer did not specify their preferred database software.   

If you write code for SQLServer in project and after that if client wanted to use Oracle? –To solve this problem it is needed to implement data access mechanism in platform independent fashion.

Now, what is the fashion? Here we will use concept of factory design pattern. In .NET framework one nice Interface called Dbprovider has given to do this job.
In factory design pattern, we can create object in run time.  In run time user will supply some information to factory class and depending on supplied information factory class will create object.
Let’s see below code to implement same.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using PIHelper;
using System.Data.Common;

namespace WindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
          
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            DbProviderFactory provider = null;
            DbConnection con = null;
            DbCommand cmd = null;
            DbDataReader rdr = null;
            DataTable dt = new DataTable();
            
            provider =DbProviderFactories.GetFactory("System.Data.SqlClient");
            con =
provider.CreateConnection();   //Create Connection according to Connection Class
            con.ConnectionString = "Data Source=Nayab\\SQL_INSTANCE;Initial
Catalog=test;Integrated Security=True";
            cmd =
provider.CreateCommand();   //Create command according to Provider
        
            try
            {
                cmd.CommandText = "select * from name";
                cmd.CommandType = CommandType.Text;
                if (con.State == ConnectionState.Closed ||
con.State == ConnectionState.Broken)
                {
                    con.Open();
                    cmd.Connection = con;
                    using(con)
                    {
                        rdr =
cmd.ExecuteReader(CommandBehavior.CloseConnection);
                        dt.Load(rdr);

                        if (dt.Rows.Count > 0)
                        {
                            //return dt;
                            this.dataGridView1.DataSource = dt;
                        }
                        else
                        {
                            this.dataGridView1.DataSource = null;
                        }
                          
                    }
                }
            }
         
            catch
(Exception ex)
            {
                throw;
            }
            finally
            {
                //trn.Rollback();
                con.Dispose();
                cmd.Dispose();
            }
            
        }
        
    }
}

This is the whole code of a windows form. I will suggest you to look at button’s click event. If you look closely you can find we are not creating any ADO.NET object for any specific database provider. All objects are getting created depending on database provider.
Here we are supplying provider string of SQLServer class. And if you want to access data from any other database just change the provider name and it will work perfectly. In below the code portion need to change.

DbProviderFactories.GetFactory("System.Data.SqlClient");
Here is sample output:

3 important properties of Exception class

Here we will discuss three very important properties of exception class. In any project development exception handling and log in is very crucial part. Log proper message and enough is very important. It will helpful to developer for next step.

Now, question is how we will log proper message about information! We have to extract proper message and information from exception object by setting few properties. Here we will discuss three important properties one by one.

Message property to get message from exception location

Message property will supply message from exception location. We can log this information to know exact message regarding exception. Here is sample code to do same.


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using PIHelper;
using System.Data.Common;

namespace WindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
          
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
          // Exception handeling
                try
                {
                    throw new Exception("My created exception");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        }
        
    }
} 

Here is sample output:

Stack Trace to detect original location of exception


Stack tracing is very important when one function call to another any exception comes from chain of function calling. For example function A is calling to function B again function B is calling to function C . Now, if C throws exception and we want to detect it from function A then we have to use StackTrace property of Exception class. Here is sample code for example.


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using PIHelper;
using System.Data.Common;

namespace WindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
          
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
          // Exception handeling

            try
            {
                throw new Exception("My created exception");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace);
            }


        }
        
    }
}

In output screen we are seeing actual location of exception.


Inner exception to get information of original exception object


In conductive function calling scenario if any inner function throws exception it may replace by other exception when it re throws by different catch block.
And if we want to get information about original exception object we have to use InnerException property of Exception class. Here in sample code and implementation.


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using PIHelper;
using System.Data.Common;

namespace WindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
          
        }

        public void MakeException()
        {
            try
            {
                throw new ApplicationException("My created exception");
            }
            catch (Exception mainE)
            {
                throw new Exception("Exception String",mainE);
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
          // Exception handeling

            try
            {
                MakeException();
            }
            catch (Exception ex)
            {
MessageBox.Show(ex.InnerException.Message.ToString());
            }
        }
        
    }
} 

Here is sample output.

 

Fetch data from multiple tables using Store procedure

It is another technique to fetch data from multiple tables. At first we have to create one store procedure like below
create procedure fetchdata
as
      begin
            select * from name
            select * from friend
      end


Then we will all this store procedure using ADO.NET code. In below code we are calling store procedure using single SqlCommand object.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
           
InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
          
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection();
           
con.ConnectionString = "Data Source=Nayab\\SQL_INSTANCE2;Initial Catalog=test;Integrated
Security=True";
            con.Open();

            SqlCommand cmd = new SqlCommand();
           
  cmd.CommandText = "fetchdata";
           
  cmd.CommandType = CommandType.StoredProcedure;
           
           cmd.Connection = con;

           SqlDataAdapter ad = new System.Data.SqlClient.SqlDataAdapter();
           
  ad.SelectCommand = cmd;
           DataSet ds = new DataSet();
           
  ad.Fill(ds);

           this.dataGridView1.DataSource = ds.Tables[0];
           this.dataGridView2.DataSource = ds.Tables[1];

        }
        
    }
}



Fetch data from multiple tables using query

Here we will combine two SQL queries within single command and using dataset we can store data separately into two DataTable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace WindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
           
InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
          
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection();
           
con.ConnectionString = "Data Source=Nayab\\SQL_INSTANCE2;Initial Catalog=test;Integrated Security=True";
           
 con.Open();

          SqlCommand cmd = new SqlCommand();
           
 cmd.CommandText = "select * from name;select * from friend";
           
cmd.Connection = con;
         SqlDataAdapter ad = new System.Data.SqlClient.SqlDataAdapter();
           
ad.SelectCommand = cmd;
         DataSet ds = new DataSet();
           
ad.Fill(ds);

            this.dataGridView1.DataSource = ds.Tables[0];
            this.dataGridView2.DataSource = ds.Tables[1];

        }
        
    }
}

3 advantages of @ symbol in C#

Here we will see three different advantages of @ symbol in C# application.

In front of C# keyword


We can use @ symbol in front of any keyword in C# and we can suppress general meaning of that keyword. For example, in below program we have used @ symbol in front of if and while, very known keyword of C# but using @ symbol we can use them as normal variable. To control if and while loop we have used if and while keyword simultaneously.


using System;
using System.Collections;
using System.Globalization;

namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
            int @if; // use if as an identifier and suppress it's general meaning
            int @While = 0;

            for (@if = 0; @if < 10; @if++)
Console.WriteLine("Value is " + @if);

            while (@While < 10)
            {
Console.WriteLine("Value is " + @While);
@While++;
            }
            Console.ReadLine();
        }
    }
}

To preserve white space


We can preserve white space using @ symbol before long string. In below example we have declared a long string with lot of white space and newline character. As we have used @ symbol the string preserve its state as it is.

using System;
using System.Collections;
using System.Globalization;

namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
            String Name = @"Thsi
                            is 
                            my 
                            name
                            ";
            Console.WriteLine(Name);
            Console.ReadLine();
        }
    }
}

To insert special character within string


If we want to insert any special character within string then we have to use @ symbol in front of string. In below example we have declare a string which contents few special character like ‘and \ symbol. This is very useful to prevent SQL injection attack in application.


using System;
using System.Collections;
using System.Globalization;

namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
            String str = @"Thsi ' is \n complex string";
            Console.WriteLine(str);
            Console.ReadLine();
        }
    }
}


How to pass an array in a Query String?

Today I am going to give an example of passing an array in a query string. We have two pages one isSender.aspx and second is Receiver.aspx. We will create the ArrayList in Sender.aspx and sent it to Receiver.aspx.

Code in Sender.aspx

//Create instance of ArrayList
ArrayList arrTest = new ArrayList();

//Add element into arraylist
arrTest.Add("1");
arrTest.Add("2");
arrTest.Add("3");

//create query string value using join method String class
string strQueyString = String.Join("||", ((string[])arrTest.ToArray(typeof(String))));
           
//sending arrayliat values to Reciver.aspx
Response.Redirect("Receiver.aspx?param=" + strQueyString); 


Code in Receiver.aspx
//get the value of query string
string[] param = Request["param"].ToString().Split('|');
//create array list
ArrayList arrTest = new ArrayList();
foreach (string str in arrTest)
{
    arrTest.Add(str);
}


Note: - You have to ensure that your array string's length doesn't exceed the permissible maximum length of query string.
Happy coding!