Pages

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

}

How to Remove Underline from Link button in asp.net?

It's very easy to remove Underline from Linkbutton. 

We can do it by following ways:- 

1). Write inline style property as 


<asp:LinkButton id="lnk_view" runat="server" Text="View Details" style="text-decoration: none; color: blue;">View Details</asp:LinkButton>


2).We can make a CSS for it 


 <style type="text/css">
        .link_Under_line_Blue
        {
            text-decoration: none;
            color: blue;
        }

    </style>

And in link button we can write as:-

<asp:LinkButton id="lnk_view" runat="server" Text="View Details" CSS="link_Under_line_Blue">View Details</asp:LinkButton>


And also every time you click on Linkbutton,the color of linkbutton will be remain as Blue with the help of "color:blue" style property.

Working with Promt in Javascript


Like Console application in Dot net,we can use the same thing with the help of Prompt in Javascript.Prompt means asking a user to enter something in the input box. 

We can understand it by an example:- 
Make a Javascript function as below:- 

 <script type="text/javascript">
        function prompt_alert() {
            var value = "";
            var name = prompt("Please enter your name", "Nayab");
            if (name != null) {
                value = name;
                alert(value);
            }
        }
    </script>

So,it's easy to understand about Prompt.






Tuesday, November 26, 2013

Five different ways to get the computer name in ASP.NET


Dim way1 As String = System.Environment.MachineName

Dim way2 As String = Server.MachineName

 Dim way3 As String = System.Net.Dns.GetHostName

 Dim way4 As String = My.Computer.Name

Dim way5 As String = System.Net.Dns.GetHostEntry(Request.ServerVariables("remote_addr")).HostName

Dim nl As String = ""

Response.Write(way1 & nl & way2 & nl & way3 & nl & way4 & nl & way5)

Tuesday, November 19, 2013

SQL Server–Error Handling using Try Catch Block

In this post, we will see how to handle errors in SQL Server 2005 and 2008. In SQL Server 2005, Microsoft has introduced a new construct to handle errors in SQL Server that is ‘TRY – CATCH’. It is similar to .NET ‘Try – Catch’ block for handling the exceptions. When an error is caught in a T-SQL statement which is inside the ‘TRY’ block, the control is automatically transferred to the ‘CATCH’ block.
We can then process the error in the ‘CATCH’ block.

So let’s see some examples of the TRY CATCH block for handling the errors in SQL Server. First let’s create two tables with a relationship between them as shown below –

USE master
GO
 
CREATE TABLE SampleCustomers 
(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(30), 
City VARCHAR(20) 
)
CREATE TABLE SampleOrders 
(
OrderID INT PRIMARY KEY,
OrderDate DATETIME,
RequiredDate DATETIME,
CustomerID INT REFERENCES SampleCustomers(CustomerID) 
)

Now let’s insert three records in ‘SampleCustomers’ table as shown below – 

INSERT INTO SampleCustomers VALUES(1,'PRAVIN','AP')
INSERT INTO SampleCustomers VALUES(2,'YASH','MUMBAI')
INSERT INTO SampleCustomers VALUES(3,'SAM','DELHI')

Insert few records in ‘SampleOrders’ table as a transaction, as shown below – 

SET XACT_ABORT ON
 BEGIN TRAN 
 INSERT INTO SampleOrders VALUES (100, GETDATE ()-1, GETDATE ()+5, 1)
 INSERT INTO SampleOrders VALUES (101, GETDATE ()-1, GETDATE ()+5, 4 ) 
 INSERT INTO SampleOrders VALUES (102, GETDATE ()-1, GETDATE ()+5, 2)
 COMMIT TRAN

Now select the records from both the tables as shown below – 

Select * from SampleCustomers

Select * from SampleOrders

Now select the records from both the tables as shown below – 

CustomerID CustomerName City
1                     PRAVIN                  AP
2                     YASH                  MUMBAI
3                     SAM                  DELHI

OrderID              OrderDate              RequiredDate               CustomerID


If you observe, we are using ‘XACT_ABORT ON’ statement before starting the transaction. Because of this statement set to ‘ON’, if the T-SQL statement raise the error, the entire transaction will be roll backed. So in the data above, data for ‘SampleOrders’ did not get inserted.

Now let’s try the same transaction by setting the ‘XACT_ABORT’ statement to ‘OFF’. The transaction will roll back the statements which has errors, but the other statements will get committed as shown in the following output –

CustomerID CustomerName City
1                     PRAVIN                  AP
2                     YASH                  MUMBAI
3                     SAM                  DELHI

OrderID          OrderDate                         RequiredDate        CustomerID
100        2013-11-18 19:29:02.333 2013-11-24 19:29:02.333 1
102        2013-11-18 19:29:02.343 2013-11-24 19:29:02.343 2

SET XACT_ABORT OFF 
BEGIN TRY 
    BEGIN TRAN 
        INSERT INTO SampleOrders VALUES(100,GETDATE()-1,GETDATE()+5,1) 
        INSERT INTO SampleOrders VALUES(101,GETDATE()-1,GETDATE()+5,4) 
        INSERT INTO SampleOrders VALUES(102,GETDATE()-1,GETDATE()+5,2) 
    COMMIT TRAN 
END TRY 
BEGIN CATCH 
    SELECT 
        ERROR_NUMBER() AS ErrorNumber, 
        ERROR_SEVERITY() AS ErrorSeverity, 
        ERROR_STATE() as ErrorState, 
        ERROR_PROCEDURE() as ErrorProcedure, 
        ERROR_LINE() as ErrorLine, 
        ERROR_MESSAGE() as ErrorMessage; 
        ROLLBACK 
END CATCH 


Now if you execute the above transaction which uses the ‘TRY-CATCH’ block, when an error occurs in a T-SQL statement, it moves the control from ‘TRY’ block to ‘CATCH’ block where we are rolling back the complete transaction. The output will show the error information by using couple of in-build error functions as shown below – 

ErrorNumber ErrorSeverity ErrorState ErrorProcedure ErrorLine ErrorMessage
2627              14              1               NULL              4         Violation of PRIMARY KEY...  


Thursday, August 22, 2013

How to detect client device using JavaScript

 Device detection is very important for web application. Sometimes there is different version of same website compatible for different device.

For example, think about one big e-commerce application where lots of information is there in home page. The organization may take decision that when people will browse from computer with high speed of internet then full website will get display and when people from different device (like mobile phone ,PDA etc  ) will browse it will redirect them to customized version of their website, where full features may not available.

Using JavaScript we can check which type of device client is using to browse our application.


<%@
Page Language="C#" AutoEventWireup="true" CodeBehind="CheckMobile.aspx.cs" Inherits="ASP.NET.CheckMobile"
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" language ="javascript">

        functionCheck()
         {
            if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|poc ket|kindle|mobile|pda|psp|treo)/i))||     
(navigator.userAgent.match(/iPod/i)) ||          
(navigator.userAgent.match(/operamini/i)) ||
                (navigator.userAgent.match(/blackberry/i))||
                (navigator.userAgent.match(/(palmos|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)/i))
||(navigator.userAgent.match(/(windowsce; ppc;|windows ce;
smartphone;|windows ce;iemobile)/i)) ||
            (navigator.userAgent.match(/android/i)))
{

                 alert("Deviceis mobile ");
               }
             else{
                 alert("Device is computer");
             }
       }

    </script>

</head>
<body onload="Check();">
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

The code is very simple and self descriptive. If you know navigator object of JavaScript you can easily understand. Actually navigator property contains information of user agent and user agent is nothing but browser. We are using pattern matching technique to detect device type like below   
 (navigator.userAgent.match(/iPhone/i))
By testing the above code on a computer, we will see the following output .


Using Google Translator to Change Language in your Website in asp.net

Let us see how we can change the language of the website globally without using Globalization and Localization.

To use Google translator you will have to visit :- https://translate.google.com/manager/website/

Google Translator and its Features
  1. Instantly translate your website into 60+ languages using Google's Translate
  2. Customize and improve the translation of your website
  3. Collect and use translation suggestions from your users
  4. Invite editors to manage translations and suggestions
Using the code
  1. First you need to go to https://translate.google.com/manager/website/
  2. Then Click on Add to Website, Once you click Add to Website it will ask you to login using your GMail Credentials.
  3. Once You Login it will ask you for you website URL and ask to choose your Default Language for website (Check Screen 1).
  4. Once you add the website URL.Click on Next for Further settings.
  5. The Further settings includes the Look of the Drop Down of selection of Languages, How many Languages you need, Do you want to add google analytics code for tracking traffic (Check Screen 2).
  6. Now we are done with the settings and we will now click on Get Code Button.
  7. Once we Click on the Get Code we get the piece of Code snippet.Now here is the trick to get a Global Conversion we will add the Code Snippet to the Master Page so that it affects all the pages with the content as well :) (Check Screen 3 for Code)

Screen 1



Screen 2






Screen 3




Lets start Implementation

  1. Create a New Empty Website -> Add a Master Page and 2 Web Forms and Include the Master Page to that web form.
  2. Now go to the Head section of the master page and paste the first piece of code snippet
  3. Now once you paste the Head section code. Now paste the second piece of Code snippet on the master page as per your display requirement.
  4. This piece of Code snippet should be inside a DIV Tag.
  5. Now Go to the Content Pages and Bind a Grid from database.(Check the Code for Binding In Code Section 3)
// Head Section of Master Page (Code Section 1)
<meta name="google-translate-customization" content="18e07a495bcfdebb-6e21f50c844b7cb0-g60562cca66703d3b-3b"></meta>
// Second Piece of Code Snippet (Code Section 2)
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL, multilanguagePage: true}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Explanation of the Code 

The code is nothing but a JavaScript function which connects to the Google Translator Service, gets the languages based on your selections made in the previous steps and gives the look and feel of the drop down as per selection.

// Code section 3 : Contains Code for 2 Web Forms (HTML Mark Up and Code Behind) with Tables and Stored Procedure.
//Tables and Stored Procedure
-- Countries Table
CREATE TABLE [dbo].[Countries](
[CountryID] [int] IDENTITY(1,1) NOT NULL,
[Countries] [varchar](25) NULL


-- Table for States
create table States
(
StateID int identity(1,1),
States varchar(25)
)


-- Proc to Get Countries
create proc GetCountriesList
as
begin
select * from Countries
end

-- Proc to Get States
create proc GetStates
as
begin
select * from States
end
//HTML Mark Up and Code Behind for Page 1
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
    CodeFile="GoogleTranslator.aspx.cs" Inherits="GoogleTranslator" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div style="font-family: 'Cooper Black'; font-size: x-large; text-align: center;">
        Language Translating of WebSite<br />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="Countries" HeaderText="Countries" />
            </Columns>

        </asp:GridView><br /><br />
        <asp:HyperLink ID="HyperLink1" NavigateUrl="~/GoogleTranslator2.aspx" runat="server">Next</asp:HyperLink>
        

    </div>
</asp:Content>
//Code Behind for Page 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class GoogleTranslator : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }

    private void BindGrid()
    {
        try
        {
            // Function to bind the data to Grid.
            SqlConnection con = new SqlConnection("Data Source=nayab;Initial Catalog=master;Persist Security Info=True;User ID=sa;Password=sqluser");
            con.Open();
            SqlCommand getcontent = new SqlCommand("GetCountriesList", con);
            getcontent.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(getcontent);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {

        }
    }
}
HTML Mark up and Code Behind for Page 2
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="GoogleTranslator2.aspx.cs" Inherits="GoogleTranslator2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div style="font-family: 'Cooper Black'; font-size: x-large; text-align: center;" align="center">
        Language Translating of WebSite<br />
        <br />
        <div align="center">
         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="States" HeaderText="States" />
            </Columns>

        </asp:GridView>
        </div>
       

    </div>
</asp:Content>

Code Behind for Page 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class GoogleTranslator2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private void BindGrid()
    {
        try
        {
            // Function to bind the data to Grid.
            SqlConnection con = new SqlConnection("Data Source=Nayab;Initial Catalog=master;Persist Security Info=True;User ID=sa;Password=sa");
            con.Open();
            SqlCommand getcontent = new SqlCommand("GetStates", con);
            getcontent.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(getcontent);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {

        }
    }
}

The reason for showing 2 pages is that once you navigate to another page you dont have to select the language again for translation Google does it automatically

OutPut for Page 1 : Showing Default Language English



Selecting Language for Translation : Hindi



Translated Page : Hindi Language



Moving to Next Page : Language Still same as per user preference




Note :- Please go through the Terms of Service of Google to know about more use age.



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

        }
    }
}