Thursday, April 12, 2012

Sorting asp.net Gridview using Jquery

Tablesorter is a Jquery pulgin easy to use. Now you can sort your data without postbacking the page.It gives the client side sorting functionality.
Click to check more on Tablesorter

Code

Default.aspx
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="jqueryTableSort._Default" %>


    
    
    
    


    

Sort gridview using Jquery plugin Table Sorter

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace jqueryTableSort
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) 
            {
                BindGrid();
                
            }

        }
        #region BIND GRID
        private void BindGrid() 
        {
            CountryDataData objData = new CountryDataData();
            GridView1.DataSource = objData.GetCountryDataList();
            GridView1.DataBind();
            GridView1.UseAccessibleHeader = true;
            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader; 

        }
        #endregion
    }
}
CountryData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace jqueryTableSort
{
    public class CountryDataData
    {
        public int Id { get; set; }
        public string CountryName { get; set; }
        public List GetCountryDataList()
        {
            return new List
            {
                new CountryDataData{Id=1,CountryName="India"},
                new CountryDataData{Id=2,CountryName="Australia"},
                new CountryDataData{Id=3,CountryName="UK"},
                new CountryDataData{Id=4,CountryName="UAE"},
                new CountryDataData{Id=5,CountryName="Bangladesh"},
                new CountryDataData{Id=6,CountryName="Austria"},
                new CountryDataData{Id=7,CountryName="Japan"},
                new CountryDataData{Id=8,CountryName="China"},
                new CountryDataData{Id=9,CountryName="Dubai"},
                new CountryDataData{Id=10,CountryName="South Africa"},
                new CountryDataData{Id=11,CountryName="Mexcico"},
                new CountryDataData{Id=12,CountryName="Merryland"},
                new CountryDataData{Id=13,CountryName="USA"},
                new CountryDataData{Id=14,CountryName="Peru"},
                new CountryDataData{Id=15,CountryName="Nepal"},
                new CountryDataData{Id=16,CountryName="Pakistan"},
                new CountryDataData{Id=17,CountryName="Srilanka"},
                new CountryDataData{Id=18,CountryName="Vietnam"},
                new CountryDataData{Id=19,CountryName="Westindies"},
                new CountryDataData{Id=20,CountryName="England"},
                new CountryDataData{Id=21,CountryName="Afganistan"},
                new CountryDataData{Id=22,CountryName="Russia"},
                new CountryDataData{Id=23,CountryName="Newzeland"},
                new CountryDataData{Id=24,CountryName="Timore"},
                new CountryDataData{Id=25,CountryName="Canada"}

            };

        }

    }
}



Download Code





Monday, April 2, 2012

Creating ZIP and UNZIP files in ASP.NET using DotNetZip library.

DotNetZip is easy to use free class library for ziping and extracing the zip files.
Check this DotNetZip for more information.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ionic.Zlib;
using Ionic.Zip;
using System.IO;




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

        }
        #region Download ZIP File
        private void DownloadFile()
        {
            if (FileUpload1.HasFile)
            {
                //file upload folder App_Data
                string _fileName = FileuploadUtility.UploadFile(FileUpload1, Server.MapPath("~/App_Data/"), Session.SessionID);
                string[] _zip_fileName = _fileName.ToString().Split('.');
                Response.Clear();
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "filename=" + "download_" + _zip_fileName.ToString() + ".zip");

                using (ZipFile zip = new ZipFile())
                {
                    zip.AddEntry(_fileName.ToString(), File.ReadAllBytes(Server.MapPath("~/App_Data/" + _fileName.ToString())));
                    zip.Save(Response.OutputStream);
                }
            }

        }
        #endregion

        #region EXTRACT THE ZIP FILE
        private void ExtractZipFile() 
        {
            string _fileName = FileuploadUtility.UploadFile(FileUpload1, Server.MapPath("~/App_Data/"), Session.SessionID);

            using (ZipFile zip1 = ZipFile.Read(Server.MapPath("~/App_Data/" + _fileName.ToString())))
            {
                
                foreach (ZipEntry e in zip1)
                {
                    //destination folder zipfiles
                    e.Extract(Server.MapPath("~/ZipFiles/"), ExtractExistingFileAction.OverwriteSilently);
                }
            }

        }
        #endregion

        protected void Button1_Click(object sender, EventArgs e)
        {
            DownloadFile();

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            ExtractZipFile();
        }
    }
}







Download Sample

Sunday, February 5, 2012

Change DB owner in SQL Server Database

Change db owner in sql server 2005 database.

Example

DECLARE @old sysname, @sql varchar(1000)

SELECT

 @old = 'oldOwner_CHANGE_THIS'

 , @sql = '

 IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES

 WHERE

     QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?''

     AND TABLE_SCHEMA = ''' + @old + '''

 )

 ALTER SCHEMA dbo TRANSFER ?'

EXECUTE sp_MSforeachtable @sql

Thursday, October 13, 2011

Difference between ref and out parameters in c#

The difference between ref and out parameters is at the language level. In case of ref you must have to assign it as in "Example by ref" string val is assigned.
In case of out you don't need to assign an out parameter before passing it to a method. But the out parameter in that method must assign the parameter before returning.

Example

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
        Response.Write("Example by ref");
        string val = "hello";
        ExampleByRef(ref  val);
        Response.Write(val);
        Response.Write("Example by out
"); string vals; ExampleByOut(out vals); } public static void ExampleByRef(ref string val) { if (val == "hello") { System.Web.HttpContext.Current.Response.Write("Example by ref case"); } else { System.Web.HttpContext.Current.Response.Write("Example by ref else response"); } val = "hi"; } public static void ExampleByOut(out string vals) { vals = "Example by Out case
"; System.Web.HttpContext.Current.Response.Write(vals); } }


Output
Example by ref
Example by ref case
hi
Example by out
Example by Out case

Wednesday, September 14, 2011

Track User status if user closes the browser window.

This is a sample application of "User Status" tracking in asp.net. When the user is logged in. This will show the user status as online user. If the user click on logout then it automatically logout user and update the user status as off line. But what if the user closes the browser then also you can track the status.
Here in this example I have used SQL server as database. I have created a table [tbluserlogins] in database with a "userstatus" column as bit datatype. Every time I update the "userstatus" when user logged in and logged out.

Sample Table Structure
CREATE TABLE [dbo].[tblUserLogins](
 [sno] [int] IDENTITY(1,1) NOT NULL,
 [username] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [password] [nvarchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [userStatus] [bit] NOT NULL,
 [lastLogin] [datetime] NOT NULL CONSTRAINT [DF_tblUserLogins_lastLogin]  DEFAULT (getdate()),
 CONSTRAINT [PK_tblUserLogins] PRIMARY KEY CLUSTERED 
(
 [username] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
1. We have to maintain the session state like this
2. In global.asax there we can update the status.
void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown
        //Update the user status if the application is closed

        try
        {
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.Text, "update tblUserLogins set userStatus='false' where sno=" + Session["userid"].ToString(), null);
        }
        catch (Exception ex)
        {

            throw ex;
        }


    }


void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
        //If the user close the browser window or session is end. It will automatically update the staus
        try
        {
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.Text, "update tblUserLogins set userStatus='false' where sno=" + Session["userid"].ToString(), null);
        }
        catch (Exception ex)
        {

            throw ex;
        }

    }


Download the sample code




Monday, June 13, 2011

Client Callbacks in ASP.NET

Some time a situation comes wherein you want to process some server side processing without refreshing the whole page. This can be achived by using Microsoft ajax controls like "UpdatePanel" but some time you want to implement a functionality on your own in that case you can use your own client Callbacks.
For this first we will implement the System.Web.UI.ICallbackEventHandler. The ICallbackEventHandler has two methods.
1. GetCallbackResult : This method will return the reslut of server side processing.

2. RaiseCallbackEvent : This method will be called by client and you can use it to get the parameter values from client.

In this example I have used a Textbox and getting the value of that text box value in a lable while typing in textbox.


Code
    
   

Welcome to ASP.NET!


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

namespace CallbackExample
{


    public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
    {
        string _result = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            //callback reference of the client-side function which will be called after the completion of server side processing. 
            string callbackRef = Page.ClientScript.GetCallbackEventReference(this, "args", "ClientFunction", "");
            // Javascript function that will be called from client to call the server
            string callBackFunctionScript = @"function CallServerFunction(args){" + callbackRef + "}";
            // Now register the script on the page
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServerFunction", callBackFunctionScript, true);
        }

        public string GetCallbackResult()
        {
            //throw new NotImplementedException();
            return _result;


        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            _result = eventArgument;
        }

        
    }
}







Download Code