Tuesday, November 17, 2009

Import .dbf data to gridview

 System.Data.Odbc.OdbcConnection oConn = new System.Data.Odbc.OdbcConnection();
        Con.ConnectionString = @"Driver={Microsoft dBase Driver (*.dbf)};SourceType=DBF;SourceDB=D:\Sample\;Exclusive=No; Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
        Con.Open();
        System.Data.Odbc.OdbcCommand oCmd = oConn.CreateCommand();
        oCmd.CommandText = @"SELECT * FROM D:\Sample\IndiaDB\FileName.dbf";
        DataTable dat = new DataTable();
        dat.Load(oCmd.ExecuteReader());
        Con.Close();
     
        GridView1.DataSource = dat;
        GridView1.DataBind();


To import this data to SQL table, create a table with sample field and use this code...
 DataTableReader reader = dt.CreateDataReader();

          myConnection.Open();   ///this is my connection to the sql server
          SqlBulkCopy sqlcpy = new SqlBulkCopy(myConnection);

          sqlcpy.DestinationTableName = "YourTable";  //copy the datatable to the sql table

          sqlcpy.WriteToServer(dt);

          myConnection.Close();

Highlight Search Keyword in datalist



When you are displaying search result in datalist, if you highlight seach keyword,it will be easy for user user.


Use thisfunction to highlight search term.


protected string HighlightText(string searchWord, string inputText)
    {
        if (searchWord != null && searchWord != "")
        {
            Regex expression = new Regex(searchWord.Replace(" ", "|"), RegexOptions.IgnoreCase);
            return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
        }
        return inputText;
    }

    public string ReplaceKeywords(Match m)
    {

        return  "" + m.Value + "";
      
    }


And add this inside your datalist.
 <%#HighlightText(txtSearch.Text,Eval("YourField").ToString())%>

Now the search term in YourField will be highlighted in bold. you can chang this as you like.

Monday, November 16, 2009

Disable browser back button using javascript

 Avoid users to navigate previous page by clicking browser's back button.
Use anyone script. 
window.history.forward(0);

ASP.NET Auto Complete Extender From DB with CSS


Place this class function in App_Code folder:

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
[WebService]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : WebService
{
    public AutoComplete()
    {
    }
    [WebMethod]   
    public string[] GetCompletionList(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        DataTable dt = GetRecords(prefixText);
        List items = new List(count);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strName = dt.Rows[i][0].ToString(); items.Add(strName);
        }
        return items.ToArray();
    }
    public DataTable GetRecords(string strName)
    {
        string strConn = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue("@Name", strName);
        cmd.CommandText = "Select Distinct YourValue from YourTable where YourValue like +@Name+'%' ";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd; con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        return objDs.Tables[0];
    }


 add this to Auto Complete extender :


  
                    CompletionListCssClass="AutoExtender" CompletionListHighlightedItemCssClass="AutoExtenderHighlight" CompletionListItemCssClass=".AutoExtenderList"
 runat="server" TargetControlID="txtSearch"  ServicePath="AutoComplete.asmx" OnClientItemSelected=" GetCode"  ServiceMethod="GetCompletionList"
                    

CSS:


.AutoExtender
        {
            font-family: Verdana, Helvetica, sans-serif;
            font-size: .8em;
margin:0px;
            font-weight: normal;
            border:solid 1px #006699;

            line-height:20px;
            padding:0px;
            background-color:White;
        }

        .AutoExtenderList
        {
            border-bottom:dotted 1px #006699;
            cursor:pointer;
            color:Maroon;
            left:auto;
            margin:0px;
           
        }

        .AutoExtenderHighlight
        {
            color:White;
            background-color:#006699;
            cursor:pointer;
            margin:0px;
        }



To enable OnClientItemSelected write this script:
Place one hiddenfield and call the event in script




  • function GetCode(source, eventArgs) {

         $get('<%=this.HiddenField1.ClientID%>').value = eventArgs.get_value();
         $get('<%=this.ImageButton1.ClientID%>').click();

Resizing images without loss of quality in ASP.NET

 Resize image without loss of it original quality. Here i'm resizing a big image to (410,90).


    private void MakeLarge()
    {
        System.Drawing.Image myThumbnail150;
        object obj = new object();
        obj = fuPhoto;
        System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
        HtmlInputFile hFile = (HtmlInputFile)obj;
        if (hFile.PostedFile != null && hFile.PostedFile.ContentLength > 0)
        {
            //this code used to remove some symbols between image name and replace with space
            string imgname1 = hFile.PostedFile.FileName.Replace('%', ' ').Substring(hFile.PostedFile.FileName.LastIndexOf("\\") + 1);
            string imgname2 = imgname1.Replace('#', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
            string imgname3 = imgname2.Replace('@', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
            string imgname4 = imgname3.Replace(',', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
            string imgname5 = imgname4.Replace('&', ' ').Substring(imgname1.LastIndexOf("\\") + 1);

            Finalimagename = imgname5.ToString();

            string imgname = hFile.PostedFile.FileName.Substring(hFile.PostedFile.FileName.LastIndexOf("\\") + 1);
            string sExtension = imgname.Substring(imgname.LastIndexOf(".") + 1);

            //this code is used to check image extension
            if (sExtension.ToLower() == "jpg" || sExtension.ToLower() == "gif" || sExtension.ToLower() == "bmp" || sExtension.ToLower() == "jpeg")
            {

                hFile.PostedFile.SaveAs(ResolveUrl(Server.MapPath("~/Product_Photo_Large/" + Finalimagename)));
                //imgOriginal = "Product_Photo_Large\\" + Finalimagename;
                System.Drawing.Image imagesize = System.Drawing.Image.FromFile(Server.MapPath("~/Product_Large\\" + fuPhoto.PostedFile.FileName));
                Bitmap bitmapNew = new Bitmap(imagesize);

                if (imagesize.Width < imagesize.Height)
                {

                    myThumbnail150 = bitmapNew.GetThumbnailImage(390 * imagesize.Width / imagesize.Height, 390, myCallback, IntPtr.Zero);
                    // myLarge = bitmapNew.GetThumbnailImage(410, 310, myCallback, IntPtr.Zero);
                }
                else if (imagesize.Width > imagesize.Height)
                {
                    myThumbnail150 = bitmapNew.GetThumbnailImage(410, 410 * imagesize.Height / imagesize.Width, myCallback, IntPtr.Zero);
                    // myLarge = bitmapNew.GetThumbnailImage(410, 310, myCallback, IntPtr.Zero);
                }
                else
                {
                    myThumbnail150 = bitmapNew.GetThumbnailImage(410, 390, myCallback, IntPtr.Zero);
                }

                //Create a new directory name ThumbnailImage
                //Directory.CreateDirectory(Server.MapPath("ThumbnailImage"));
                //Save image in TumbnailImage folder
                myThumbnail150.Save(ResolveUrl(Server.MapPath("~/Resize\\")) + Finalimagename, System.Drawing.Imaging.ImageFormat.Jpeg);
                imgOriginal = "Resize\\" + Finalimagename;
                // MessageLabel.Text = "Successfully uploaded";


            }
            else
            {
                // lblError1.Visible = true;
                //lblError1.Text = "Check image extension";
            }
        }
    }