Sunday 16 June 2013

Get Client IP using jQuery


  •  jsonip.com: is a free utility service that returns a client's IP address in a JSON object with support for JSONP, CORS, and direct requests. It serves millions of requests each day for websites, servers, mobile devices and more from all around the world.

All you need to do is to make a call to jsonip.com.

$(document).ready(function () {
    $.get('http://jsonip.com', function (res) {
        $('p').html('IP Address is: ' + res.ip);
    });
});

  • Smart-IP.net: Smart IP for today is one of the leading services providing to it's users all the required information about IP-addresses and everything related to them.

$(document).ready(function () {
    $.getJSON('http://smart-ip.net/geoip-json?callback=?', function(data) {
        $('p').html('My IP Address is: ' + data.host);
    });
});

Along with the IP address, this service also provide Geo location details as well like Country, latitude, longitude etc. Following are the properties which are returned as JSON response by this service.

data.host;
data.countryName;
data.countryCode;
data.city;
data.region;
data.latitude;
data.longitude;
data.timezone;

Thursday 13 June 2013

How to find duplicate values in two columns in Excel?


1. In cell B1, input this formula: “=IF(ISERROR(MATCH(A1,$C$1:$C$13,0)),"",A1)”.
A1 is the column which you want to be compared.
$C$1:$C$13 is the range that you want to be compared with.
You can change the variables for what you are using.

2. Press the Enter key. Select cell B1, and then drag the fill handle over cell B15.

3. And all of the duplicate names will be displayed in column B. See screenshot:


doc-find-duplicates2

Difference between WCF and Web API and WCF REST and Web Service

Web Service

It is based on SOAP and return data in XML form.
It support only HTTP protocol.
It is not open source but can be consumed by any client that understands xml.
It can be hosted only on IIS.

WCF

  • It is also based on SOAP and return data in XML form.
  • It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  • The main issue with WCF is, its tedious and extensive configuration.
  • It is not open source but can be consumed by any client that understands xml.
  • It can be hosted with in the applicaion or on IIS or using window service.
WCF Rest

  • To use WCF as WCF Rest service you have to enable webHttpBindings.
  • It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  • To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
It support XML, JSON and ATOM data format.


Web API

This is the new framework for building HTTP services with easy and simple way.
Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)

It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.

It can be hosted with in the application or on IIS.
It is light weight architecture and good for devices which have limited bandwidth like smart phones.
Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
To whom choose between WCF or WEB API

Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

Monday 10 June 2013

Show Gridview Row Details in Tooltip on MouseHover in Asp.net C# using Jquery

To show gridview row details in tooltip on mouseover with jQuery we need to write the following code in aspx page


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Show Gridview Rows Details in tooltip with jQuery</title>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script src="jquery.tooltip.min.js" type="text/javascript"></script>
<script type="text/javascript">
function InitializeToolTip() {
$(".gridViewToolTip").tooltip({
track: true,
delay: 0,
showURL: false,
fade: 100,
bodyHandler: function () {
return $($(this).next().html());
},
showURL: false
});
}
</script>
<script type="text/javascript">
$(function () {
InitializeToolTip();
})
</script>
<style type="text/css">
#tooltip {
position: absolute;
z-index: 3000;
border: 1px solid #111;
background-color: #FEE18D;
padding: 5px;
opacity: 0.85;
}
#tooltip h3, #tooltip div { margin: 0; }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:TemplateField HeaderText="UserId">
<ItemStyle Width="30px" HorizontalAlign="Center" />
<ItemTemplate>
<a href="#" class="gridViewToolTip"><%# Eval("UserId")%></a>
<div id="tooltip" style="display: none;">
<table>
<tr>
<td style="white-space: nowrap;"><b>UserName:</b>&nbsp;</td>
<td><%# Eval("UserName")%></td>
</tr>
<tr>
<td style="white-space: nowrap;"><b>Education:</b>&nbsp;</td>
<td><%# Eval("Education")%></td>
</tr>
<tr>
<td style="white-space: nowrap;"><b>Location:</b>&nbsp;</td>
<td><%# Eval("Location")%></td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
If you observe in header section I added jQuery plugin and tooltip plugin by using those files we can display gridview row details in tooltip. To get those files download attached sample code or from this url bassistance.de tooltip plugin

Now in code behind add the following namespaces

C# Code


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
After that add below code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
DataRow dtrow = dt.NewRow();    // Create New Row
dtrow["UserId"] = 1;            //Bind Data to Columns
dtrow["UserName"] = "SureshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();               // Create New Row
dtrow["UserId"] = 2;               //Bind Data to Columns
dtrow["UserName"] = "MadhavSai";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();              // Create New Row
dtrow["UserId"] = 3;              //Bind Data to Columns
dtrow["UserName"] = "MaheshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Nuzividu";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}

Thursday 6 June 2013

Gridview With out DataBase in asp.net and C#


Use this code in .aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" Width="189px"></asp:TextBox>
 <asp:TextBox ID="TextBox2" runat="server" Width="179px"></asp:TextBox>
    < asp:TextBox ID="TextBox3" runat="server" Height="22px" Width="222px"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
        <asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand"
            onrowdeleting="GridView1_RowDeleting" OnSelectedIndexChanged="GridView1_SelectedIndexChanged1" >
            <Columns>
            <asp:TemplateField>
            <ItemTemplate>
            <asp:Button  ID="btndelete" runat="server" Text="delete" CommandName="delete"/>
            </ItemTemplate>
            </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>
</body>
</html>


CodeBehind:

 static DataTable dtValues = new DataTable();
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CreateDataTable();
        }
      
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataRow drValues = dtValues.NewRow();
       
        drValues[0] = TextBox1.Text;
        drValues[1] = TextBox2.Text;
        drValues[2] = TextBox3.Text;
        drValues[3] = TextBox4.Text;
        dtValues.Rows.Add(drValues);
        fillgrid();
        TextBox1.Text = "";
        TextBox2.Text = "";
        TextBox3.Text = "";
        TextBox4.Text = "";
       
    }
  
    public void fillgrid()
    {
        GridView1.DataSource = dtValues;
        GridView1.DataBind();
    }
    protected void CreateDataTable()
    {
        dtValues.Columns.Add("eno");
        dtValues.Columns.Add("name");
        dtValues.Columns.Add("sal");
        dtValues.Columns.Add("phoneno");
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "delete")
        {
            GridViewRow d = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
            int index = d.RowIndex;
            dtValues.Rows[index].Delete();
            fillgrid();
        }
    }

Easy way to Generate Barcode in ASP.NET C#

1.First Download the Barcode.dll file below shown link 


2.Add .dll file Reference to your project 

3.Add this Namespace to cs file


using System.Drawing;
using System.Drawing.Imaging;

using BarcodeLib;
using System.Collections.Generic;
using System.IO;

4. Copy this Code in .cs file

 BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
                    {
                        IncludeLabel = false,
                        Alignment = AlignmentPositions.LEFT,
                        Width = 200,
                        Height = 30,
                        RotateFlipType = RotateFlipType.RotateNoneFlipNone,
                        BackColor = Color.White,
                        ForeColor = Color.Black,
                    };

                    System.Drawing.Image img = barcode.Encode(TYPE.CODE39, "0123456789");


                    string sGuid;
                    sGuid = Convert.ToString(Guid.NewGuid());
                    sGuid = sGuid.Replace("-", "");
                    img.Save(Server.MapPath("~/BarCodeImages/" + name + "/") + sGuid + ".jpg",     ImageFormat.Jpeg);
                   
                    image1.ImageUrl = "~/BarCodeImages/" + name + "/" + sGuid + ".jpg";

5.Source 

 <asp:Image ID="Image1" runat="server" />


Bar code is store in Barcodeimages folder ,add image control to source page ,generated bar code is shown in image control 

merge cells with equal values in Asp.net GridView

public class GridDecorator
{
    public static void MergeRows(GridView gridView)
    {
        for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
        {
            GridViewRow row = gridView.Rows[rowIndex];
            GridViewRow previousRow = gridView.Rows[rowIndex + 1];

            for (int i = 0; i < row.Cells.Count; i++)
            {
                if (row.Cells[i].Text == previousRow.Cells[i].Text)
                {
                    row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 : 
                                           previousRow.Cells[i].RowSpan + 1;
                    previousRow.Cells[i].Visible = false;
                }
            }
        }
    }
}
protected void gridView_PreRender(object sender, EventArgs e)
{
    GridDecorator.MergeRows(gridView);
}

Stopping Previous Page navigation after log out in ASP.NET C#

After Signout click on back button is goto previous page  ,solution is copy below code in  page_load event

if  your using Master page  then same code copy in masterpage page_load event



 Codebehind:

 protected void Page_Load(object sender, EventArgs e)
    {
        if ( Session["user"]==null)
        {
            Response.Redirect("../admin/login.aspx");
        }
        
        Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
}



  protected void   Logout_Click (object sender, LoginCancelEventArgs e)
    {
        Session["user"] = null;
        Session.Abandon();
        Response.Redirect("../admin/login.aspx");
     }

Search in gridview entered in textbox using javascript

Javascript


<script type="text/javascript">  
   String.prototype.startsWith = function(str){    return (this.indexOf(str) === 0);}  
        function Highlight()     
        {     
            var srchval = document.getElementById('<%= TextBox1.ClientID %>').value;     
            var cntrlname = document.getElementById('<%= GridView1.ClientID %>');                 
            var rows = cntrlname.getElementsByTagName("tr"); 
            var rowTop = 0;  
            var FirstRow = rows[1];
            for(var loop = 0 ; loop < rows.length ; loop++)     
            {
                rows[loop].style.background='#ffffff';
            }
            if(srchval != '')
            {
            for(var loop = 0 ; loop < rows.length ; loop++)     
            {     
                var ok = 0;    
                var cells = rows[loop].getElementsByTagName("td");     
                for(i = 0 ; i < cells.length ; i++)     
                {                
                    if(cells[i].innerHTML.toLowerCase().startsWith(srchval.toLowerCase()))     
                    {     
                        ok = 1;                             
                    }     
                }     
               if(ok == 1)        
               {
                    CurrentRow = rows[loop];
                    SendUp(CurrentRow, FirstRow);
                    CurrentRow.style.background='#eeff00';                
               }       
                else                     
                    rows[loop].style.background='#ffffff';             
            }     
            }
            return false;     
        }   
        function SendUp(CurrentRow,FirstRow)
        {
            FirstRow.parentNode.insertBefore(CurrentRow,FirstRow);
        }
        function GetMedName(MedName)
        {
            document.getElementById('<%= TextBox1.ClientID %>').value = MedName;
        }
     </script>


 <asp:TextBox runat="server" ID="TextBox1" onkeypress="Highlight() " ></asp:TextBox> 

Code Behind
Hope that your medication name is on first cell



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Attributes.Add("onclick", "GetMedName('" + e.Row.Cells[0].Text + "');");
        }
    }

Export to Excel Simple Code using Asp.net C#

public void ExportToExcel(DataTable dt)
    {
        
        if (dt.Rows.Count > 0)
        {
      string excelHeader = "SampleHeading "";
                       System.IO.StringWriter tw = new System.IO.StringWriter();

            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

            DataGrid dgGrid = new DataGrid();

            dgGrid.DataSource = dt;

            dgGrid.DataBind();

            // Report Header

            hw.WriteLine("<b><u><font size=’3′> " + excelHeader + " </font></u></b>");

            //Get the HTML for the control.

            dgGrid.RenderControl(hw);

            //Write the HTML back to the browser.

            //Response.ContentType = “application/vnd.ms-excel”;
         
            Response.ContentType = "application/vnd.ms-excel";

            Response.AppendHeader("Content-Disposition", "attachment; filename=" Test.xls"");

            this.EnableViewState = false;

            Response.Write(tw.ToString());

            Response.End();

        }

    }

Gridview Data show in Horizontal or Vertical Direction in Asp.net and C#

public DataSet FlipDataSet(DataSet my_DataSet)
    {
        DataSet ds = new DataSet();
        DataTable table = new DataTable();
        foreach (DataTable dt in my_DataSet.Tables)
        {
            for (int i = 0; i <= dt.Rows.Count; i++)
            {
                table.Columns.Add(Convert.ToString(i));
            }
            DataRow r;
            for (int k = 0; k < dt.Columns.Count; k++)
            {
                r = table.NewRow();
                r[0] = dt.Columns[k].ToString();
                for (int j = 1; j <= dt.Rows.Count; j++)
                    r[j] = dt.Rows[j - 1][k];
                table.Rows.Add(r);
            }
        }
        ds.Tables.Add(table);
        return ds;
    }

JAVASCRIPT : Validate a decimal number in a textbox on a data entry form and accept only one decimal point

function isNumberKeyAndDot(event, value) {
    var charCode = (event.which) ? event.which : event.keyCode
    var intcount = 0;
    var stramount = value;
    for (var i = 0; i < stramount.length; i++) {
        if (stramount.charAt(i) == '.' && charCode==46) {
            return false;
        }
    }   
    if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode != 46)
        return false;
    return true;


Source Code:

<asp:TextBox ID="txtdiscvalue" runat="server"  onkeypress="return isNumberKeyAndDot(event,value)"></asp:TextBox>

Paging in Datalist Asp.net ,C#

Datalist Paging


Source Page  .aspx:


 <asp:DataList ID="DataListpost" runat="server" DataKeyField="id"
                      Width="100%"
            HorizontalAlign="Center">
  <ItemTemplate>
  </ItemTemplate>  </asp:DataList>
            
         


<asp:LinkButton id="Prev" Text="NewPost" OnClick="Page_DataList" runat="server"  
          ForeColor="#003366" />                
             <asp:LinkButton id="Next" Text="OldPost" runat="server" ForeColor="#003366" 
                          onclick="Page_DataList"  EnableViewState="true"  /> 


 <input type="hidden" id="PageSize" value="10" runat="server"/>
  <input type="hidden" id="CurrentPage" value="1" runat="server"/>
  <input type="hidden" id="TotalSize" runat="server"/>

Codebehind :

 SqlConnection con;
    SqlCommand cmd;

    DataTable dt;
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["scon"].ConnectionString);
        if (!IsPostBack)
            BuildGrid();
      
        
    }

    protected void btnbook_Click(object sender, EventArgs e)
    {
        
    }
    public void BuildGrid()
    {
        cmd = new SqlCommand("select * from post order by id desc", con);

        con.Open();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        ds = new DataSet();
        int startRecord = (int.Parse(CurrentPage.Value) - 1) *
       int.Parse(PageSize.Value);
        //Fetch only the necessary records.
        adp.Fill(ds, startRecord, int.Parse(PageSize.Value), "post");
        //DataBind the DataList    
        DataListpost.DataSource = ds.Tables["post"].DefaultView;
        DataListpost.DataBind();

        //Second Part
        //Create a new Command to select the total number of records
        SqlCommand myCmd = new SqlCommand("SELECT Count(*) from post", con);

        //retrieve the value
        TotalSize.Value = myCmd.ExecuteScalar().ToString();
        con.Close();
        BuildPagers();
    }
    public void BuildPagers()
    {
        //Check if its possible to have the previous page
        if ((int.Parse(CurrentPage.Value) - 1) <= 0)
        {
            Prev.Enabled = false;
        }
        else
        {
            Prev.Enabled = true;
        }
        //Check if its possible to have the next page  
        if ((int.Parse(CurrentPage.Value) * int.Parse(PageSize.Value))
        >= int.Parse(TotalSize.Value))
        {
            Next.Enabled = false;
        }
        else
        {
            Next.Enabled = true;
        }
    }
    public void Page_DataList(object sender, EventArgs e)
    {
        //Check for Button clicked
        if (((LinkButton)sender).ID == "Prev")
        {
            //Check if we are on any page greater than 0 
            if ((int.Parse(CurrentPage.Value) - 1) >= 0)
            {
                //Decrease the CurrentPage Value
                CurrentPage.Value = (int.Parse(CurrentPage.Value) - 1).ToString();
            }
        }
        else if (((LinkButton)sender).ID == "Next")
        {
            //Check if we can display the next page.
            if ((int.Parse(CurrentPage.Value) * int.Parse(PageSize.Value))
           < int.Parse(TotalSize.Value))
            {
                //Increment the CurrentPage value
                CurrentPage.Value = (int.Parse(CurrentPage.Value) + 1).ToString();
            }
        }
        //Rebuild the Grid
        BuildGrid();
       
    }