Wednesday, 21 December 2011

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();
    }

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();
    }

File Handling in ASP.NET : Insert into 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++;
        }

    }

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>

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);
            }
        }
       
    }

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);
        }
       
    }

Tuesday, 20 December 2011

Ajax AutoCompleteExtender 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"
      ShowOnlyCurrentWordInCompletionListItem="True">
</asp:AutoCompleteExtender>

Using Service File Method : (.asmx)


    [WebMethod]
    public string[] GetCompletionList(string prefixText)
    {
       
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["mystring"].ConnectionString);
        SqlCommand com = new SqlCommand("SELECT Username FROM Table_Login WHERE Username LIKE '" + prefixText + "%'", conn);
        com.CommandType = CommandType.Text;
        conn.Open();
        SqlDataReader reader = com.ExecuteReader();


        List<string> strarr = new List<string>();


        while (reader.Read())
        {
            strarr.Add(reader.GetString(0));
        }


        conn.Close();
        return strarr.ToArray();

    }


Using Handler : (.ashx)



public class AutocompleteData : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        string firstname = context.Request.QueryString["q"];
        string sql = "select top 10 Username from Table_Login where Username like '" + firstname + "%'";

        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["mystring"].ConnectionString))
        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            connection.Open();
 
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    context.Response.Write(reader.GetString(0) + Environment.NewLine);
                }
            }
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}


Creating 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;
    }

}

Using ASP.NET Controls 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>

Sunday, 11 December 2011

Image Resizing in ASP.NET


public static void Resize(int thumbWidth, string src, string des)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(src);
        int srcWidth = image.Width;
        int srcHeight = image.Height;
        int thumbHeight = Convert.ToInt16(srcHeight * thumbWidth / srcWidth);
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight);

        System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
        gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, System.Drawing.GraphicsUnit.Pixel);

        image.Dispose();
        bmp.Save(des);

        bmp.Dispose();
       
    }

    public static void Resize(string src, string des, int thumbHeight)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(src);
        int srcWidth = image.Width;
        int srcHeight = image.Height;
        int thumbWidth = Convert.ToInt16(srcWidth * thumbHeight / srcHeight);
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight);

        System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
        gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, System.Drawing.GraphicsUnit.Pixel);

        image.Dispose();
        bmp.Save(des);

        bmp.Dispose();
       
    }

Creating CSV file


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();

AutoCompleteExtender 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>

How to use Accordion


<asp:Accordion ID="Accordion1" runat="server" SelectedIndex="0"
            HeaderCssClass="accordionHeader" HeaderSelectedCssClass="accordionHeaderSelected"
            ContentCssClass="accordionContent" FadeTransitions="false" FramesPerSecond="40"
            TransitionDuration="250" AutoSize="None" RequireOpenedPane="false" SuppressHeaderPostbacks="true">
           <Panes>

                <asp:AccordionPane ID="a1" runat="server">
                    <Header>
                        1. Accordion
                    </Header>
                    <Content>
                        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                    </Content>
                </asp:AccordionPane>

                <asp:AccordionPane ID="a2" runat="server">
                    <Header>
                        2. Accordion
                    </Header>
                    <Content>
                        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                    </Content>
                </asp:AccordionPane>

                <asp:AccordionPane ID="a3" runat="server">
                    <Header>
                        3. Accordion
                    </Header>
                    <Content>
                        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                    </Content>
                </asp:AccordionPane>

            </Panes>
        </asp:Accordion>

Wednesday, 7 December 2011

Applying pagination in DataList

DataListPagination.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataListPagination.aspx.cs" Inherits="DataListPagination" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <br />
        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="Default.aspx">Default</asp:HyperLink>
        <br /><br /><br /><br />
    <div>
       
        <asp:DataList ID="DataList1" runat="server" BackColor="White"
            BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
            DataKeyField="id" GridLines="Both"
            RepeatColumns="3" RepeatDirection="Horizontal">
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
            <ItemStyle BackColor="White" ForeColor="#003399" />
            <ItemTemplate>
                id:
                <asp:Label ID="idLabel" runat="server" Text='<%# Eval("id") %>' />
                <br />
                Fname:
                <asp:Label ID="FnameLabel" runat="server" Text='<%# Eval("Fname") %>' />
                <br />
                Lname:
                <asp:Label ID="LnameLabel" runat="server" Text='<%# Eval("Lname") %>' />
                <br />
                Username:
                <asp:Label ID="UsernameLabel" runat="server" Text='<%# Eval("Username") %>' />
                <br />
                Email:
                <asp:Label ID="EmailLabel" runat="server" Text='<%# Eval("Email") %>' />
                <br />
                DOB:
                <asp:Label ID="DOBLabel" runat="server" Text='<%# Eval("DOB") %>' />
                <br />
<br />
            </ItemTemplate>
            <SelectedItemStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        </asp:DataList>
        <asp:LinkButton ID="LinkButton2" runat="server" onclick="LinkButton2_Click">Previous</asp:LinkButton>
        <asp:DataList ID="DataList2" runat="server"
            onitemcommand="DataList2_ItemCommand"
            onitemdatabound="DataList2_ItemDataBound" RepeatColumns="10"
            RepeatDirection="Horizontal">
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("PageIndex") %>' CommandName="lnkbtnPaging" Text='<%# Eval("PageText") %>'></asp:LinkButton>
            </ItemTemplate>
        </asp:DataList>
        <asp:LinkButton ID="LinkButton3" runat="server" onclick="LinkButton3_Click">Next</asp:LinkButton>
        <br />

    </div>
    </form>
</body>


DataListPagination.aspx.cs ::


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class DataListPagination : System.Web.UI.Page
{
    PagedDataSource pds = new PagedDataSource();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    public int CurrentPage
    {

        get
        {
            if (this.ViewState["CurrentPage"] == null)
                return 0;
            else
                return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
        }

        set
        {
            this.ViewState["CurrentPage"] = value;
        }

    }

    private void BindGrid()
    {
        string sql = "SELECT [id], [Fname], [Lname], [Username], [Email], [DOB] FROM [Table_Login]";
        SqlDataAdapter da = new SqlDataAdapter(sql,ConfigurationManager.ConnectionStrings["mystring"].ConnectionString);
        DataTable dt = new DataTable();
        da.Fill(dt);
       
        pds.DataSource = dt.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = 3;
        pds.CurrentPageIndex = CurrentPage;
        LinkButton3.Enabled = !pds.IsLastPage;
        LinkButton2.Enabled = !pds.IsFirstPage;

        DataList1.DataSource = pds;
        DataList1.DataBind();

        doPaging();
    }
    private void doPaging()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");
        for (int i = 0; i < pds.PageCount; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }

        DataList2.DataSource = dt;
        DataList2.DataBind();
    }


    protected void DataList2_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("lnkbtnPaging"))
        {
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
            BindGrid();
        }
    }

    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        BindGrid();
    }

    protected void LinkButton3_Click(object sender, EventArgs e)
    {
        CurrentPage += 1;
        BindGrid();
    }

    //protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    CurrentPage = 0;
    //    BindGrid();
    //}

    protected void DataList2_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("LinkButton1");
        if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkbtnPage.Enabled = false;
            lnkbtnPage.Font.Bold = true;
        }
    }
}

Showing Image from database 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();

Monday, 5 December 2011

Using Microsoft SQL Server as Database 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();




Using Microsoft Office Access as database in asp.net


ESTABLISHING A CONNETION TO THE ACCESS DATABASE :

OleDbConnection connection= new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; " + "Data Source=" + Server.MapPath("PATH OF THE ACCESS DATABASE"));
        OleDbCommand command = new OleDbCommand();

        command .CommandText = "TYPE YOUR SQL QUERY HERE";
        command .CommandType = CommandType.Text;
        command .Connection = connection;

        connection.Open();

        command .ExecuteNonQuery();
     
        connection.Close();

----------------------------------------------------------------------------------------------------------
BINDING THE DATA CONTROL WITH ACCESS DATABASE :


OleDbConnection connection= new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; " + "Data Source=" + Server.MapPath("App_Data/Database1.accdb"));
        OleDbCommand command = new OleDbCommand("Select * FROM Table_Detail", conn);
        connection.Open();

        OleDbDataReader reader = command .ExecuteReader();

        GridView1.DataSource = reader;
        GridView1.DataBind();

        connection.Close();

Saturday, 3 December 2011

Lets start with Introduction of ASP.NET


Microsoft's previous server side scripting technology ASP (Active Server Pages) is now often called classic ASP.
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.