Friday 10 February 2012

CREATE ZIP FILE IN ASP.NET



public class Zip
{
public Zip()
{
}
static string writetofilepath = System.Web.HttpContext.Current.Server.MapPath("~/Files/");
public static void WriteZipFile(string[] filesToZip, string writeToFilePath)
{
try
{
if (EnsureDirectory(writetofilepath))
{
Crc32 crc = new Crc32();
FileStream fs1 = File.Create(writeToFilePath);
ZipOutputStream s = new ZipOutputStream(fs1);
s.SetLevel(9); // 0 - store only to 9 - means best compression
for (int i = 0; i < filesToZip.Length; i++)
{
      // Must use a relative path here so that files show up in the Windows Zip File Viewer
      // .. hence the use of Path.GetFileName(...)
ZipEntry entry = new ZipEntry(Path.GetFileName(writetofilepath + filesToZip[i]));
entry.DateTime = DateTime.Now;
// Read in the
using (FileStream fs = File.OpenRead(writetofilepath + filesToZip[i]))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
      // set Size and the crc, because the information
      // about the size and crc should be stored in the header
      // if it is not set it is automatically written in the footer.
      // (in this case size == crc == -1 in the header)
      // Some ZIP programs have problems with zip files that don't store
      // the size and crc in the header.
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
s.Finish();
s.Close();
}
}
catch (Exception ex)
{
HttpContext.Current.Trace.Warn(ex.ToString());
}
}
private static bool EnsureDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return true;
}
public string[] getdir()
{
DirectoryInfo di = new DirectoryInfo(writetofilepath);
FileInfo[] rgFiles = di.GetFiles("*.pdf");
string[] files = new string[rgFiles.Length];
int i = 0;
foreach (FileInfo fi in rgFiles)
{
files[i] = fi.Name;
 i++;
 }
 return files;
 }
 }




AUTO COMPLETE EXTENDER IN ASP.NET



 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
       
 TargetControlID="TextBox1" ServiceMethod="GetCompletionList"
            ServicePath="AjaxLearning.asmx" MinimumPrefixLength="1"
            CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
            CompletionListItemCssClass="autocomplete_listItem"
            CompletionListCssClass="autocomplete_completionListElement"
            ShowOnlyCurrentWordInCompletionListItem="True">
</asp:AutoCompleteExtender>


CREATING CSV FILE IN ASP.NET



        SqlConnection conn = new SqlConnection();
        SqlCommand com = new SqlCommand();
        conn.ConnectionString = "TYPE CONNECTION STRING HERE";
        string query_str = "WRITE QUERY HERE";
        com.CommandText = query_str;
        com.CommandType = CommandType.Text;
        com.Connection = conn;
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = com;
        DataSet ds = new DataSet();
        da.Fill(ds);
        DataTable dt = ds.Tables[0];
        HttpContext context = HttpContext.Current;
        context.Response.Clear();
        context.Response.ContentType = "text/csv";
        context.Response.AddHeader("Content-Disposition","attachment; Filename = FILE.csv");
        for (int i = 0; i < dt.Columns.Count - 1 ; i++)
        {
         if (i > 0) context.Response.Write(",");
         context.Response.Write(dt.Columns[i].ColumnName);
        }
        context.Response.Write(Environment.NewLine);
        foreach (DataRow dr in dt.Rows)
        {
         for (int i = 0; i < dt.Columns.Count - 1; i++)
        {
         if (i > 0) context.Response.Write(",");
         context.Response.Write(dr.ItemArray[i].ToString());
         }
         context.Response.Write(Environment.NewLine);
         }
        context.Response.End();



EXPIRE DATE AND TIME FOR COOKIE IN DOT NET


 
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <script runat="server">

protected void Page_Load(object sender, System.EventArgs e) {
HttpCookie cookie = new HttpCookie("ColorCookie");
cookie["Color"] = "Crimson";
cookie["ColorValue"] = "#DC143C";
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
Label1.Text = "Cookie created successfully and set expire after 1 year";
 HttpCookie myCookie = Request.Cookies["ColorCookie"];

if (myCookie != null)
{
string color = myCookie["Color"];
string colorValue = myCookie["ColorValue"];
Label1.Text += "<br /><br />Cookie[ColorCookie] Found and read<br/>";
Label1.Text += "Color: " + color;
Label1.Text += "<br />Value: " + colorValue;
}
}
</script>

 <html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">
<title>asp.net cookie example: how to set expires date time</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Teal">asp.net Cookie example: set cookie expires</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="Crimson"
Font-Italic="true"
Font-Bold="true"
> 
</asp:Label>
</div>
</form>
</body>
</html>


HOW TO READ COOKIES VALUES IN DOT NET


 
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void Page_Load(object sender, System.EventArgs e) {
if (!this.IsPostBack)
{
HttpCookie infoCookie = new HttpCookie("Info");
infoCookie["Country"] = "USA";
infoCookie["City"] = "NewYork";
infoCookie["Name"] = "Jenny";
infoCookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(infoCookie);
}
}
protected void Button1_Click(object sender, System.EventArgs e) {

HttpCookie cookie = Request.Cookies["Info"];
if (cookie != null)

{
string country = cookie["Country"];
string city = cookie["City"];
string name = cookie["Name"];
Label1.Text = "Cookie[Info] Found and read<br/>";
Label1.Text += "Name: " + name;
Label1.Text += "<br />Country: " + country;
Label1.Text += "<br />City: " + city;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">
<title>asp.net cookie example: how to read a cookie</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Teal">asp.net Cookie example: Read a cookie</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="DarkGreen">
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="Read Cookie"
OnClick="Button1_Click"
Font-Bold="true"
ForeColor="HotPink"
/>
</div>
</form>
</body>
</html>


FILE HANDLING IN ASP.NET : DELETE FROM FILE



Protected Void DeleteFromFile()
{
FileStream fr = new FileStream(Server.MapPath("temp.txt"), FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fr);
 FileStream fwt = new FileStream(Server.MapPath("abcd.txt"), FileMode.Create, FileAccess.Write);
 StreamWriter swt = new StreamWriter(fwt);
for (int i = 1; i <= total; i++)
{
if (position == i)
{
for (int j = 0; j < 5; j++) sr.ReadLine();
}
else
{
for (int j = 0; j < 5; j++) swt.WriteLine(sr.ReadLine());
}
}
swt.Flush();
sr.Close();
fr.Close();
swt.Close();
fwt.Close();
FileStream fw = new FileStream(Server.MapPath("temp.txt"), FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fw);
FileStream frt = new FileStream(Server.MapPath("abcd.txt"), FileMode.Open, FileAccess.Read);
StreamReader srt = new StreamReader(frt);
while (!srt.EndOfStream) sw.WriteLine(srt.ReadLine());
sw.Flush();
sw.Close();
fw.Close();
frt.Close();
srt.Close();
if (position == total)
{
total--;
position = total;
            }
else
{
total--;
}
read_text(position);
}
protected void read_text(long pos)
{
FileStream fs = new FileStream(Server.MapPath("temp.txt"), FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
if (pos == 1)
{
sr.BaseStream.Seek(0, SeekOrigin.Begin);
TextBox1.Text = sr.ReadLine();
TextBox2.Text = sr.ReadLine();
TextBox3.Text = sr.ReadLine();
TextBox4.Text = sr.ReadLine();
sr.ReadLine();
}
else
{
for (int i = 0; i < (pos - 1) * 5; i++)
{
sr.ReadLine();
}
TextBox1.Text = sr.ReadLine();
TextBox2Text = sr.ReadLine();
TextBox3.Text = sr.ReadLine();
TextBox4.Text = sr.ReadLine();
sr.ReadLine();
}
sr.Close();
fs.Close();
}



HOW TO USE COOKIES IN DOT NET TECHNOLOGY




<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
protected void page_Load(object sender, System.EventArgs e) {
HttpCookie favoriteColor = Request.Cookies["FavoriteColor"];
if (favoriteColor == null)
{
HttpCookie userCookie = new HttpCookie("FavoriteColor");
userCookie["Name"] = "Jones";
userCookie["Color"] = "Crimson";
userCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(userCookie);
Label1.Text = "Cookie created at: " + DateTime.Now.ToString()+ "<br /><br />";
}
else
{
string name = favoriteColor["Name"];
string color = favoriteColor["Color"];
Label1.Text += "Cookie found and read<br />";
Label1.Text += "Hi " + name + " your favorite Color: " + color;
}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

<title>asp.net cookie example: how to use cookie in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">asp.net cookie: how to use</h2>
<asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="SeaGreen">
</asp:Label>
</div>
</form>
</body>
</html>