Thursday, January 26, 2012

Working with Custom and User Controls

Bellow is the code for my "Calculator" Control. A user control is simply a container to controls
Calculator.ascx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Calculator : System.Web.UI.UserControl
{
    public event EventHandler MagicNumber;
    public string TitleText { get{return (string)ViewState["TitleText"];} set{ViewState["TitleText"]=value;} }// retains the state of the property while postbacks
    public FontUnit Fontsize { get { return (FontUnit)ViewState["Fontsize"]; } set { ViewState["Fontsize"] = value; } }
    public Calculator()
    {

         TitleText = "My Calculator";
         Fontsize = FontUnit.Small ;// is over ridden every time by the viewState having the value the first load
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        lblLegend.Text = TitleText;
        lblLegend.Font .Size  = Fontsize;
        lblResult.Font.Size = Fontsize;
        txtNum1.Font.Size = Fontsize;       
        txtNum2.Font.Size = Fontsize;
        btnEnter.Font.Size = Fontsize;
    }
  
    protected void btnEnter_Click(object sender, EventArgs e)
    {
        int num1 = int.Parse(txtNum1.Text);
        int num2 = int.Parse(txtNum2.Text);
        int res = num1 + num2;
        if (res == 8 && MagicNumber != null)
            MagicNumber(this, EventArgs.Empty);
        lblResult .Text = res.ToString();
    }

}
Default.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.Drawing;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Session["Theme"] = "~/SkinFile";
       if (!IsPostBack)
        {
        
            myCalc1.Fontsize = FontUnit.Smaller;
        }
        Panel1.Controls.Add(LoadControl("~/Calculator.ascx"));

    }
    protected void OnMagicNumberCalculated(object sender, EventArgs e)
    {
        showMagNum.Text = "Magic Number Calculated";
    }
}


Default.aspx 
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 <%@ Register Src="~/Calculator.ascx" TagName="myCalc" TagPrefix="C" %>


<!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">

<C:myCalc ID="myCalc1"  runat="server" TitleText="Super Calculator!"  OnMagicNumber="OnMagicNumberCalculated" />
<asp:Label ID ="showMagNum" runat="server" EnableViewState ="false" ></asp:Label>
<asp:Panel ID="Panel1" runat="server">
<CC:MyCustomControl runat="server" ID="MyCC" />
</asp:Panel>

</form></body>
</html>
Web.config File
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 <%@ Register Src="~/Calculator.ascx" TagName="myCalc" TagPrefix="C" %>


<!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">

<C:myCalc ID="myCalc1"  runat="server" TitleText="Super Calculator!"  OnMagicNumber="OnMagicNumberCalculated" />
<asp:Label ID ="showMagNum" runat="server" EnableViewState ="false" ></asp:Label>
<asp:Panel ID="Panel1" runat="server">
<CC:MyCustomControl runat="server" ID="MyCC" />
</asp:Panel>

</form></body>
</html>
MyCustomControl.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace NameSpaceSaad
{
    public class MyCustomControl: WebControl
    {
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            writer.Write("<b><h6><marquee>HI!! CHECK MY CALCULATOR I M ADDRESSING YOU FROM MY CUSTOM CONTROL</marquee></h2></b>");
            base.Render(writer);
        }
   
    }
}

LinQ to SQL

Basic DB commands With LINQ to SQL
Markup File:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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">
    <div>
        <asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="lblLocation" runat="server" Text="Location:"></asp:Label>
        &nbsp;<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnShow" runat="server" Text="Show Records"
            onclick="btnShow_Click" />
        <asp:Button ID="btnInsert" runat="server" Text="Add Record"
            onclick="btnInsert_Click" />
        <asp:Button ID="btnUpdate" runat="server" Text="UpdateRecord"
            onclick="btnUpdate_Click" />
        <asp:Button ID="btnDelete" runat="server" Text="Delete Record"
            onclick="btnDelete_Click" /><br />
        <asp:GridView ID="gdShow" runat="server" AutoGenerateColumns="False"
            onselectedindexchanged="gdShow_SelectedIndexChanged">
            <Columns>
                <asp:BoundField DataField="DeptID" HeaderText="Department ID"
                    SortExpression="DeptID" />
                <asp:BoundField DataField="DName" HeaderText="Dept Name"
                    SortExpression="DName" />
                <asp:BoundField DataField="DLocation" HeaderText="Location"
                    SortExpression="DLocation" />
                <asp:TemplateField ShowHeader="False">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
                            CommandName="Select" Text="Select"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
CS code File:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    LinqToSqlDataContext db = new LinqToSqlDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {


    }
    protected void btnShow_Click(object sender, EventArgs e)
    {
        FillGrid();

    }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        try
        {
            tblDepartment dept = new tblDepartment { DName = txtName.Text, DLocation = txtAddress.Text };
            db.tblDepartments.InsertOnSubmit(dept);
            db.SubmitChanges();
            txtName.Text = "";
            txtAddress.Text = "";
            FillGrid();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

      
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            tblDepartment dept = db.tblDepartments.Single(p => p.DName.Equals(txtName.Text) );
            dept.DLocation = txtAddress.Text;

            db.SubmitChanges();
            txtName.Text = "";
            txtAddress.Text = "";
            FillGrid();
        }
        catch(Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            var dept=from p in db.tblDepartments where p.DName ==txtName .Text select p ;
           // tblDepartment dept = db.tblDepartments.First(p => p.DName.StartsWith(txtName.Text) && p.DLocation.StartsWith(txtAddress.Text));
          //  tblDepartment dept = db.tblDepartments.Single(p => p.DName.Equals(gdShow.SelectedRow.Cells[1].Text) && p.DLocation.Equals(gdShow.SelectedRow.Cells[2].Text));
            //tblDepartment dept = gdShow.SelectedRow.Cells [0];
           // db.tblDepartments .DeleteOnSubmit (dept );
           // db.SubmitChanges ();
            foreach (tblDepartment dept2 in dept )
            {
                db.tblDepartments.DeleteOnSubmit(dept2);
            }
            //db.tblDepartments.DeleteOnSubmit(dept);
            db.SubmitChanges();
          
            FillGrid();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

      
    }
    public void FillGrid()
    {
        try
        {
            var Department = db.tblDepartments;
            gdShow.DataSource = Department;
            gdShow.DataBind();
        }
        catch (Exception ex)
        {

        }

    }
    protected void gdShow_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtName.Text = gdShow.SelectedRow.Cells[1].Text .ToString ();
        txtAddress.Text = gdShow.SelectedRow.Cells[2].Text .ToString();
    }
}

Some AJAX Tools

 Ajax Toolkit 3.5....

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit.HTMLEditor"
    TagPrefix="cc1" %>


<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<!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">
    <link href="App_Themes/Theme/StyleSheet.css" rel="stylesheet" type="text/css" />
    <title></title>
   
</head>
<body>
<form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
  
   <br />
    <hr />
    <br />
   <h4> Using AutoComplete</h4>
    <br />
    <asp:TextBox ID="txtAutoComplete" runat="server"></asp:TextBox>
    <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
        TargetControlID ="txtAutoComplete" ServiceMethod="GetCompletionList"
        UseContextKey="True">
    </asp:AutoCompleteExtender>
    <br />
    <hr />
    
   
   
   <br /><h4> Using Update Panel</h4><br />
    <asp:Label ID="lblFirst" runat="server" Text="Label"></asp:Label>
        <asp:Button ID="btnShow" runat="server" onclick="btnShow_Click" Text="Show" />
            <asp:Button ID="btnRun" runat="server"
                onclick="btnRun_Click" Text="Run" />
            <br />
     <br />
       
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate ><asp:Label ID="lblSecond" runat="server" Text="Label"></asp:Label></ContentTemplate>
       
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="btnRun" EventName="Click" />
            </Triggers>
       
        </asp:UpdatePanel>
       
       Using Accordion
     <hr /><asp:Accordion ID="Accordion1" runat="server">
        <Panes >
            <asp:AccordionPane ID="AccordionPane1" runat="server">
            <Header ><a href="" onclick="return false;">Linq</a> </Header>
            <Content >In my humble opinion, Linq is easily the greatest thing .Net
            has come out with in the past few years, and along with it, Linq-to-SQL
            (L2S) was a godsend. Being quick to hop on the L2S bandwagon, I quickly
            became a huge fan of the framework, it is amazing easy and useful. That being as it is
            , I was quite disappointed when I heard that Linq-to-SQL was no longer going to be
            advanced at all. Now, it is surely not dead, it is still very usable and effective
                at what it does, but I like to stay with frameworks that will be actively advanced
                and fbug-fixed. So I decided to make the jump to Linq-to-Entities (L2E), and it was
                suprisingly simple.

This guide should be a good starting point for anyone whether or not they are
familiar with L2S, and a quick 'jumping guide' to L2S developers.
 </Content>
            </asp:AccordionPane>

            <asp:AccordionPane ID="AccordionPane2" runat="server">
            <Header ><a href="" onclick ="return false;">Linq 2</a></Header>
            <Content >
            Make your ADO.NET Entity Data Model (.edmx file)
This is comparable to the .dbml file that you made with L2S.
•    Right click on your App_Code folder and select New Item
•    Select ADO.NET Entity Data Model and name it (I left the default Model.edmx for the example)
•    Choose Generate from database and click Next
•    Choose your database from the dropdown and choose the name to save the ConnectionString as and click Next

</Content>
            </asp:AccordionPane>
        </Panes>
        </asp:Accordion>
        <br />
        <hr />

        <h4>Using Animation Extender</h4>
        <asp:Panel ID="PanelForAnimationExtender" runat="server">
            Make your ADO.NET Entity Data Model (.edmx file)
This is comparable to the .dbml file that you made with L2S.
•    Right click on your App_Code folder and select New Item
•    Select ADO.NET Entity Data Model and name it (I left the default Model.edmx for the example)
•    Choose Generate from database and click Next
•    Choose your database from the dropdown and choose the name to save the ConnectionString as and click Next

        </asp:Panel>
         <asp:AnimationExtender ID="AnimationExtender1" runat="server" TargetControlID ="PanelForAnimationExtender">
        <Animations>
        <OnMouseOver>
        <FadeOut Duration=".5" Fps="20" />
        </OnMouseOver>
        </Animations>
            </asp:AnimationExtender>
            <br />
            <hr/>
            <br />
          <h4>Using Shadow Extender</h4> <br />
    <asp:Panel ID="PanelForShadowExtender" runat="server">
     Make your ADO.NET Entity Data Model (.edmx file)
This is comparable to the .dbml file that you made with L2S.
•    Right click on your App_Code folder and select New Item
•    Select ADO.NET Entity Data Model and name it (I left the default Model.edmx for the example)
•    Choose Generate from database and click Next
•    Choose your database from the dropdown and choose the name to save the ConnectionString as and click Next

    </asp:Panel>
    <asp:Image ID="MyPic" runat ="server" ImageUrl="~/Images/b.png" />
    <asp:DropShadowExtender ID="DropShadowExtender1" runat="server"
     TargetControlID ="PanelForShadowExtender" Opacity =".1"
      Rounded ="true" TrackPosition ="true" Radius="20" >
     </asp:DropShadowExtender>
     <asp:DropShadowExtender ID="DropShadowExtender2" runat="server"
     TargetControlID ="MyPic" Opacity =".1"
      Rounded ="true" TrackPosition ="true" Radius="20" >
     </asp:DropShadowExtender>
     <br />
     <hr/>
     <br />
     <h4>Using Confirm Button Extender</h4>
    <asp:Button ID="btnStndard" runat="server" Text="Button Standard"
        onclick="btnStndard_Click" /><br />
  
    <asp:Button ID="btnAjax" runat="server" Text="Button Ajax" onclick="btnAjax_Click" /><br />
    <asp:Label ID="lblDisplay" runat="server" Text="Label"></asp:Label>
  
    <asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server"
     TargetControlID ="btnAjax" ConfirmText ="Are you Sure?" ConfirmOnFormSubmit ="False">
    </asp:ConfirmButtonExtender>
   <h4>Using Filter Extender</h4>  <br />
    <asp:TextBox ID="txtFiltering" runat="server"></asp:TextBox>
    <asp:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server"
    TargetControlID ="txtFiltering" FilterType="Custom,LowercaseLetters" ValidChars="+-*/()." >
    </asp:FilteredTextBoxExtender>
    <br />
    <hr />
    <br /><h4>Using RoundedCorner Extender</h4>
    <br />
    <asp:Panel ID="RoundedPanel" runat="server" BackColor="BurlyWood">
    Right click on your App_Code folder and select New Item
•    Select ADO.NET Entity Data Model and name it (I left the default Model.edmx for the example)
•    Choose Generate from database and click Next
•    Choose your database from the dropdown and choose the name to save the ConnectionString as and click Next
    </asp:Panel>
    <asp:RoundedCornersExtender ID="RoundedCornersExtender1" runat="server"
    TargetControlID ="RoundedPanel" Color="BurlyWood" Radius ="20"
     Corners ="TopLeft,BottomRight" BorderColor ="Brown">
    </asp:RoundedCornersExtender>
   
   
    <br /><hr /><br /><h4>Using waterMark Extender</h4>
   
    <asp:TextBox ID="txtWM1" runat="server"></asp:TextBox>
    <asp:TextBox ID="txtWM2" runat="server"></asp:TextBox>
    <asp:Label ID="lblWM" runat="server" Text="Watermark"></asp:Label>
    <asp:Button ID="btnWM"        runat="server" Text="Watermark"
        onclick="btnWM_Click" />
    <asp:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server"
     TargetControlID ="txtWM1" WatermarkText ="Enter Your Name">
    </asp:TextBoxWatermarkExtender>
    <asp:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender2" runat="server"
    TargetControlID ="txtWM2" WatermarkText ="Enter Sur Name">
    </asp:TextBoxWatermarkExtender>
     <br /><hr /><br />
    <h4>Using Collapsible Panel Extender</h4>
     <br />
    
      <asp:CollapsiblePanelExtender ID="CollapsiblePanelExtender1" runat="server"
      TargetControlID="PanelContent" ExpandControlID="PanelHeader" CollapseControlID ="PanelHeader"
      Collapsed ="true" ExpandedText ="(Show Detail)" CollapsedText ="(Hide Detai)" SuppressPostBack ="true">
    </asp:CollapsiblePanelExtender>
    <asp:Panel ID="PanelHeader" runat="server" CssClass="CollapsiblePanelHeader">
    LINQ
    </asp:Panel>
    <asp:Panel ID="PanelContent" runat="server" CssClass="CollapsiblePanel">
    In my humble opinion, Linq is easily the greatest thing .Net
    has come out with in the past few years, and along with it, Linq-to-SQL
    (L2S) was a godsend. Being quick to hop on the L2S bandwagon, I quickly
     became a huge fan of the framework, it is amazing easy and useful. That being as it is
      , I was quite disappointed when I heard that Linq-to-SQL was no longer going to be
      advanced at all. Now, it is surely not dead, it is still very usable and effective
      at what it does, but I like to stay with frameworks that will be actively advanced
      and fbug-fixed. So I decided to make the jump to Linq-to-Entities (L2E), and it was
      suprisingly simple.
    </asp:Panel>
     <br />
    <hr />
    <br />
   <h4> Using Editortool</h4>
    <br />

    <cc1:Editor ID="Editor1" runat="server"  />
    <asp:TextBox ID="txtFromEditor" runat="server"></asp:TextBox>
    <asp:Button ID="btnEditorTotextBox" runat="server" Text="To Text Box" onclick="btnEditorTotextBox_Click" />
    <asp:Button ID="btnToEditor" runat="server" Text="To Editor"  onclick="btnToEditor_Click" />
    <asp:Label ID="lblEditor" runat="server" ></asp:Label>



</form></body>
</html>
 
CS File:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnRun_Click(object sender, EventArgs e)
    {

        lblSecond.Text = System.DateTime.Now.ToString();
    }
    protected void btnShow_Click(object sender, EventArgs e)
    {
        lblFirst.Text = System.DateTime.Now.ToString();
    }
    protected void btnStndard_Click(object sender, EventArgs e)
    {
        lblDisplay.Text = System.DateTime.Now.ToString();
    }
    protected void btnAjax_Click(object sender, EventArgs e)
    {
        lblDisplay.Text = System.DateTime.Now.ToString();
    }
    protected void btnWM_Click(object sender, EventArgs e)
    {
        lblWM.Text = txtWM1.Text + " " + txtWM2.Text;
        txtWM1.Text = " ";
        txtWM2.Text = " ";
        txtWM1.Text = TextBoxWatermarkExtender1.WatermarkText;// shows watermark text in textbox
        txtWM2.Text = TextBoxWatermarkExtender2.WatermarkText;

    }
    protected void btnEditorTotextBox_Click(object sender, EventArgs e)
    {
        txtFromEditor.Text   =  Editor1.Content;
    }
    protected void btnToEditor_Click(object sender, EventArgs e)
    {
        Editor1.Content = txtFromEditor.Text;

    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        string[] array ={"apple","orange","tree","world","home","nonsense","ajax","watdouwant",":(" };
        return (from str in array where str.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) select str).Take(count).ToArray();
    }
}