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>




FILE HANDLING IN ASP.NET : RETRIEVE DATA FROM A FILE



Protected Void RetriveFromFile()
{
position = 0;
total = 0;

FileStream fs = new FileStream(Server.MapPath("Temp/temp.txt"), FileMode.Open, FileAccess.Read);

StreamReader sr = new StreamReader(fs);
while (!sr.EndOfStream)
{
for (int i = 0; i < 5; i++)
{
sr.ReadLine();
}
total++;
}
position++;
read_text(position);

sr.Close();
fs.Close();
}
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();
TextBox2.Text = sr.ReadLine();
TextBox3.Text = sr.ReadLine();
TextBox4.Text = sr.ReadLine();

sr.ReadLine();
}

sr.Close();
fs.Close();
}

========================================================================

HOW TO ADD IMAGE WORD DOC. USING C# CODE IN DOT NET




Hi everyone,
i'd like to add an image/logo to word document automatically via c# code.
i used with Microsoft.Office.Interop.Word.Document object to open the word documents,
and then i used the Shapes.AddPicture method for inserting the image into the documents.

(I didn't use the InlineShapes.AddPicture method because, these method doesn't support layers etc.)

here is my code:
object FileName = filesCollection.ToString();
object saveFileName = FileName;
object vk_read_only = false;
object vk_visibile = true;
object vk_false = false;
object vk_true = true;
object vk_dynamic = 2;
object vk_missing = System.Reflection.Missing.Value;
object LinkToFile = true;
object myRange = System.Reflection.Missing.Value;
object vk_format = Microsoft.Office.Interop.Word.WdOpenFormat.wdOpenFormatDocument;
object Left = 1;
object Top = 1;
object Width = 498;
object Height = 89;

oWord.Visible = true;
oWord.Activate();






FILE HANDLING IN ASP.NET : INSERT IN A FILE




Protected Void InsertIntoFile()
{
if (TextBox1.Text != "" && TextBox2.Text != "" && TextBox3.Text != "" && TextBox4.Text != "")
{
FileStream fs = new FileStream(Server.MapPath("Temp/temp.txt"), FileMode.Append, FileAccess.Write);

StreamWriter sw = new StreamWriter(fs);

sw.WriteLine(TextBox1.Text);
sw.WriteLine(TextBox2.Text);
sw.WriteLine(TextBox3.Text);
sw.WriteLine(TextBox4.Text);
sw.WriteLine();
sw.Flush();
sw.Close();
fs.Close();
}
else Response.Write("Please fill all the fields.");

total = 0;

FileStream fs1 = new FileStream(Server.MapPath("Temp/temp.txt"), FileMode.Open, FileAccess.Read);

StreamReader sr = new StreamReader(fs1);

while (!sr.EndOfStream)
{
for (int i = 0; i < 5; i++)
{
sr.ReadLine();
}
total++;
}
}




Thursday, 9 February 2012

XML FILE FOR ADROTATOR IN ASP.NET



<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>

<Ad>

<ImageUrl>Picture_URL1.jpg</ImageUrl>

<NavigateUrl>http://www.address1.com</NavigateUrl>

<AlternateText>Text1</AlternateText>

<Keyword>Key1</Keyword>

<Impressions>100</Impressions>

</Ad>

<Ad>

<ImageUrl>Picture_URL2.jpg</ImageUrl>

<NavigateUrl>http://www.address2.com</NavigateUrl>

<AlternateText>Text2</AlternateText>

<Keyword>Key2</Keyword>

<Impressions>100</Impressions>

</Ad>

<Ad>

<ImageUrl>Picture_URL3.jpg</ImageUrl>

<NavigateUrl>http://www.address3.com</NavigateUrl>

<AlternateText>Text3</AlternateText>

<Keyword>Key3</Keyword>

<Impressions>100</Impressions>

</Ad>

</Advertisements>



HOW TO USE ENCRYPTION & DECRYPTION METHOD IN ASP.NET



string NORMAL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string ENCRYPT = "YO17KPLVSU50C8WE64GAI3MB2DFNZQ9JXTRH";
string strInput = "MamtaDevi";
string strEncrypted = string.Empty;
string strDecrypted = string.Empty;
string strNewChar;
string strLtr;
int iIdx;
protected EncryptionDecryptionDemo()
   {
    Response.Write(strInput);
    Response.Write("<br />");
    for (int i = 0; i < strInput.Length; i++)
   {
    strLtr = strInput.Substring(i, 1).ToUpper();
    iIdx = NORMAL.IndexOf(strLtr);
    strNewChar = ENCRYPT.Substring(iIdx, 1).ToUpper();
    strEncrypted += strNewChar;
    }
    Response.Write(strEncrypted);
    Response.Write("<br />");

    for (int i = 0; i < strInput.Length; i++)
    {
    strLtr = strEncrypted.Substring(i, 1).ToUpper();
    iIdx = ENCRYPT.IndexOf(strLtr);
    strNewChar = NORMAL.Substring(iIdx, 1).ToUpper();
    strDecrypted += strNewChar;
    }
    Response.Write(strDecrypted);
    }

If you want to use any special characters you can add in variable "NORMAL" and equivalent encrypted value in variable "ENCRYPT".
"ENCRYPT" variable has the reordered letters of "NORMAL" variable.

=====================================================================


XML FILE OPERATIONS : UPDATE AND DELETE IN XML FILE



XML File Operations : Update a node in XML file

protected void UpdateXMLNode(string xmlFilePath)
        {
        if (File.Exists(xmlFilePath))
        {
            DataSet ds = new DataSet();
            ds.ReadXml(xmlFilePath);
            string filterExpression = "NAME = '" + TextBox1.Text + "'";
            DataRow[] row = ds.Tables[0].Select(filterExpression);
         if (row.Length == 1)
         {
             row[0][0] = TextBox2.Text;
             row[0][1] = TextBox3.Text;
             row[0][2] = TextBox4.Text;
            ds.WriteXml(xmlFilePath);
          }
          }
          }


XML File Operations : Delete from XML file

protected void DeleteXMLNode(string xmlFilePath)
        {
        if (File.Exists(xmlFilePath))
        {
            DataSet ds = new DataSet();
            ds.ReadXml(xmlFilePath);
            string filterExpression = "NAME = '" + TextBox4.Text + "'";
            DataRow[] row = ds.Tables[0].Select(filterExpression);
            if (row.Length == 1)
         {
            row[0].Delete();
            ds.WriteXml(xmlFilePath);
          }
          }
          }




HOW TO CREATE WEB CONFIG FILE IN ASP.NET



<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
    <configSections>
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                    <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
                    <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                    <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                    <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
    </sectionGroup>
    </sectionGroup>
    </sectionGroup>
    </configSections>
    <appSettings/>
    <connectionStrings/>
    <system.web>
<!--
            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.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        </assemblies>
        </compilation>
<!--

            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
-->
        <authentication mode="Windows"/>
<!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
        <error statusCode="403" redirect="NoAccess.htm" />
        <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
        <pages>
            <controls>
            <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
             <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </controls>
        </pages>
        <httpHandlers>
        <remove verb="*" path="*.asmx"/>
        <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
         <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
        </httpHandlers>
        <httpModules>
        <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
    </system.web>
    <system.codedom>
     <compilers>
     <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
           <providerOption name="CompilerVersion" value="v3.5"/>
           <providerOption name="WarnAsError" value="false"/>
            </compiler>
            <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
           <providerOption name="CompilerVersion" value="v3.5"/>
           <providerOption name="OptionInfer" value="true"/>
           <providerOption name="WarnAsError" value="false"/>
           </compiler>
           </compilers>
           </system.codedom>
<!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
-->
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules>
            <remove name="ScriptModule"/>
            <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </modules>
        <handlers>
            <remove name="WebServiceHandlerFactory-Integrated"/>
            <remove name="ScriptHandlerFactory"/>
            <remove name="ScriptHandlerFactoryAppServices"/>
            <remove name="ScriptResource"/>
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.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=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </handlers>
    </system.webServer>
    <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
     <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
     <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
     </dependentAssembly>
     <dependentAssembly>
     <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
     <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
     </dependentAssembly>
     </assemblyBinding>
     </runtime>
</configuration>



XML FILE OPERATIONS : CREATE AND INSERT IN XML FILE



protected void InsertXML(string xmlFilePath, string elements, string element)
{
 if (!File.Exists(xmlFilePath))
{
string data = "<" + elements + ">" + "</" + elements + ">";
doc.Load(new StringReader(data));
XmlElement child = doc.CreateElement(element);
child.SetAttribute("NAME", TextBox1.Text);
child.SetAttribute("CITY", TextBox2.Text);
child.SetAttribute("NUMBER", TextBox3.Text);
doc.DocumentElement.AppendChild(child);
doc.Save(xmlFilePath);
         
}
else
{
doc.Load(xmlFilePath);
XmlElement child = doc.CreateElement(element);
child.SetAttribute("NAME", TextBox1.Text);
child.SetAttribute("CITY", TextBox2.Text);
child.SetAttribute("NUMBER", TextBox3.Text);
doc.DocumentElement.AppendChild(child);
doc.Save(xmlFilePath);
}
            }



USE OF GRID VIEW IN ASP.NET (GRID VIEW EVENTS



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
        GridDataBind();
     }

    public void GridDataBind()
     {


    String constr = ConfigurationSettings.AppSettings["constr"];
    SqlConnection con = new SqlConnection(constr);
    SqlCommand com = new SqlCommand("select * from Table_Name", con);

    con.Open();
    SqlDataReader dr = com.ExecuteReader();
    GridView1.DataSource = dr;
    GridView1.DataBind();
    con.Close();
      }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
     {
    GridViewRow row = GridView1.Rows[e.RowIndex];
    DataKey key;
     if (row != null)
      {
     key = GridView1.DataKeys[row.RowIndex];
     TextBox txtname = (TextBox)row.FindControl("txtname");
     TextBox txtpass = (TextBox)row.FindControl("txtpass");
     string strname = txtname.Text;
     string strpass = txtpass.Text;
     string constr = ConfigurationSettings.AppSettings["constr"];
     SqlConnection conn = new SqlConnection(constr);
     SqlCommand com = new SqlCommand("update Table_Name set               
     name='"+strname+"', pass='"+strpass+"' where ID='"+key.Value+"'", conn);
     conn.Open();
     com.ExecuteNonQuery();
     conn.Close();
     GridView1.EditIndex = -1;
     GridDataBind();
      }
      }
     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
     {
     GridView1.EditIndex = e.NewEditIndex;
     GridDataBind();
      }
   protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgse)
     {
     GridView1.EditIndex = -1;
     GridDataBind();
      }
      protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
      {
      GridViewRow row = GridView1.Rows[e.RowIndex];
      DataKey key ;
      key = GridView1.DataKeys[row.RowIndex];
      if (row != null)
      {
      String constr = ConfigurationSettings.AppSettings["constr"];
      SqlConnection conn = new SqlConnection(constr);
      SqlCommand com = new SqlCommand();
      conn.Open();
      com.CommandText = "delete from Table_Name where ID='" + key.Value + "'";
      com.Connection = conn;
      com.ExecuteNonQuery();
      conn.Close();
      }
      GridDataBind();
      }
      }
Table_Name, Append Setting, Execute Query, Newedit Index, Web.Security, Grid View


CONTROLS USING ASP.NET IN CONTROLS PARAMETERS IN SQL DATA SOURCE




<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"
            AutoGenerateRows="False" DataKeyNames="id" DataSourceID="SqlDataSource1"
            EnableModelValidation="True" DefaultMode="Edit">
            <Fields>
              <asp:TemplateField HeaderText="Fname" SortExpression="Fname">
                <EditItemTemplate>
                  <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Fname") %>'></asp:TextBox>
             </EditItemTemplate>
               <ItemTemplate>
                 <asp:Label ID="Label1" runat="server" Text='<%# Bind("Fname") %>'></asp:Label>
              </ItemTemplate>
                 </asp:TemplateField>
                   <asp:TemplateField HeaderText="Lname" SortExpression="Lname">
                     <EditItemTemplate>
                      <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Lname") %>'></asp:TextBox>
               </EditItemTemplate>
                  <ItemTemplate>
                     <asp:Label ID="Label2" runat="server" Text='<%# Bind("Lname") %>'></asp:Label>
               </ItemTemplate>
                 </asp:TemplateField>
                   <asp:TemplateField HeaderText="Username" SortExpression="Username">
                     <EditItemTemplate>
                       <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Username") %>'></asp:TextBox>
                </EditItemTemplate>
                   <ItemTemplate>
                     <asp:Label ID="Label3" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                 </ItemTemplate>
                   </asp:TemplateField>
                     <asp:TemplateField HeaderText="Password" SortExpression="Password">
                       <EditItemTemplate>
                         <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
                 </EditItemTemplate>
                    <ItemTemplate>
                      <asp:Label ID="Label4" runat="server" Text='<%# Bind("Password") %>'></asp:Label>
                </ItemTemplate>
                   </asp:TemplateField>
                     <asp:TemplateField HeaderText="Email" SortExpression="Email">
                       <EditItemTemplate>
                         <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
                  </EditItemTemplate>
                     <ItemTemplate>
                       <asp:Label ID="Label5" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
                  </ItemTemplate>
                     </asp:TemplateField>
                       <asp:CommandField ShowEditButton="True" />
                         </Fields>
                           </asp:DetailsView>
                             <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
                  SelectCommand="SELECT * FROM [Table_Login]"
                  UpdateCommand="UPDATE [Table_Login] SET [Fname] = @Fname, [Lname] = @Lname, [Username] = @Username, [Password] = @Password, [Email] = @Email WHERE [id] = @id">
            <UpdateParameters>
                <asp:ControlParameter Name="Fname" ControlID="DetailsView1$TextBox1" Type="String" />
                <asp:ControlParameter Name="Lname" ControlID="DetailsView1$TextBox2" Type="String" />
                <asp:ControlParameter Name="Username" ControlID="DetailsView1$TextBox3" Type="String" />
                <asp:ControlParameter Name="Password" ControlID="DetailsView1$TextBox4" Type="String" />
                <asp:ControlParameter Name="Email" ControlID="DetailsView1$TextBox5" Type="String" />
                </UpdateParameters>
                   </asp:SqlDataSource>


HOW TO CREATE COOKIES IN ASP.NET



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
public partial class _Default : System.Web.UI.Page
    {
    protected void bttLogin_Click(object sender, EventArgs e)
    {
    HttpCookie myCookie = new HttpCookie("yourInfo");
    myCookie.Values["yourName"] = txtUsername.Text;
    myCookie.Values["yourID"] = txtPassword.Text;
    Response.Cookies.Add(myCookie);
     }
    protected void bttGet_Click(object sender, EventArgs e)
    {
    HttpCookie getCookie;
    getCookie = Request.Cookies["yourInfo"];
    if (getCookie.HasKeys)
    {
    NameValueCollection valueCookie = new NameValueCollection(getCookie.Values);
    foreach (string k in valueCookie.AllKeys)
    {
    Response.Write(k + " : ");
    Response.Write(getCookie.Values[k] + "<br />");
     }
     }  
    else
     { Response.Write(getCookie.Value); }
    lblSum.Text = "Welcome .. " + getCookie.Values["yourName"];
     }
     }



SHOW AND STORE IMAGE IN ASP.NET



Showing Image From Data Base Using Handler

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class Handler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
string query = "Select Image from  Table_Image WHERE Name = '" + context.Request.QueryString["Name"].ToString() +"'" ;
SqlConnection connection = new SqlConnection("Type your Connection String Here");
SqlCommand command = new SqlCommand(query, connection );
connection .Open();
byte[] img = (byte[])command.ExecuteScalar();
context.Response.BinaryWrite(img);      
connection.Close();
}
public bool IsReusable
{
get
{
return false;
}
}
}
After making a handler as above. Set Image URL like this ::
Image1.ImageUrl = "Handler.ashx?Name=" + TextBox1.Text;

How To Store Image In Database In Asp.Net

byte[] imgbyte = FileUpload1.FileBytes;
SqlConnection connection = new SqlConnection("Type Connection String Here");
SqlCommand command = new SqlCommand("INSERT INTO Table_Image(Name,Image) VALUES (@name,@image)", connection );
connection .Open();
command .Parameters.AddWithValue("@name", TextBox1.Text);
SqlParameter img = new SqlParameter("@image", SqlDbType.Image, imgbyte.Length);
img.Value = imgbyte;
command .Parameters.Add(img);
command .ExecuteNonQuery();
connection .Close();






Wednesday, 8 February 2012

HOW TO SEND A MAIL IN ASP.NET



public partial class mailer : System.Web.UI.Page
{
MailMessage mailmsg;
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["admin"] == null)
{
Response.Redirect("index.aspx");
}
//if (Request.QueryString["id"] != null)
//{
//    txtToAddress.Text = Request.QueryString["id"];
//}
if(!IsPostBack)
{
String user = Session["admin"].ToString();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["name"].ConnectionString);
con.Open();
cmd = new SqlCommand("select email from registration where username='" + user + "'",con );
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
txtFromAddress.Text = dr.GetString(0);
}
dr.Close();
}
}
protected void btnSendmail_Click(object sender, ImageClickEventArgs e)
{
try
{
String to = txtToAddress.Text;
String from = txtFromAddress.Text;
String cc = txtCCAddress.Text;
String bcc = txtBCC.Text;
String subject = txtSubject.Text;
String body = txtMessage.Text;
mailmsg = new MailMessage();
mailmsg.From =new MailAddress( from );
mailmsg.To.Add ( new MailAddress(to));
if ((cc != null) && (cc != string.Empty))
{
mailmsg.CC.Add(new MailAddress(cc));
 
if ((bcc != null) && (bcc != string.Empty))
{
mailmsg.Bcc.Add(new MailAddress(bcc));
}
mailmsg.Subject = subject;
mailmsg.Body = body;
if (fileAttachment.HasFile)
{
mailmsg.Attachments.Add(new Attachment(fileAttachment.PostedFile.FileName));
}
// Set the format of the mail message body as HTML
mailmsg.IsBodyHtml = true;
// Set the priority of the mail message to normal
mailmsg.Priority = MailPriority.Normal;
SmtpClient smtpclient = new SmtpClient();
smtpclient.Host = ConfigurationManager.AppSettings["hostname"];
smtpclient.Send(mailmsg);
}
catch (Exception ex)
{
lblmsg.Text = "Your mail has been sent..";
}
}
}

MICROSOFT SQL SERVER AS DATABASE USE IN ASP.NET


Establishment Of Connection To Sql Server :


SqlConnection connection = new SqlConnection();

SqlCommand command = new SqlCommand();

if (connection .State == ConnectionState.Closed)
{
connection .ConnectionString = "CONNECTION STRING HERE";

connection .Open();
}
command .CommandText = "SQL QUERY HERE";

command .Connection = connection ;

//PERFORM THE OPERATIONS HERE ACCORDINGLY

connection .Close();

USING SqlDataReader :

SqlConnection connection = new SqlConnection();

SqlCommand command = new SqlCommand();

if (connection .State == ConnectionState.Closed)
{
connection .ConnectionString = "CONNECTION STRING HERE";

connection .Open();
}
command .CommandText = "SQL QUERY HERE";

command .Connection = connection ;

SqlDataReader datareader = command .ExecuteReader();

connection .Close();

USING DataAdapter :

DataSet obj = new DataSet();

SqlConnection connection = new SqlConnection();

SqlCommand command = new SqlCommand();

SqlDataAdapter adapter = new SqlDataAdapter();

if (connection .State == ConnectionState.Closed)
{
connection .ConnectionString = "CONNECTION STRING HERE";
connection .Open();
}
command .CommandText = "SQL QUERY HERE";

command .Connection = connection ;

adapter .SelectCommand = command ;

adapter .Fill(obj);

connection .Close();

 

USE OF WEB SERVER CONTROL IN ASP.NET


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
{
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
ListBox1.Items.Add(CheckBox1.Text);
}
else
}
ListBox1.Items.Remove(ListBox1.Items.FindByText(CheckBox1.Text));
}
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox2.Checked == true)
{
ListBox1.Items.Add(CheckBox2.Text);
}
else
{
ListBox1.Items.Remove(ListBox1.Items.FindByText(CheckBox2.Text));
}
}
protected void CheckBox3_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox3.Checked == true)
{
ListBox1.Items.Add(CheckBox3.Text);
}
else
{
ListBox1.Items.Remove(ListBox1.Items.FindByText(CheckBox3.Text));
}
}
protected void CheckBox4_CheckedChanged(object sender, EventArgs e)
{
 if (CheckBox4.Checked == true)
{
 ListBox1.Items.Add(CheckBox4.Text);
            }
 else
            {
 ListBox1.Items.Remove(ListBox1.Items.FindByText(CheckBox4.Text));
            }
            }
 protected void CheckBox5_CheckedChanged(object sender, EventArgs e)
            {
 if (CheckBox5.Checked == true)
            {
 ListBox1.Items.Add(CheckBox5.Text);
            }
 else
            {
 ListBox1.Items.Remove(ListBox1.Items.FindByText(CheckBox5.Text));
            }
            }
            }


INTRODUCTION START OF ASP.NET


Microsoft's previous server side scripting technology asp (active server pages) is now often called classic asp.
Active Server Pages .NET (ASP.NET) is the infrastructure built inside the .NET  Framework for running Web applications. As a programmer, you interact with it using appropriate types in the class libraries to write programs and design webforms.
 When a client request a page,t the ASP.NET service runs (inside CLR), executes your code and creates a final HTML page to send to the client. 
Asp 3.0 was the last version of classic asp.
Asp.net is the next generation asp, but it's not an upgraded version of asp.
ASP.NET Is An Entirely New Technology For Server-Side Scripting. It Was Written From The Ground Up And Is Not Backward Compatible With Classic ASP.
You Can Read More About The Differences Between ASP And ASP.NET In The Next Chapter Of This Tutorial.
ASP.NET Is The Major Part Of The Microsoft's .NET Framework.


WHAT IS ASP.NET?

Asp.net is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an internet server.
  • Asp.net is a microsoft technology
  • Asp stands for active server pages
  • Asp.net is a program that runs inside iis
  • Iis (internet information services) is microsoft's internet server
  • Iis comes as a free component with windows servers
  • Iis is also a part of windows 2000 and xp professional

WHAT IS AN ASP.NET FILE?

  • An asp.net file is just the same as an html file
  • An asp.net file can contain html, xml, and scripts
  • Scripts in an asp.net file are executed on the server
  • An asp.net file has the file extension ".aspx"

HOW DOES ASP.NET WORK?

  • When a browser requests an HTML file, the server returns the file
  • When a browser requests an ASP.NET file, IIS passes the request to the ASP.NET engine on the server
  • The ASP.NET engine reads the file, line by line, and executes the scripts in the file
  • Finally, the ASP.NET file is returned to the browser as plain HTML

THE MICROSOFT .NET FRAMEWORK

The .NET Framework is the infrastructure for the Microsoft .NET platform.
The .NET Framework is an environment for building, deploying, and running Web applications and Web Services.
Microsoft's first server technology ASP (Active Server Pages), was a powerful and flexible "programming language". But it was too code oriented. It was not an application framework and not an enterprise development tool.
The Microsoft .NET Framework was developed to solve this problem.
.NET Frameworks keywords:
  • Easier and quicker programming
  • Reduced amount of code
  • Declarative programming model
  • Richer server control hierarchy with events
  • Larger class library
  • Better support for development tools
The .NET Framework consists of 3 main parts:
Programming languages:
  • C# (Pronounced C sharp)
  • Visual Basic (VB .NET)
  • J# (Pronounced J sharp)
Server technologies and client technologies:
  • ASP .NET (Active Server Pages)
  • Windows Forms (Windows desktop solutions)
  • Compact Framework (PDA / Mobile solutions)
Development environments:
  • Visual Studio .NET (VS .NET)
  • Visual Web Developer
ASP.NET has better language support, a large set of new controls, XML-based components, and better user authentication.
ASP.NET provides increased performance by running compiled code.
ASP.NET code is not fully backward compatible with ASP.

NEW IN ASP.NET

  • Better language support
  • Programmable controls
  • Event-driven programming
  • XML-based components
  • User authentication, with accounts and roles
  • Higher scalability
  • Increased performance - Compiled code
  • Easier configuration and deployment
  • Not fully ASP compatible

LANGUAGE SUPPORT

ASP.NET uses ADO.NET.
ASP.NET supports full Visual Basic, not vbscript.
ASP.NET supports C# (C sharp) and C++.
ASP.NET supports jscript.

ASP.NET CONTROLS

ASP.NET contains a large set of HTML controls. Almost all HTML elements on a page can be defined as ASP.NET control objects that can be controlled by scripts.
ASP.NET also contains a new set of object-oriented input controls, like programmable list-boxes and validation controls.
A new data grid control supports sorting, data paging, and everything you can expect from a dataset control.

EVENT AWARE CONTROLS

All ASP.NET objects on a Web page can expose events that can be processed by ASP.NET code.
Load, Click and Change events handled by code makes coding much simpler and much better organized.

ASP.NET COMPONENTS

ASP.NET components are heavily based on XML. Like the new AD Rotator, that uses XML to store advertisement information and configuration.

USER AUTHENTICATION

ASP.NET supports form-based user authentication, cookie management, and automatic redirecting of unauthorized logins.

USER ACCOUNTS AND ROLES

ASP.NET allows user accounts and roles, to give each user (with a given role) access to different server code and executables.

HIGH SCALABILITY

Much has been done with ASP.NET to provide greater scalability.
Server-to-server communication has been greatly enhanced, making it possible to scale an application over several servers. One example of this is the ability to run XML parsers, XSL transformations and even resource hungry session objects on other servers.

COMPILED CODE

The first request for an ASP.NET page on the server will compile the ASP.NET code and keep a cached copy in memory. The result of this is greatly increased performance.

EASY CONFIGURATION

Configuration of ASP.NET is done with plain text files.
Configuration files can be uploaded or changed while the application is running. No need to restart the server. No more metabase or registry puzzle.

EASY DEPLOYMENT

No more server-restart to deploy or replace compiled code. ASP.NET simply redirects all new requests to the new code.

COMPATIBILITY

ASP.NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need some changes to run under ASP.NET.
To overcome this problem, ASP.NET uses a new file extension ".aspx". This will make ASP.NET applications able to run side by side with standard ASP applications on the same server.
Compilers that are compliant with the CLR generate code that is targeted for the runtime, as opposed to specific CPU. This code, known variously as Microsoft Intermediate Language(MSIL), is an assembler-type language  that is packaged in EXE or DLL file. These are not standard executable files and require that the runtime’s Just-in-Time compiler convert IL in them to machine specific code when an application actually runs. Because the common language runtime is responsible for managing this IL, the code is known as Managed code.