Pages

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, December 9, 2013

How to add web browser in C#

The Web Browser control in C# allows you to host Web pages and other web browser enabled documents in your Windows Forms applications. You can add browser control in your C# projects and it displays the web pages like normal commercial web browsers .You can use the Browser control to provide integrated HTML based user assistance or Web browsing capabilities in your application.



The The Web Browser control has several properties, methods, and events related to navigation. The following C# program displays a web page in browser window and also you can retrieve the source code of the same web page with another button click.

using System;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            webBrowser1.Navigate(textBox1.Text );
        }

        private void button2_Click(object sender, EventArgs e)
        {
            String source = ("viewsource.txt");
            StreamWriter writer = File.CreateText(source);
            writer.Write(webBrowser1.DocumentText);
            writer.Close();
            Process.Start("notepad.exe", source);
        }
    }
}

Sunday, December 8, 2013

How to find IP Adress of a computer

Network programming in windows is possible with sockets . C# simplifies network programming through its namespaces like System.Net and System.Net.Sockets . The System.Net classes provide functionalities that is similar to Microsoft WinInet API.

The System.net namespace provides the information about IP Address . The following C# program shows how to find the IP Address of a host.

using System;
using System.Windows.Forms;
using System.Net;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                IPHostEntry hostname = Dns.GetHostByName(textBox1.Text );
                IPAddress[] ip = hostname.AddressList;
                textBox2.Text  = ip[0].ToString(); 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

How to find hostname of a computer in c#.net

The System.Net classes provide functionalities that is similar to Microsoft WinInet API , it allows classes to communicate with other applications by using the Hypertext Transfer Protocol (HTTP), Transmission Control Protocol (TCP), User Datagram Protocol (UDP), and Socket Internet protocols.
The following C# program show how to find the Host name of a computer.

  Dns.GetHostName()

using System;
using System.Net;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show (Dns.GetHostName());
        }
    }
}

Monday, December 2, 2013

Generating Random date and time




private void button1_Click(object sender, EventArgs e)
{
DateTime dt = new DateTime();
dt=DateTime.Now.AddDays(new Random().Next(1000));
MessageBox.Show(dt.ToString());

}

Wednesday, August 21, 2013

5 common exceptions in c# and their solution in .net


In this article we will see how to handle few very common exceptions in C#. Before start with example let’s learn what is exception exactly!

Exceptions are one kind of event that occurs when something goes wrong. And when it will go wrong no one knows. For example “Stack overflow exception” , Your program in working perfectly with small amount of input but somehow if it gets large number of input then “Stack overflow exception” might happen. But again we don’t know when program will get huge amount of input. Let’s start with few simple examples.

1 ) Null Reference Exception


This exception occurs when we try to work with null value with some function when that particular function is not capable to handle null String or null value. Have a look on below code to understand properly.


using System;
namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
               
string String = null;
               
Console.WriteLine(String.ToString());
            }
            catch (NullReferenceException)
            {
               
Console.WriteLine("NullReferenceException!");
            }

            Console.ReadLine();

        }
    }
} 

2) Argument out of range Exception


This exception occurs when we try to access any element with it’s but index is not present in collection. In below example we are trying to access 10 th element but we have added only one element into it.


using System;
using System.Collections;
namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
               
ArrayList list = new ArrayList();
               
list.Add(1);
               
Console.WriteLine("Item 10 = {0}", list[10]);
            }
            catch (ArgumentOutOfRangeException x)
            {
               
Console.WriteLine("ArgumentOutOfRangeException Handler");
            }
            Console.ReadLine();

        }
    }
} 

3) Overflow exception


This type of exception may occur when we try to convert one data type to another data type where target variable is not capable to store whole result. In below example we are using check keyword to check overflow of conversion.


using System;
using System.Collections;
namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {

            int Integer = 1234500;
            long Long = Integer;

            try
            {
               
long c = checked(Long * 99999999999999);
            }
            catch (OverflowException e)
            {
               
Console.WriteLine("Type cast overflow exception");
            }
            Console.ReadLine();

        }
    }
} 

4) Divide by zero exception


It’s one kind of Arithmetic exception which occurs when we try to divide a number with zero. Theoretically the result is infinitive but in computer programming it’s not allowed.   


using System;
using System.Collections;
namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
               
int y = 0;
               
y = 10 / y;
            }
            catch (DivideByZeroException e)
            {
               
Console.WriteLine("Devide by zero exception");
           }
            Console.ReadLine();

        }
    }
} 

5 ) SQL Connection


SQL connection is one of the common exceptions in any application. It happen when there is something wrong with database connection. In below example we did not assign connection string but tried to open connection, hence SQL exception has occur.


using System;
using System.Collections;
using System.Data.SqlClient;
namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
               
SqlConnection con = new SqlConnection();
               
con.Open();
            }
            catch (Exception e)
            {
               
Console.WriteLine("SQL connection error");
            }
            Console.ReadLine();

        }
    }
} 
 

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.

 

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