Friday, December 3, 2010

Zipping a folder which contains multiple files using Ionic.Zip.dll library


              String ReadmeText = string.Format("This file was created automatically by..... application on," + DateTime.Now.ToString("yyyy-MMM-dd--HH:mm:ss"), DownloadfileName, Environment.NewLine);
                StreamWriter sw = File.CreateText(Server.MapPath("~//zipfolder//Readme.txt"));
                sw.WriteLine(ReadmeText);
                sw.Close();
                string path = Server.MapPath("~//zipfolder//MyZipFile");
                using (ZipFile zip = new ZipFile())
                 {
                     zip.AddFile(Server.MapPath("zipfolder//Readme.txt"),"");
                     zip.AddFile(Server.MapPath("xmlfolder//ss.xml"),"");
                     zip.Save(Server.MapPath("~//zipfolder//MyZipFile.zip"));
                  }

For to Download a file

        Response.Clear();
        string archiveName = String.Format("xml-{0}.zip", ".zip");
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "filename=MyZipFile" + archiveName);
        Response.TransmitFile(Server.MapPath("~\\zipfolder\\MyZipFile.zip"));
        Response.End();

Saturday, October 30, 2010

Create Xml,Csv,Zip files from dataset in asp.net

For Xml
protected void Button5_Click(object sender, EventArgs e)
    {
    int _count = ListSeCh.Items.Count;
        if (_count != 0)
        {
               DataTable dtTemp = new DataTable();
              dtTemp.Columns.Add("Id", typeof(string));
              dtTemp.Columns.Add("Name", typeof(string));
            for (int j = 0; j <= _count - 1; j++)
            {
                DataRow dr;
                dr = dtTemp.NewRow();
                dr["Id"] = ListSeCh.Items[j].Value;
                dr["Name"] = ListSeCh.Items[j].Text;
                dtTemp.Rows.Add(dr);
            }
              DataSet ds11 = new DataSet();
              ds11.Merge(dtTemp);
              ds11.WriteXml(Server.MapPath("ss.xml"));

}

Code for the Zip file of "ss.xml"

                     FileStream fs = new FileStream(Server.MapPath("ss.xml"), FileMode.Open,   FileAccess.Read, FileShare.Read);
                    byte[] data = new byte[fs.Length];
                    fs.Read(data, 0, data.Length);
                    FileStream compressed = new FileStream("D:\\New Folder\\WebSite\\zipfolder\\ss.zip", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    GZipStream gzip = new GZipStream(compressed, CompressionMode.Compress, false);
                    gzip.Write(data, 0, data.Length); 
                    fs.Close();
                    gzip.Close();
                    compressed.Close();

Code for Csv

//From Dataset
                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=CPCB.csv");
                Response.Charset = "";
                Response.ContentType = "application/text";
                StringBuilder sb = new StringBuilder();
                for (int k = 0; k < dtTemp.Columns.Count; k++)
                {
                    //add separator
                    sb.Append(dtTemp.Columns[k].ColumnName + ',');
                }
                //append new line
                sb.Append("\r\n");
                for (int i = 0; i < dtTemp.Rows.Count; i++)
                {
                    for (int k = 0; k < dtTemp.Columns.Count; k++)
                    {
                        //add separator
                        sb.Append(dtTemp.Rows[i][k].ToString().Replace(",", ";") + ',');
                    }
                    //append new line
                    sb.Append("\r\n");
                }
                Response.Output.Write(sb.ToString());
                Response.Flush();
                Response.End();

OR
using Excel = Microsoft.Office.Interop.Excel;

 public void Excel_FromDataTable(DataTable dt)
    {

        Excel.ApplicationClass excel = new Excel.ApplicationClass();
        Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
        try
        {
            int iCol = 0;
            foreach (DataColumn c in dt.Columns)
            {
                iCol++;
                excel.Cells[1, iCol] = c.ColumnName;
            }

            int iRow = 0;
            foreach (DataRow r in dt.Rows)
            {
                iRow++;
                iCol = 0;
                foreach (DataColumn c in dt.Columns)
                {
                    iCol++;
                    excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
                }
            }
        }
        catch (Exception e)
        {
          Console.WriteLine(e);
        }

        if (System.IO.File.Exists("D:\\MyExcelWorkBook.csv"))
            System.IO.File.Delete("D:\\MyExcelWorkBook.csv");
   

        object missing = System.Reflection.Missing.Value;
        workbook.SaveAs("D:\\MyExcelWorkBook",        
        Excel.XlFileFormat.xlCSV, missing, missing,
        false, false, Excel.XlSaveAsAccessMode.xlExclusive,
        missing, missing, missing, missing, missing);
        workbook.Saved = true;
        workbook.Close(false, missing, missing);
        excel.Quit();
        //excel.Visible = true; 
    }

Moving items from one list box to another

 Output




 protected void Button1_Click(object sender, EventArgs e)

   {
int index=0;
        index = ListAvCh.SelectedIndex;
      if(ListAvCh.Items.Count > 0)
      {
          if(ListAvCh.SelectedIndex>-1)
          {
              string _value = ListAvCh.SelectedItem.Value;
              string _text = ListAvCh.SelectedItem.Text;
              ListItem item = new ListItem();
              item.Text = _text;
              item.Value = _value;
              ListSeCh.Items.Add(item);
              ListAvCh.Items.Remove(item);
           try
              {
                  if (ListAvCh.Items.Count == index)
                  {
                      ListAvCh.Items[index - 1].Selected = true;
                  }
                  else if (ListAvCh.Items.Count > index)
                  {
                      ListAvCh.Items[index].Selected = true;
                  }
              }
              catch(Exception )
              {

              }
          }
      }
      for (int a = 0; a < ListSeCh.Items.Count; a++)
      {
          ListSeCh.Items[a].Selected = true;
      }

    }
    protected void BtnGroupRightSelect_Click(object sender, EventArgs e)
    {
        int _count = ListAvCh.Items.Count;
        if (_count != 0)
        {
            for (int i = 0; i < _count; i++)
            {
                ListItem item = new ListItem();
                item.Text = ListAvCh.Items[i].Text;
                item.Value = ListAvCh.Items[i].Value;
                ListSeCh.Items.Add(item);
            }

            for (int a = 0; a < ListAvCh.Items.Count; a++)
            {
                ListSeCh.Items[a].Selected = true;
            }
        }
        ListAvCh.Items.Clear(); 

    }
    protected void BtnleftSingleSelect_Click(object sender, EventArgs e)
    {
        int index = 0;
        index = ListSeCh.SelectedIndex;
        if (ListSeCh.Items.Count > 0)
        {
            if (ListSeCh.SelectedIndex > -1)
            {
                string _value = ListSeCh.SelectedItem.Value;
                string _text = ListSeCh.SelectedItem.Text;
                ListItem item = new ListItem();
                item.Text = _text;
                item.Value = _value;
                ListAvCh.Items.Add(item);
                ListSeCh.Items.Remove(item);
                try
                {
                    if (ListSeCh.Items.Count == index)
                    {
                        ListSeCh.Items[index - 1].Selected = true;
                    }
                    else if (ListSeCh.Items.Count > index)
                    {
                        ListSeCh.Items[index].Selected = true;
                    }
                }
                catch (Exception)
                {

                }
            }
        }
    }
    protected void BtnleftMulSel_Click(object sender, EventArgs e)
    {
        int _count = ListSeCh.Items.Count;
        if (_count != 0)
        {
            for (int i = 0; i < _count; i++)
            {
                ListItem item = new ListItem();
                item.Text = ListSeCh.Items[i].Text;
                item.Value = ListSeCh.Items[i].Value;
                ListAvCh.Items.Add(item);
            }
        }
        ListSeCh.Items.Clear();
    }
   

Tuesday, October 12, 2010

Preventing Page Review after Logout with Forms Authentication

Use this code in pageload of userhome
 

Response.Buffer= true;
Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);
Response.Expires =-1500;
Response.CacheControl = "no-cache";
if (Session["Username"] == null)
{
Response.Redirect ("Details.aspx");
}

 
Page_Load of log out page

HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

LogOut_Btn_Click
        FormsAuthentication.SignOut();
        Session.Abandon();
        FormsAuthentication.RedirectToLoginPage();
        //  Response.Redirect("Default.aspx");


In Web_config .Net 2.0

<authentication mode="Forms">
      <forms loginUrl ="Default.aspx" timeout="30">
      </forms>
    </authentication>

   <authorization>
      <deny users ="?"/>
    </authorization>
      






In Ajax... Web.config 2.0






















<?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
            <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
                <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
                <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
                    <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
                    <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
                    <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
                </sectionGroup>
            </sectionGroup>
        </sectionGroup>
    </configSections>
 
  //Define Connection String


    <connectionStrings>
        <add name="ConnectionString" connectionString="Data Source=A;Initial Catalog=NewEx;Integrated security=True" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.web>
        <authentication mode="Forms">
            <forms loginUrl="Default.aspx" timeout="30">
            </forms>
        </authentication>
        <authorization>
            <deny users="?"/>
        </authorization>
   
   
        <pages>
            <controls>
                <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            </controls>
        </pages>
        <!--
          Set compilation debug="true" to insert debugging
          symbols into the compiled page. Because this
          affects performance, set this value to true only
          during development.
    -->
        <compilation debug="true">
            <assemblies>
                <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
                <add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies>
        </compilation>
        <httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
        </httpHandlers>
        <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        </httpModules>
   
   //Define Folder path.... 

 
    </system.web>
    <location path="CSS">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="JS">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="images">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
   
    </location>
    <system.web.extensions>
        <scripting>
            <webServices>
                <!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
                <!--
      <jsonSerialization maxJsonLength="500">
        <converters>
          <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
        </converters>
      </jsonSerialization>
      -->
                <!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->

 
                <authenticationService enabled="true" requireSSL="false"/>
                <!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
           and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
           writeAccessProperties attributes. -->
                <!--
      <profileService enabled="true"
                      readAccessProperties="propertyname1,propertyname2"
                      writeAccessProperties="propertyname1,propertyname2" />
      -->
            </webServices>
            <!--
      <scriptResourceHandler enableCompression="true" enableCaching="true" />
      -->
        </scripting>
    </system.web.extensions>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules>
            <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        </modules>
        <handlers>
            <remove name="WebServiceHandlerFactory-Integrated"/>
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        </handlers>
    </system.webServer>
</configuration>

     

   


   
     
   

   
     
   



 

Wednesday, May 5, 2010

Creating a Strongly Typed DataSet in Asp.Net

Strongly typed DataSets are merely generic DataSets that have their columns and tables defined in advance, so the compiler already knows what they will contain. 

1.     Open Visual Studio, and create a new ASP.NET web site.
2.     In Solution Explorer, right-click to add a new item, and select DataSet. Visual Studio will recommend placing the DataSet file inside the App_Code folder, which you should allow it to do for you.
3.     The DataSet1.xsd will open in design mode, and the TableAdapter Configuration Wizard will be launched. For now, just click Cancel, because you will add tables by dragging them from the Server Explorer.
4.     Locate the Server Explorer Toolbox, navigate to your SQL Server 2005 database,
5.     Drag the dbo.empuserdetails table to your DataSet Designer window. The window should now resemble Figure.
    
                  As you can see from Figure 1, for each table that is added to the designer, Visual Studio creates a strongly  typed DataTable and a TableAdapter. The DataTable has all of its columns already defined. The table adapter is the object you will use to fill the table. By default, you have a Fill() method that will find every row from that table.
This strongly typed DataSet, as is, will return all of the records in the Product table. 
Since the Empuser table contains a lot of information, let us modify the default query to return only the employee that belong to the given empid. To do this, right-click the empuserdetailsTableAdapter and select Add Query. Pick Use SQL statements and click the Next button. Then, choose SELECT, which returns rows, and click Next. Finally, enter the following query in the window 

SELECT Empid, Username, Password 
FROM dbo.Empuserdetails
Where Empid= @Empid

Place a GridView in default.aspx
The Code in Default.aspx.cs is given below
 
public partial class _Default : System.Web.UI.Page 
{
  protected void Page_Load(object sender, EventArgs e)
  {
  DataSet1TableAdapters.EmpuserdetailsTableAdapter adas=
         new DataSet1TableAdapters.EmpuserdetailsTableAdapter ();
DataSet1.EmpuserdetailsDataTable table=adas.GetData();
                                                              //or GetDataBy(1)
 GridView1.DataSource=table;
 GridView1.DataBind();
   }
} 




 

Tuesday, April 20, 2010

Grid View Editing,Updating in Asp.Net



In Default2.aspx.cs

using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Default2 : System.Web.UI.Page
{
Class1 ob = new Class1();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
show();
}
public void show()
{
GridView1.DataSource = ob.selec();
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
show();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow gr=GridView1.Rows[e.RowIndex];
string id = ((TextBox)gr.Cells[0].Controls[0]).Text;
string na = ((TextBox)gr.Cells[1].Controls[0]).Text;
string age = ((TextBox)gr.Cells[2].Controls[0]).Text;
ob.up(na, Convert.ToInt32(age), Convert.ToInt32(id));
GridView1.EditIndex = -1;
show();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
show();
}

//Get Values in Row Deleting Event

//string Val=GridView1.Rows[e.RowIndex].Cells[1].Text;
}
 
In Class1.cs
 
using System.Data.SqlClient;

///
/// Summary description for Class1
///

public class Class1
{
SqlConnection con = new SqlConnection(@"Data Source=INDIA\SQLEXPRESS;Initial catalog=ani;integrated security=true");
public Class1()
{
//
// TODO: Add constructor logic here
//
}
public DataTable selec()
{
SqlDataAdapter da = new SqlDataAdapter("select * from aa", con);
DataSet ds = new DataSet();
da.Fill(ds,"gg");
return ds.Tables["gg"];
}
public void up(string name, int age,int id)
{
SqlCommand cmd = new SqlCommand("update aa set name='" + name + "',age=" + age + " where id=" + id + "", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}

 ImageButton1_Click on Gridview

  protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton imgbtn = (ImageButton)sender;
        GridViewRow grdRow = (GridViewRow)imgbtn.NamingContainer;
        LinkButton name = (LinkButton)imgbtn.FindControl("controlIdName");
        Label tId = (Label)imgbtn.FindControl("Label1");
        string ab = tId.Text;
     
    }
Editing GridView Row Using Button1

 protected void Button1_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        GridViewRow gr = (GridViewRow)btn.NamingContainer;
        GridView1.EditIndex = gr.RowIndex;
        show();
    }