Wednesday 25 June 2014

Code of Changing Language of website through google api


<Head>
<meta name="google-translate-customization" content="6789df04e7a523e6-c909299b54ba9bf6-g59b2dee19f609d27-14"></meta>

</Head>

<Body>

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

</Body>

Then Run.......................

-------------------------------------------------------------------------------------

This code use for only English and Hindi....
<body>

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'en,hi', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

</body>

Using the Google Translator in Web API

Google Translator
The Google Translator translates the search Query to the language you want. Google Translator is a free statistical multilingual machine translation service that is provided by Google. It translates written text from one language to another.
Now you can see the process of using the Google Translator in a Web API application as in the following:
  1. First we create a Google Account.
  2. To integrate the Google Translator, login with your Gmail id from this link:

  1. Click on "Sign in".
trans.jpg
Sign in with your Gmail id.
  1. Then login with your id. Open a window.
trans1.jpg
  1. Click on the tab "Add to your website now" .
Type your website URL in the "website URL" TextBox.
trans3.jpg
Website URL:  in this block you write your website URL.
Website language: It defines the default language for your website.
Click on the "Next" button.
  1. Open a window in which you select "translation language", "display mode" and click on "Get Code" button.
trans4.jpg
Translation Languages: here two options are available as in the following:
  • All language: If we select all languages then it shows all the languages that are used in the Google Translator.
  • Specific languages: If you select this option then you choose a specific language.
Display mode: This mode defines the list of languages in a different mode.
Now click on the "Get Code" button.
trans5.jpg
  1. Create a Web API application as in the following:
  • Start Visual Studio 2012.
  • From Start window select "New Project".
  • From the new project window select "Installed" -> "Visual C#" -> "Web".
  • Select "ASP.NET MVC4 Web Application" and click on the "OK" button.
trans10.jpg
  • From the "MVC4 Project" window select "Web API".
trans11.jpg
  • Click the "OK" button.
  1. For copying the code you need the "index.cshtml" file. This file exists:
  • In the "Solution Explorer".
  • Expand "Home" folder.
  • Select the "index.cshtml" file and add the code.
trans9.jpg
Copy the Meta tag content and paste it in the "<head>" tag.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>
            c-sharpcorner
        </title>
       <meta name="google-translate-customization" content="3280487709591956-dc3fc45d489f056a-g5378ebab0cbcd0a4-12"/>
    </head>

Now copy the block of code and paste it into the "<body>" tag.
<body>
<div id="google_translate_element">
    Welcome to! MSDN Site.
</div><script type="text/javascript">
          function googleTranslateElementInit()
          {
            new google.translate.TranslateElement({ pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE }, 'google_translate_element');
          }
</script>
    <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit">

         </script>
    </body>
        </html>

  1. Now execute the application:
trans6.jpg

Click on the Dropdown list:
trans7.jpg
Select any language. Here the output looks like this:
trans8.jpg

Saturday 21 June 2014

How to SORT DataTable in C# Dot Net

        DataView dv = new DataView(Datatable1);
        dv.Sort = "Column Name DESC";
        Datatable2 = new DataTable();
        dt = dv.ToTable();

Friday 20 June 2014

How to read mail from gmail in asp.net

In this post,I will show you how to read mail from gmail in asp.net
aspdotnetcodebook

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        UserName :
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
        Password:
        <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox><br />
        <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" /><br />
        <asp:GridView ID="grdMail" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.Xml.Linq;

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

    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        XNamespace ns = "http://purl.org/atom/ns#";
        string userName = txtUserName.Text;
        string password = txtPassword.Text;
        string gmailFeedUrl = @"https://mail.google.com/mail/feed/atom ";
        WebClient client = new WebClient();
        string credential = string.Format("{0}:{1}", userName, password);
        string auth = "Basic" + Convert.ToBase64String(Encoding.ASCII.GetBytes(credential));
        client.Headers.Add("Authorization", auth);
        var inboxXml = client.DownloadString(gmailFeedUrl);
        var xml = XDocument.Parse(inboxXml);
        var query = from entry in xml.Descendants(ns + "entry")
                    select new
                    {
                        Title = entry.Element(ns + "title").Value,
                        Author = entry.Element(ns + "author").Element(ns + "name").Value,
                    };
        grdMail.DataSource = query;
        grdMail.DataBind();
    }
}

Thursday 12 June 2014

create dynamic menu and sub-menu with sql database in asp.net


Create Two table first

DATABASE

----------------------------------------
create table menu
(
id int primary key identity(1,1),
name varchar(120),
url varchar(200),
isorder int unique,
isactive int default(1)
)

create table submenu
(
id int primary key identity(1,1),
name varchar(120),
url varchar(200),
isorder int unique,
menuid int,
isactive int default(1)
)

ASPX PAGE :

--------------------------------
<div class="menu-part">


        <div class="menu">

            <div class="menu-inner">
            <ul id="main_menu">
                <asp:DataList ID="DataList1" runat="server" DataKeyField="id"
                    RepeatDirection="Horizontal" onitemdatabound="DataList1_ItemDataBound">
                <ItemTemplate>
                <li>
                    <asp:LinkButton ID="menu" CommandArgument='<%#Eval("id") %>'                                                           PostBackUrl='<%#Eval("url") %>' runat="server"><%#Eval("name") %>
                     </asp:LinkButton>
                        <ul style="overflow: hidden; display: block; height: 0px; z-index: 51; opacity: 0.00588235;">
                         <asp:DataList ID="DataList2" runat="server">
                         <ItemTemplate>
                         <li>
                               <asp:LinkButton ID="submenu" CommandArgument='<%#Eval("id") %>'                                                     PostBackUrl='<%#Eval("url") %>' runat="server"><%#Eval("name") %>                                                     </asp:LinkButton>
                          </li>
                         </ItemTemplate>
                          </asp:DataList>
                   </ul>
                </li>
                </ItemTemplate>
                </asp:DataList>
            </ul>
             
            </div>

        </div>

    </div>

CS PAGE

-----------------------------------------
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;
using System.Configuration;

public partial class MasterPage : System.Web.UI.MasterPage
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ConnectionString);
    SqlCommand cmd;
    SqlDataAdapter da;
    DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
        menu();
    }
    public void menu()
    {
        try
        {
            da = new SqlDataAdapter("select * from menu order by isorder", con);
            dt = new DataTable();
            da.Fill(dt);
            DataList1.DataSource = dt;
            DataList1.DataBind();

        }
        catch (Exception)
        { }
    }
 
    protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        DataList submenu = (DataList)e.Item.FindControl("DataList2");
        LinkButton menu = (LinkButton)e.Item.FindControl("menu");
        int id=Convert.ToInt32( menu.CommandArgument);
        da = new SqlDataAdapter("select * from submenu where menuid=" + id + " order by isorder", con);
        dt = new DataTable();
        da.Fill(dt);
        submenu.DataSource = dt;
        submenu.DataBind();
     
    }
}

CSS CODE

--------------------------------------
.top-menu{height:auto;float:right;padding-right:65px;}
.top-menu ul li{display:inline-block;float:left;background:url(../images/top-menu-bu.png) left no-repeat;font:11px bold Arial, Helvetica, sans-serif;text-transform:uppercase;color:#FFF;padding-left:18px;padding-right:14px;}
.top-menu ul li a{color:#FFF;}
.top-menu ul li a:hover{color:#ed0345;}

.menu-part{width:1011px;height:auto;float:left;}
.menu{width:731px;height:60px;float:left;background:url(../images/menu-left.png) no-repeat;}
.menu-inner{width:1011px;height:60px;float:left;background:url(../images/menu-bg.png) repeat-x;font:Bold 14px  Arial, Helvetica, sans-serif;text-transform:uppercase;color:#fafeff;text-shadow: 0px 1px #011e33;}



ul#main_menu {list-style:none; margin-top:17px;}
ul#main_menu * {margin:0; padding:0;}
ul#main_menu li {position:relative; background:url(../images/divater.png) right no-repeat; float:left; padding-left:24px; padding-right:24px;height:30px; padding-top:13px;}
ul#main_menu li a{font:Bold 12px  Arial, Helvetica, sans-serif;color:#FFF; text-transform:uppercase;}
ul#main_menu li a:hover{color:#f8a94d;}
ul#main_menu li.selected a{color:#f8a94d;}

ul#main_menu ul {position:absolute; top:50px; left:0px;display:none; opacity:0; list-style:none;}
ul#main_menu ul li {position:relative; width:200px;padding:0px; background:#17476f; border:#0e406a solid 1px;-moz-border-radius:3px;-webkit-border-radius: 6px;margin-bottom:2px;}
ul#main_menu ul li a {display:block; padding:6px 10px 10px 10px; color:#FFF; font-size:16px;-moz-border-radius:3px;-webkit-border-radius:6px; font:Normal 14px Arial, Helvetica, sans-serif;color:#FFF;
text-transform:none;}
ul#main_menu li.selected ul li a{ color:#FFFFFF;}
ul#main_menu li.selected ul li a:hover{ color:#f8a94d;}
ul#main_menu ul li a:hover {background-color:#3271a6; color:#FFF; display:block; padding-bottom:8px; }


Wednesday 4 June 2014

Rating control in asp.net with database


Rating Control properties:
<ajaxToolkit:Rating ID="ThaiRating" runat="server"
    CurrentRating="2"
    MaxRating="5"
    StarCssClass="ratingStar"
    WaitingStarCssClass="savedRatingStar"
    FilledStarCssClass="filledRatingStar"
    EmptyStarCssClass="emptyRatingStar"
    OnChanged="ThaiRating_Changed" />

AutoPostBack - True to cause a postback on rating item click.
CurrentRating - Initial rating value
MaxRating - Maximum rating value
ReadOnly - Whether or not the rating can be changed
StarCssClass - CSS class for a visible star
WaitingStarCssClass - CSS class for a star in waiting mode
FilledStarCssClass - CSS class for star in filled mode
EmptyStarCssClass - CSS class for a star in empty mode
RatingAlign - Alignment of the stars (Vertical or Horizontal)
RatingDirection - Orientation of the stars (LeftToRightTopToBottom or RightToLeftBottomToTop)
OnChanged - ClientCallBack event to fire when the rating is changed
Tag - A custom parameter to pass to the ClientCallBack

First we have to create to create table. Sample table design given below

Table design (UserRating):
Column Name
Data Type
Id (Auto Increment)
int
Rating
Int

In we.config  file we have to set connection string
Sample code: 
<connectionStrings>
        <add name="ConnectionString" connectionString="Data Source=localhost;                           
                                        Initial Catalog=Demo; Integrated Security=True"/>
</connectionStrings>

Here we have to add AjaxControlToolkit assembly reference in our page
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

Then we have to create our aspx page like this

Designer source code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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>AJAX Rating control</title>
    <style type="text/css">
body
{
margin:0px auto;
width:980px;
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif
background:#C9C9C9;
}
.blankstar
{
background-imageurl(images/blank_star.png);
width16px;
height16px;
}
.waitingstar
{
background-imageurl(images/half_star.png);
width16px;
height16px;
}
.shiningstar
{
background-imageurl(images/shining_star.png);
width16px;
height16px;
}
</style>
</head>
<body>
    <form id="form1" runat="server">  
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>   
   
    <asp:Rating ID="Rating1" runat="server" AutoPostBack="true" StarCssClass="blankstar"
        WaitingStarCssClass="waitingstar" FilledStarCssClass="shiningstar"
        EmptyStarCssClass="blankstar" OnChanged="Rating1_Changed">
    </asp:Rating>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>,
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> 
    </form>
</body>
</html>

Note:
          Source code has been attached along with this article (No registration required). 
You can download and copy the required images for Rating Control.

C# code:
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;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "0 Users have rated this Product";
        Label2.Text = "Average rating for this Product is 0";      
        if (!IsPostBack)
        {
            BindRatings();
        }
    }
    protected void Rating1_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
    {       
        con.Open();
        SqlCommand cmd = new SqlCommand("INSERT INTO UserRating(Rating) VALUES (@Rating)", con);
        cmd.Parameters.AddWithValue("@Rating"SqlDbType.Int).Value = Rating1.CurrentRating;
        cmd.ExecuteNonQuery();
        con.Close();
        BindRatings();
    }
    public void BindRatings()
    {
        int Total = 0;       
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT Rating FROM UserRating", con);       
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Total += Convert.ToInt32(dt.Rows[i][0].ToString());
            }
            int Average = Total / (dt.Rows.Count);
            Rating1.CurrentRating = Average;
            Label1.Text = dt.Rows.Count + " " + "Users have rated this Product";
            Label2.Text = "Average rating for this Product is" + " " + Convert.ToString(Average);
        }
    }
}