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>