Pages

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

        }
    }
} 
 

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: