Friday, October 14, 2011

Webservice to get distance from Latitude and Longitude

 Sample Application for Web Service


Write this code on WebService Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService
{
    public Service () {

    }
    [WebMethod]
    public double distanceFrom(double lat1, double lng1, double lat2, double lng2)
    {
        double dist;       
        dist= distance(lat1, lng1, lat2, lng2);
        return dist;
    }
    private double distance(double lat1, double lon1, double lat2, double lon2)
    {
        double theta = lon1 - lon2;
        double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));
        dist = Math.Acos(dist);
        dist = rad2deg(dist);
        dist = dist * 60 * 1.1515;
        //For Kilometer
       // dist = dist * 1.609344;
       //For S Miles
       //   dist = dist * 0.8684;
        dist = Math.Round(dist, 2);
        return (dist);
    }
    private double deg2rad(double deg)
    {
        return (deg * Math.PI / 180.0);
    }
    private double rad2deg(double rad)
    {
        return (rad / Math.PI * 180.0);
    }
}

After This Add Web Reference in your site and write code on your aspx.cs page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceReference1;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       
        ServiceReference1.ServiceSoapClient sp=new ServiceSoapClient();
        double lat1=Convert.ToDouble(TextBox1.Text);
        double lat2 = Convert.ToDouble(TextBox3.Text); ;
        double lon1=Convert.ToDouble(TextBox2.Text);
        double lon2 = Convert.ToDouble(TextBox4.Text); ;
        double str = sp.distanceFrom(lat1,lon1,lat2,lon2);
        TextBox5.Text = str.ToString()+' '+"Miles";
    }
}

Friday, September 16, 2011

Enable SSL in asp.net



Please Create this function to enable SSL on your site with some page but make sure the SSL certificate is already installed
on your site or server and then call this function on page load event. 



Private void EnableSSL()
    {
        String CurrentUrl = Request.Url.ToString();
        //Get absolute path
        String sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
        System.IO.FileInfo Finfo = new System.IO.FileInfo(sPath);
        string page=
Finfo.Name;
        if (
page== "abc.aspx" || page== "cde.aspx" )
        {
            String NewUrl = "";
            if (!Request.IsSecureConnection)
            {
                NewUrl = "https" + CurrentUrl.Substring(4);
                Response.Redirect(NewUrl);
            }
        }
        else
        {
            if (CurrentUrl.IndexOf("https") >= 0)
            {
                Response.Redirect(CurrentUrl.Replace("https", "http"));
            }
        }
    }









Monday, September 5, 2011

LINQ To Entity and Convert class Methods Problems

While i was working with linq to sql or entity framework i have getting error at runtime like:

1. LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression
 
 2. LINQ to Entities does not recognize the method 'System.String get_Item(System.String)' method, and this method cannot be translated into a store expression.

and my code is:

                var lst = (from p in context.Products
                           where p.CategoryID==Convert.ToInt32(this.Request.QueryString["Category"])
                           select p).ToList();

Than i have found that:

Reason: First value of type "object" is returned and then it is typecasted to int. This is, again, not permitted as a temporary anonymous object needs to be created for resolving translation of Data Type.

Solution of this:

int id = Convert.ToInt32(this.Request.QueryString["Category"]);
                var lst = (from p in context.Products
                           where p.CategoryID==id
                           select p).ToList();




Sunday, August 21, 2011

Change gridview row color on mouseover and mouseout in asp.net




protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='Silver'");
            // This will be the back ground color of the GridView Control
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='White'");
        }
    }


Saturday, August 20, 2011

Retreive data from Excel Sheet in asp.net



/// This mehtod retrieves the excel sheet names from

/// an excel workbook.



private String[] GetExcelSheetNames(string excelFile)
{
  OleDbConnection objConn = null;
  System.Data.DataTable dt = null;

  try
  {
    // Connection String. Change the excel file to the file you

    // will search.

    String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
        "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
    // Create connection object by using the preceding connection string.

    objConn = new OleDbConnection(connString);
    // Open connection with the database.

    objConn.Open();
    // Get the data table containg the schema guid.

    dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

    if(dt == null)
    {
      return null;
    }

    String[] excelSheets = new String[dt.Rows.Count];
    int i = 0;

    // Add the sheet name to the string array.

    foreach(DataRow row in dt.Rows)
    {
      excelSheets[i] = row["TABLE_NAME"].ToString();
      i++;
    }

    // Loop through all of the sheets if you want too...

    for(int j=0; j < excelSheets.Length; j++)
    {
      // Query each excel sheet.

    }

    return excelSheets;
  }
  catch(Exception ex)
  {
    return null;
  }
  finally
  {
    // Clean up.

    if(objConn != null)
    {
      objConn.Close();
      objConn.Dispose();
    }
    if(dt != null)
    {
      dt.Dispose();
    }
  }




Sql Function To Split the commas Value and insert them into table.



CREATE FUNCTION [dbo].[ListToTable] (
  /*
  FUNCTION ListToTable
  Usage: select entry from listtotable('abc,def,ghi') order by entry desc
  PURPOSE: Takes a comma-delimited list as a parameter and returns the values of that list into a table variable.
  */
  @mylist varchar(8000)
  )
  RETURNS @ListTable TABLE (
  seqid int not null,
  entry varchar(255) not null)

  AS

  BEGIN
      DECLARE
              @this varchar(255),
              @rest varchar(8000),
              @pos int,
              @seqid int

      SET @this = ' '
      SET @seqid = 1
      SET @rest = @mylist
      SET @pos = PATINDEX('%,%', @rest)
      WHILE (@pos > 0)
      BEGIN
              set @this=substring(@rest,1,@pos-1)
              set @rest=substring(@rest,@pos+1,len(@rest)-@pos)
              INSERT INTO @ListTable (seqid,entry)  VALUES (@seqid,@this)
              SET @pos= PATINDEX('%,%', @rest)
              SET @seqid=@seqid+1
      END
      set @this=@rest
      INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,@this)
      RETURN
  END

Some Important Example or Regular expression in asp.net



Remove last two zero inside gridview if
Price=56.0000:

'<%#Eval("Price").ToString().Remove(Eval("Price").ToString().Length - 2, 2) %>'


Regular Expressions for Amount:

^\$?\d+(\.(\d{2}))?$
To evaluate an amount with or without a dollar sign where the cents are optional.


^([0-9]*|\d*\.\d{1}?\d*)$
Accept only (0-9) integer and one decimal point(decimal point is also optional).After decimal point it accepts at least one numeric .This will be usefull in money related fields or decimal fields.

Regular Expression for multiline Textbox:

ErrorMessage="Address should be less than 130 characters" ValidationExpression="[\s\S]{0,130}"
ValidationGroup="submit">.


compare validate for today date:

Type="Date" runat="server" ValidationGroup="submit" ErrorMessage="Start date must be greater than today date."
SetFocusOnError="True">.



On page load

 c1.ValueToCompare = DateTime.Now.ToString("MM/dd/yyyy");


Friday, June 10, 2011

Asp.net MVC, Html.DropDownList Selected Value for EDIT

In Controller:

  ViewData["MyDropDown"] = new SelectList(CatModel.getAllCategory(), "Value", "Text",selectedValue:prModel.DisplayProductByid(prd).CategoryID);

In View:

 <%: Html.DropDownList("MyDropDownID", ViewData["MyDropDown"] as SelectList)%>

----------------------------------------------------------------------------
I have got same problem and the solution is above:
I just changed the Name of the drop down and handled the assignment in the controller.
The reason behind this problem is that asp.net MVC first looks for a match between the name of the drop down and a property on the model. If there’s a match, the selected value of the SelectList is overridden. Changing the name of the drop down is all it takes to remedy the issue.

Thursday, March 17, 2011

Send Multiple attachment in Mail

  public static void SendAttachmentMail(string MailBody, string EmailTo, string MailFrom, string Subject, string[] listpdf)
    {
        try
        {
            MailMessage sendMail = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            NetworkCredential SmtpUser = new NetworkCredential();
            sendMail.To.Add(EmailTo);
            sendMail.From = new MailAddress(MailFrom);
            sendMail.Subject = Subject;
            sendMail.Body = MailBody;
            sendMail.IsBodyHtml = true;
          
            int cnt = listpdf.Count();
            for (int l = 0; l < cnt; l++)
            {
                Attachment at_l = new Attachment(listpdf[l]);
                sendMail.Attachments.Add(at_l);
            }
            smtp.EnableSsl = true;
            smtp.Send(sendMail);
            sendMail.To.Clear();
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message.ToString());
            HttpContext.Current.Response.End();
        }
    }

Sunday, February 6, 2011

Create Barcode Image with asp.net

To create and save barcode image in database with asp.net :




private Bitmap createbarcode(string data)
    {
        Bitmap barcode = new Bitmap(1, 1);
        PrivateFontCollection pfc = new PrivateFontCollection();
        string pth = Server.MapPath("../Fonts/idautomationhc39m.ttf");
        pfc.AddFontFile(pth);
        FontFamily ff = pfc.Families[0];
        FontFamily family = new FontFamily("IDAutomationHC39M", pfc);
        System.Drawing.Font threeofnine = new System.Drawing.Font(family, 12, FontStyle.Regular, GraphicsUnit.Point);
        Graphics graphic = Graphics.FromImage(barcode);
        SizeF datasize = graphic.MeasureString(data, threeofnine);
        barcode = new Bitmap(barcode, datasize.ToSize());
        graphic = Graphics.FromImage(barcode);
        graphic.Clear(System.Drawing.Color.White);
        graphic.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
        graphic.DrawString(data, threeofnine, new SolidBrush(System.Drawing.Color.Black), 0, 0);
        graphic.Flush();
        threeofnine.Dispose();
        graphic.Dispose();
        return barcode;
    }
    private void GenerateAndGetBarCode()
    {
        data = GenerateRandomCode();
        Bitmap barCode = createbarcode("*" + data + "*");
        imgPath = ConfigurationManager.AppSettings["site_url"] + "/Barcode/" + data + ".Gif";
        String filepath = Server.MapPath("../BarCode/") + data + ".Gif";
        barCode.Save( filepath, ImageFormat.Gif);
    }