Saturday, January 29, 2011

Ajax Auto-complete

Download  AjaxControlToolkit.dll
Add refrence in page,Make a webservice autocomplet.asmx
open autocomplet.cs in app_code



using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : WebService
{
    public AutoComplete()
    {
    }
    private static string _GroupCode;
    string conn = ConfigurationManager.AppSettings["ConnectionString"].ToString();
    public string GroupCode
    {
        set
        {
            _GroupCode = value;
        }
        get
        {
            return _GroupCode;
        }
    }
    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        //string conn = ConfigurationManager.AppSettings["ConnectionString"].ToString();
        SqlConnection con = new SqlConnection(conn);
        con.Open(); SqlCommand cmd = new SqlCommand();
        string Query; string[] temp = prefixText.Trim().Split(' ');
        Query = "SELECT Question, answer FROM faq WHERE";
        for (int i = 0; i < temp.Length; i++)
        {
            Query = Query + " Question LIKE \'%" + temp[i] + "%\'";
            if (i < (temp.Length - 1))
            {
                Query = Query + " OR";
            }
        }
        cmd.CommandText = Query;
        cmd.Connection = con;
        SqlDataReader dr = cmd.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr); con.Close();
        string[] r = new string[dt.Rows.Count];

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            r[i] = dt.Rows[i][0].ToString();
        }
        return r;
    }
}


////////Add refrence in aspx page

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>


<asp:TextBox ID="Mytextbox" runat="server" AutoCompleteType="Search"
                    Width="300px" CssClass="txtbox"></asp:TextBox>
 <ajaxToolkit:AutoCompleteExtender
    runat="server"
    ID="autoComplete"
    TargetControlID="Mytextbox"
    ServiceMethod="GetCompletionListall"
    ServicePath="AutoComplete.asmx"
    MinimumPrefixLength="2"
    CompletionInterval="100"
    CompletionSetCount="20"
    CompletionListCssClass="autocomplete_completionListElement"
    CompletionListItemCssClass="autocomplete_listItem"
    CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
    DelimiterCharacters=","
    BehaviorID="AutoCompleteEx"
    OnClientPopulated="HideImage" OnClientPopulating="ShowImage"
   Enabled="true">            
</ajaxToolkit:AutoCompleteExtender>        




Add script

<script language="javascript" type="text/javascript">

    function ShowImage()
    {
        document.getElementById('<%=Mytextbox.ClientID %>').style.backgroundImage = 'url(img/wait.gif)';
        document.getElementById('<%=Mytextbox.ClientID %>').style.backgroundRepeat = 'no-repeat';
        document.getElementById('<%=Mytextbox.ClientID %>').style.backgroundPosition = 'right';
    }
    function HideImage()
    {
       document.getElementById('<%=Mytextbox.ClientID %>').style.backgroundImage = 'none';
    }
</script>

download image and place in img folder wait.gif

place code in .cs page on load

    protected void Page_Load(object sender, EventArgs e)
    {


        this.Mytextbox.Attributes.Add("onkeypress", "ShowImage()");
        this.Mytextbox.Attributes.Add("onblur", "HideImage()");
    }

Thursday, January 27, 2011

output parameter in .net

SqlConnection con = GetConnection();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "countid";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = cmd.Parameters.AddWithValue("@mode", mode);
parameter = cmd.Parameters.AddWithValue("@logeduserid", logeduserid);
parameter = cmd.Parameters.AddWithValue("@updatedempid", updatedempid);
parameter = cmd.Parameters.Add("@result",SqlDbType.VarChar,10);
parameter.Direction = ParameterDirection.Output;
SqlDataReader dr = cmd.ExecuteReader();
if(!(mode=="V" || mode=="R")) id = parameter.Value.ToString();
DataTable dt = new DataTable();
dt.Load(dr); con.Close();
return dt;

/**************************************************
ALTER procedure [dbo].[countid]
(@mode varchar(2),@logeduserid varchar(10),@updatedempid varchar(10),@result nvarchar(20) output)
as begin
declare @a as bigint declare @b as bigint declare @c as bigint
select @a=isnull(max(employee_code),0)from HRMS_MAS_EMPLOYEE where len([employee_code])=5
set @c=len(@a)
set @result= substring('00000',1,5-@c)+cast(@a as varchar(6))

get connection

protected SqlConnection GetConnection()
{
string connection = ConfigurationManager.AppSettings["connectionString"];
SqlConnection con = new SqlConnection(connection);
if (con.State != ConnectionState.Open)
con.Open();
return con;
}

month & year from code

DataTable dt = new DataTable();
DataColumn name = new DataColumn("value", typeof(string));
dt.Columns.Add(name);
DataRow row;
/*to genrate years */
for (int i = 1970; i <= DateTime.Now.Year; i++) { row = dt.NewRow(); dt.Rows.Add(row); row[0] = i; } return dt; /* for months*/
for (int i = 1; i < 13; i++)
{
row = dt.NewRow();
dt.Rows.Add(row);
row[0] = Convert.ToDateTime("1-" + i + "-2000").ToString("MMM"); ;
}
return dt;

Get datatable

/*text is query */
public DataTable connecttotable(string text)
{
SqlConnection con = GetConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = text;
cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr); con.Close();
return dt;
}

get dataset from table

public DataSet connecttotabledataset(string text)
{
SqlConnection con = GetConnection();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(text, con);
da.Fill(ds);
return ds;
}
//text is Query here

Remove Multiple space

public string removemuttiplespace(string core)
{
string[] user = (core).Split(' ');
string spc = "";
for (int s = 0; s < user.Length; s++)
{
if (user[s].Length != 0)
{
spc += user[s].ToString() + " ";
}

}
return spc;
}

Data encription c# .net

public string Encrypt(string sData)
{
try
{
byte[] encData_byte = new byte[sData.Length];

encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);

string encodedData = Convert.ToBase64String(encData_byte);

return encodedData;

}
catch (Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}
public string Decrypt(string sData)
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(sData);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}

Genrate calendar in c#


  public DataTable calander(int year, int month)
    {
        DataTable dt = new DataTable();
        DataRow row;
        int k = 1; bool leav = true;
        int day = System.DateTime.DaysInMonth(year, month);
        int da = (int)Convert.ToDateTime(year+"-" + month + "-1"  ).DayOfWeek;
        DataColumn name1 = new DataColumn("SUN", typeof(string));
        DataColumn name2 = new DataColumn("MON", typeof(string));
        DataColumn name3 = new DataColumn("TUE", typeof(string));
        DataColumn name4 = new DataColumn("WED", typeof(string));
        DataColumn name5 = new DataColumn("THU", typeof(string));
        DataColumn name6 = new DataColumn("FRI", typeof(string));
        DataColumn name7 = new DataColumn("SAT", typeof(string));
        dt.Columns.Add(name1); dt.Columns.Add(name2); dt.Columns.Add(name3);  
        dt.Columns.Add(name5); dt.Columns.Add(name6); dt.Columns.Add(name7);
dt.Columns.Add(name4);
        for (int i = 0; i <= 5; i++)
        {
            row = dt.NewRow();
            dt.Rows.Add(row);
            for (int j = 0; j < 7; j++)
            {
                if (da > j && k < 8 && leav)
                { row[j] = ""; }
                else
                {
                    row[j] = k++;
                    leav = false;
                }
                if (k == day + 1) { i++; break; }
            }
        }
        return dt;
    }