Tuesday, 19 June 2012

How to allow sorting with gridview header column in asp.net

Here is complete code for allow sorting in asp.net gridview:

 public SortDirection dir
    {
        get
        {
            if (ViewState["dirState"] == null)
            {  ViewState["dirState"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["dirState"];
        }
        set
        {        ViewState["dirState"] = value;
        }

    }
        protected void gvShowRecord_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortingDirection = string.Empty;

            if (dir == SortDirection.Ascending)
            {
                dir = SortDirection.Descending;

                sortingDirection = "Desc";
            }

            else
            {
                dir = SortDirection.Ascending;
                sortingDirection = "Asc";
            }

            DataView sortedView = new DataView(BindGridOfParticipantDetail());

            sortedView.Sort = e.SortExpression + " " + sortingDirection;

            gvShowRecord.DataSource = sortedView;

            gvShowRecord.DataBind();
        }
    }


and design page require some settings  as


1. AllowSorting="True"   onsorting="gvShowRecord_Sorting"

 2. <asp:BoundField HeaderText="First Name" DataField="FirstName" SortExpression="FirstName" />


Thursday, 14 June 2012

how to create zip folder and download in asp.net


  
using ionic.zip;
 public string  SaveStreamToFile()
        {
            
             CV.Programs.Entity.ParticipantDocument participantDocument = new CV.Programs.Entity.ParticipantDocument();
            participantDocument.ParticipantId = Convert.ToInt32(Session["ParticipantId"]);
            ParticipantDocumentBLL participantDocumentBLL = new ParticipantDocumentBLL();
            DataTable _dataTable=participantDocumentBLL.GetParticipantDocument(participantDocument);
            string directoryPath = Server.MapPath("~/abc/ParticipantDOC/") +"admin"+ Session["ParticipantId"].ToString() + "" + DateTime.Now.ToString("ss");
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
                ViewState["DirName"] = directoryPath;
            }
            for (int i = 0; i < _dataTable.Rows.Count; i++)
            {
                if (Convert.ToString(_dataTable.Rows[i]["UploadedDocumentName"]) != "")
                {
                    byte[] file = null;
                    file = _dataTable.Rows[i]["UploadedDocument"] as byte[];
                    string filename = _dataTable.Rows[i]["UploadedDocumentName"].ToString();
                    string strExtenstion = Path.GetExtension(filename);
                    // Create a FileStream object to write a stream to a file
                    using (FileStream fileStream = System.IO.File.Create(directoryPath+"/" + Session["ParticipantId"] + "_"+i+"Document" + strExtenstion))
                    {
                        fileStream.Write(file, 0, file.Length);
                    }
                }
            }
            return directoryPath;
        }




        protected void DownloadAllDocuments(string dirPath)
        {


            using (MemoryStream ms = new MemoryStream())
            {
                // create new ZIP archive within prepared MemoryStream
                //Directory.CreateDirectory(Server.MapPath("/KIZUNA/ParticipantPDF/" + Session["UserLoginId"].ToString() + "_" + Session["ParticipantId"] + ".zip"));
                //ZipFile zip =ZipFile.Create(Server.MapPath("/ abc /ParticipantPDF/"+Session["UserLoginId"].ToString()+"_"+Session["ParticipantId"]+".zip"));                
                    // add some files to ZIP archive
               
                    Response.Clear();
                    Response.AddHeader("content-disposition", "filename=sample.zip");
                    Response.ContentType = MimeType(".zip");
                    //string[] allFiles = Directory.GetFiles(dirPath, "*.*", SearchOption.AllDirectories);
                    using (ZipFile zip = new ZipFile())
                    {
                        zip.AddDirectory(dirPath);
                        zip.Save(Response.OutputStream);
                    }


                    //zip.BeginUpdate();
                    //for (int i = 0; i < allFiles.Length; i++)
                    //{
                    //    zip.Add(allFiles[i].ToString());
                       
                    //}
                    //ms.WriteTo(Response.OutputStream);
                    //// clear response stream and set the response header and content type
                   
                    


                    //// write content of the MemoryStream (created ZIP archive) to the response stream
                   
                    //zip.CommitUpdate();
                    //zip.Close();
                
            }
            if (Directory.Exists(dirPath))
            {
                Directory.Delete(dirPath, true);
                //Directory.CreateDirectory(directoryPath);
                //ViewState["DirName"] = directoryPath;
            }
            if (Directory.Exists(Server.MapPath("/ abc /ParticipantPDF/" + Session["UserLoginId"].ToString() + "_" + Session["ParticipantId"] + ".zip")))
            {
                Directory.Delete(Server.MapPath("/ abc /ParticipantPDF/" + Session["UserLoginId"].ToString() + "_" + Session["ParticipantId"] + ".zip"), true);
                //Directory.CreateDirectory(directoryPath);
                //ViewState["DirName"] = directoryPath;
            }
            // close the current HTTP response and stop executing this page
            HttpContext.Current.ApplicationInstance.CompleteRequest();
            
           


        }

Wednesday, 13 June 2012

copy file from one folder to other in asp.net


 StringBuilder sb = new StringBuilder(); //  Builder to save report
           string ZipFileName = String.Format(Server.MapPath("pathfto" + DateTime.Now.ToString("yyyyMMdd") + "MyZip.zip")); //  Zip Destiny File Name
           string theDirectory = Server.MapPath("pathfrom/");     //  Folder to zip

        try
        {
            sb.Append(String.Format("Directory To Zip: {0}.<br/>", theDirectory));
            sb.Append(String.Format("Zip file: {0}.<br/>", ZipFileName));
           
            string[] allFiles = Directory.GetFiles(Server.MapPath("path"), "*.*",SearchOption.AllDirectories);   // Get all files from
            // the folder to zip

           
            foreach (string s in allFiles)
            {
                // Use static Path methods to extract only the file name from the path.
              string   fileName = System.IO.Path.GetFileName(s);
              string destFile = System.IO.Path.Combine(theDirectory, fileName);
                System.IO.File.Copy(s, destFile, true);
            }
            if (System.IO.File.Exists(ZipFileName)) //  Small piece of code
            // to delete zip file if it already exists
            {              
                System.IO.File.Delete(ZipFileName);
                sb.Append(String.Format("Deleted old Zip file: {0}.<br/>", ZipFileName));
            }

        }
        catch (Exception) { }
        }

How to create directory on server in asp.net runtime

Here is the complete code for creating new directory on server in asp.net

protected void btnCreate_Click(object sender, EventArgs e) { string directoryPath = Server.MapPath("~/") +txtDirName.Text; if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); lblMessage.Text = "Directory created"; } else lblMessage.Text = "Directory already exists"; }

Wednesday, 30 May 2012

find the control on page in nested master page.

How to find the control on page in nested master page.

  ContentPlaceHolder cp = this.Master.Master.FindControl("MainContent") as ContentPlaceHolder;
    TextBox tb = cp.FindControl("textbox1") as TextBox;

Wednesday, 9 May 2012

how to reduce mail message sending time in asp.net

Dear friend,

Please add few lines in your web config file,
it will increase the pipeline speed and reduce the sending time.

 <httpModules>
      <!-- Remove unnecessary Http Modules for faster pipeline -->
     
      <remove name="WindowsAuthentication" />
      <remove name="PassportAuthentication" />
      <remove name="AnonymousIdentification" />
      <remove name="UrlAuthorization" />
      <remove name="FileAuthorization" />
   
</httpModules>

Wednesday, 22 February 2012

Deleting Duplicate Records Using Common Table Expression (CTE) Feature of SQL Server 2005


Introduction

Deleting duplicate records from an SQL Server table can sometime become a very tedious activity especially in scenarios when you don’t have a Primary Key defined for the source table. In this article we will take advantage of Common Table Expression (CTE) feature of SQL Server 2005 to delete duplicate records from the table.

What is Common Table Expression (CTE)?

A common table expression (CTE) can be considered as a temporary result set which is defined within the execution scope of a single INSERT, UPDATE, SELECT OR DELETE statements. It is much similar to a derived table. However, a CTE can be self referenced multiple times within the scope of the same query.

Deleting Duplicate Records Using Common Table Expression (CTE) Feature of SQL Server 2005

Let us go through the below mentioned example to remove duplicates from a table which doesn’t have a Primary Key defined.
 /* Sample Script to Deleting Duplicate Records Using CTE */
USE TempDB
GO
/* Drop EmployeeDetails Table if already exists */IF OBJECT_ID (N'dbo.EmployeeDetails', N'U') IS NOT NULL
    DROP TABLE dbo.EmployeeDetails;
GO 
/* Create EmployeeDetails Details Table*/
CREATE TABLE EmployeeDetails
(
EmpID       INT IDENTITY (1,1),Name        VARCHAR(25),Age         INT)
GO
/* Insert Script is using Row Value Constructor Feature of SQL Server 2008*/

INSERT
 INTO EmployeeDetails 
VALUES 
       ('Lilly', 25)      ,('Lucy',  25)      ,('Lilly', 25)
      ,('Mary',  26)      ,('Mariam',26)      ,('Mary',  26)      ,('Lisa',  27)
GO
/* Using Common Table Expression Feature to Delete Duplicate Records */
WITH SampleCTE 
AS 
(
      SELECT ROW_NUMBER () OVER ( PARTITION BY NAME, AGE ORDER BY EmpID) AS RNUM 
      FROM EmployeeDetails 

)
DELETE FROM SampleCTE WHERE RNUM > 1
GO
/* Employee Details without Duplicates */
SELECT * FROM EmployeeDetails
GO
Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft