Friday 7 December 2012

Get & Set CheckBoxList Selected Item in ASP.net

Use the below Query to Get & Set CheckBoxList Selected Item Using ASP.net

In aspx Page create a CheckBoxList  Example query given below



<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatColumns="3">
<asp:ListItem>Mani</asp:ListItem>
<asp:ListItem>Raja</asp:ListItem>
<asp:ListItem>Durai</asp:ListItem>
</asp:CheckBoxList>

Get CheckboxList Selected Item

strCheckedText = "";
  foreach (ListItem LItem in CheckBoxList1.Items)
   {
    string stBool = LItem.Selected.ToString();
    if (stBool == "True")
      {
       if (strCheckedText == "")
       strCheckedText = LItem.Text;
       else
       strCheckedText = strCheckedText + "|" + LItem.Text;

       }
   }


Clear CheckBoxList Selection

 CheckBoxList1.ClearSelection();

Set CheckboxList Selected Item

string[] ss = strCheckedText.Split('|');
 int iq = 0;
 foreach (ListItem LItem in CheckBoxList1.Items)
 {
  for (int i = 0; i < 3; i++)
   {
    if (ss.Length != iq)
     {
      if (LItem.Text == ss[iq])
        {
          LItem.Selected = true;
          iq++;
         }
       }
      }    
    }

 

Create ThumbnailImage Using ASP.net


This article will help you to learn make thumbnail image through the system.  To upload images to the server, we need a File Upload control and a button control. Asp.Net simplifies the process of uploading images to the server with the FileUpload control. To start with, place a FileUpload control and a button control on your webpage like as follows:




<div>
<asp:Label ID="labelMessage" runat="server" Text="Browse Image:" ForeColor="navy"Width="220"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Upload" runat="server" Text="Upload" OnClick="Upload_Click" />
<asp:Button ID="Button1" runat="server" Text="button" onclick="Button1_Click" />
</div>

<div>
<asp:Label ID="label1" runat="server" Text="Normal Image (Full size): " ForeColor="navy" Width="220"></asp:Label>
<asp:Image ID="NormalImage" runat="server" />
</div>

<div>
<asp:Label ID="label2" runat="server" Text="Thumbnail Small Image (50x50)px: " ForeColor="navy" Width="220"></asp:Label>
<asp:Image ID="ThumbnailImageS" runat="server" />
</div>

<div>
<asp:Label ID="label3" runat="server" Text="Thumbnail Large Image (100x100)px: " ForeColor="navy" Width="220"></asp:Label>
<asp:Image ID="ThumbnailImageM" runat="server" />
</div>


In this article I am using the GetThumbnailImage method of the Image class. This method returns the thumbnail image for the given original image. The syntax for this method is-

public Image GetThumbnailImage(int thumbWidth, int thumbHeight, Image.GetThumbnailImageAbort callback, IntPtr callbackData);

Coading




protected void Upload_Click(object sender, EventArgs e)
    {
FileUpload1.SaveAs(MapPath("~/ImageRaja/" + FileUpload1.FileName));
System.Drawing.Image img1 = System.Drawing.Image.FromFile(MapPath("~/imgRaja/") + FileUpload1.FileName);

System.Drawing.Image bmp1 = img1.GetThumbnailImage(50, 50, null, IntPtr.Zero);
bmp1.Save(MapPath("~/thumbnailRaja/S/") + FileUpload1.FileName);
System.Drawing.Image bmp2 = img1.GetThumbnailImage(100, 100, null, IntPtr.Zero);
bmp2.Save(MapPath("~/thumbnailRaja/L/") + FileUpload1.FileName);
NormalImage.ImageUrl = "~/ ImageRaja /" + FileUpload1.FileName;
ThumbnailImageS.ImageUrl = "~/ thumbnailRaja /S/" + FileUpload1.FileName;
ThumbnailImageM.ImageUrl = "~/ thumbnailRaja /L/" + FileUpload1.FileName;
      }
 

Tuesday 27 November 2012

3-Tier Architecture in ASP.NET with C#

Introduction

3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL) or Business Logic Layer and Data Access Layer (DAL).

Presentation Layer (UI)
Presentation layer cotains pages like .aspx or windows form where data is presented to the user or input is taken from the user.

Business Access Layer (BAL) or Business Logic Layer
BAL contains business logic, validations or calculations related with the data, if needed. I will call it Business Access Layer in my demo.

Data Access Layer (DAL)
DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc). For this demo application, I have taken a very simple example. I am assuming that I have to play with record of persons (FirstName, LastName, Age) and I will refer only these data through out this article.

Friday 23 November 2012

Set and Get Common Constant Value

Set A Value to Common Constant

Create a string array and set the value of the stringarray.
 same as given below

string[] arrRaja = new string[4];
arrRaja [0] = "Parts";
arrRaja [1] = "I";
arrRaja [2] = "P";
arrRaja [3] = "PS";
              
                                          OR

 string[][] arrRaja =  {
               new[]{ "Parts " },
               new[]{ "r" },              
               new[]{ "s" },               
              new[]{ "f" },          
      };

Then give the below query in common constant

 public string getarrRaja (int iIndex)
        {
            return arrRaja [iIndex];
        }

Get The Common Constant Value To Code Behind

string strRaja=m_objCommonConstant.getarrRaja (0);
string strRaja1=m_objCommonConstant.getarrRaja (1);
string strRaja2=m_objCommonConstant.getarrRaja (2);
string strRaja3=m_objCommonConstant.getarrRaja (3);

Get Screen Resolution In C#


 Get Page Resolution
Import
using System.Windows.Forms;
Namespace In your Page

Type The Query In your page ....
int height = Screen.PrimaryScreen.Bounds.Height;
int width = Screen.PrimaryScreen.Bounds.Width;

Set Resolution In Your Page In CodeBehind

Type the below query
In Aspx page


<body id="body" runat="server">
</body>
  
In Aspx.cs page


int screenWidth= Screen.PrimaryScreen.Bounds.Width;
body.Style.Add("width", Convert.ToString(screenWidth));

Tuesday 20 November 2012

Currency (Price) Validation

Give any one of the below query to use Currency (Price) Validation ..

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript">
        function checkDecimals(fieldName, fieldValue) {
            decallowed = 2;
            if (isNaN(fieldValue) || fieldValue == "") {
                fieldName.select();
                fieldName.focus();
            }
            else {
                if (fieldValue.indexOf('.') == -1) fieldValue += ".";
                dectext = fieldValue.substring(fieldValue.indexOf('.') + 1, fieldValue.length);

                if (dectext.length > decallowed) {
                  
                    fieldName.select();
                    fieldName.focus();
                }
                else {

                }
            }
        }

    </script>


<input id="txtbox" type="text" name="txt" onkeypress="checkDecimals(this.form.txt, this.form.txt.value)">

                              OR 

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="ariy.validator.js" type="text/javascript"></script>
<script type="text/javascript">
   $(document).ready(function () {
        $('#quantity').ariyValidate({
            type: "price",
            error_message: "Raja"
        });
  });

<input type="text" id="quantity" />

                            OR


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="rev_CashTextBox" runat="server"         
        ValidationExpression="^\$?\-?([1-9]{1}[0-   9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$"        ControlToValidate="TextBox1"ValidationGroup="vld_Edit"
ErrorMessage="*" ForeColor="Red"  Display="Dynamic" ToolTip=""/>
<asp:Button ID="Button1" runat="server" Text="Button" 
   ValidationGroup="vld_Edit" onclick="Button1_Click" />


 

 

Friday 9 November 2012

Comments

Comments will not be executed.
Comments can be added to explain, or to make the code more readable.

HTML comments

HTML  comments start with /* and end with */.

ASP.net Comments

in aspx.cs page comments start with //

in ASPX page  comments start with <%--      and end with    --%>

in Class file comments start with //

CSS Comments

in CSS comments start with /* and end with */

C++ Comments

Single line comment start with //
Multi line comment  start with /* and end with */

JavaScript Comments

Single line comment start with //
Multi line comment  start with /* and end with */

Jquery

Jquery comment start with //

Thursday 8 November 2012

Payplal Integration in ASP.net

Do you want to intergrate PayPal in your shopping cart or web site? Here some source code samples to help you get started.



DataView dvOrderItems = oProducts.GetOrderByID(OrderID);
ID = dvOrderItems[0]["OrderID"].ToString();
string Payment = dvOrderItems[0]["SubTotal"].ToString();
string Orderstatus = dvOrderItems[0]["Shipping"].ToString();
amount = Convert.ToDecimal(Payment).ToString("N2").Replace(',', '.');
shipping = Convert.ToDecimal(Orderstatus).ToString("N2").Replace(',', '.');
 



string serverUrl = (config.Store.SandboxMode?
               "https://www.sandbox.paypal.com/us/cgi-bin/webscr" :
               "https://www.paypal.com/us/cgi-bin/webscr");
           
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(
HttpContext.Current.Request.Url.PathAndQuery, "") +     HttpContext.Current.Request.ApplicationPath;
if (!baseUrl.EndsWith("/"))
    baseUrl += "/";
           
string notifyUrl = HttpUtility.UrlEncode(baseUrl + "PayPal/Notify.aspx");
string returnUrl = HttpUtility.UrlEncode(baseUrl + "PayPal/OrderCompleted.aspx?ID=" + ID);
string cancelUrl = HttpUtility.UrlEncode(baseUrl + "PayPal/OrderCancelled.aspx");
string business = HttpUtility.UrlEncode(config.Store.BusinessEmail);
string itemName = HttpUtility.UrlEncode("Order #" + ID);

StringBuilder url = new StringBuilder();
url.AppendFormat(
               "{0}?cmd=_xclick&upload=1&rm=2&no_shipping=1&no_note=1&currency_code={1}&business={2}&item_number={3}&custom={3}&item_name={4}&amount={5}&shipping={6}&notify_url={7}&return={8}&cancel_return={9}",
               serverUrl,config.Store.CurrencyCode, business, ID, itemName,
               amount, shipping, notifyUrl, returnUrl, cancelUrl);
         
return url.ToString();

then give your messsage or value in 

Notify.aspx


OrderCompleted.aspx 
OrderCancelled.aspx

Thursday 1 November 2012

Editable GridView in Visual Studio 2010

Insert a Xml File in your Project
Then give the below query in xml page



<Employees>
  <Employee>
    <ID>2</ID>
    <name>Durai</name>
    <age>25</age>
    <sex>male</sex>
  </Employee>
  <Employee>
    <ID>3</ID>
    <name>ras</name>
    <age>23</age>
    <sex>female</sex>
  </Employee>
</Employees>

Then create a EmployeeInfo.cs in your Project
And give the below query in  EmployeeInfo.cs Page.



namespace EditableGridView.Class
{
    public class EmployeeInfo
    {
        public EmployeeInfo()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        private Int64 _ID;

        public Int64 ID
        {
            get { return _ID; }
            set { _ID = value; }
        }

        private string _name;

        public string name
        {
            get { return _name; }
            set { _name = value; }
        }

        private Int32 _age;

        public Int32 age
        {
            get { return _age; }
            set { _age = value; }
        }

        private string _sex;

        public string sex
        {
            get { return _sex; }
            set { _sex = value; }
        }
    }
}




Type below query In your aspx Page



<asp:GridView ID="gvwExampleXML" runat="server" AutoGenerateColumns="false" Width="100%"ShowFooter="true"onrowcancelingedit="gvwExampleXML_RowCancelingEdit" DataKeyNames="ID" onrowcommand="gvwExampleXML_RowCommand" onrowdatabound="gvwExampleXML_RowDataBound" onrowdeleting="gvwExampleXML_RowDeleting" onrowediting="gvwExampleXML_RowEditing"
onrowupdating="gvwExampleXML_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate >
<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtName"
ValidationGroup="Update" runat="server" ErrorMessage="Enter Your Name."></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<%#Eval("name") %>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtName1" runat="server" Text='<%#Eval("name") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" ControlToValidate="txtName1"
ValidationGroup="Insert" runat="server" ErrorMessage="Enter Your Name."></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Age">
<EditItemTemplate>
 <asp:TextBox ID="txtAge" runat="server" Text='<%#Eval("age") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" ControlToValidate="txtAge"
 ValidationGroup="Update" runat="server" ErrorMessage="Enter Your Age."></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<%#Eval("age") %>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAge1" runat="server" Text='<%#Eval("age") %>'></asp:TextBox>
asp:RequiredFieldValidator ID="RequiredFieldValidator11" ControlToValidate="txtAge1"ValidationGroup="Insert" runat="server" ErrorMessage="Enter Your Age."></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Gender">
<EditItemTemplate>
<asp:DropDownList ID="ddlSex" runat="server">
<asp:ListItem>male</asp:ListItem>
<asp:ListItem>female</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<%# Eval("sex")%>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlSex1" runat="server">
<asp:ListItem>male</asp:ListItem>
<asp:ListItem>female</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Edit" >
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CausesValidation="True" CommandName="Update"Text="Update" OnClientClick="return confirm('Update?')" ValidationGroup="Update"></asp:LinkButton>
<asp:ValidationSummary ID="vsUpdate" runat="server" ShowMessageBox="true" ShowSummary="false"ValidationGroup="Update" Enabled="true" HeaderText="Validation Summary..." />
<asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel"Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" runat="server" CausesValidation="True" CommandName="Insert"ValidationGroup="Insert" Text="Insert"></asp:LinkButton>
<asp:ValidationSummary ID="vsInsert" runat="server" ShowMessageBox="true" ShowSummary="false"ValidationGroup="Insert" Enabled="true" HeaderText="Validation..." />
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit"Text="Edit"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField  >
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False" CommandName="Delete"Text="Delete" OnClientClick="return confirm('Delete?')"></asp:LinkButton>
</ItemTemplate>
 <HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>

Then Give the below query in aspx.cs Page

Add using EditableGridView.Class; Namespace And give the query



Insert


protected void gvwExampleXML_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            EmployeeInfo einfo = new EmployeeInfo();
            einfo.name = ((TextBox)gvwExampleXML.FooterRow.FindControl("txtName1")).Text;
            einfo.age = Convert.ToInt32(((TextBox)gvwExampleXML.FooterRow.FindControl("txtAge1")).Text);
            einfo.sex = ((DropDownList)gvwExampleXML.FooterRow.FindControl("ddlSex1")).SelectedValue;
            new mainXML().insertEmployeeInfo(einfo);
            gvwExampleXML.EditIndex = -1;
            bindEmployeeGrid();
        }
    }

Then Create a cs(mainXML.cs) file in your project And Give the query



public List<EmployeeInfo> getEmployeeList()
    {
         List<EmployeeInfo> eList = new List<EmployeeInfo>();
            EmployeeInfo objEmp = null;

            DataSet ds = new DataSet();
            ds.ReadXml(xmlConString);
            if (ds.Tables.Count != 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    objEmp = new EmployeeInfo();
                    objEmp.ID = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"]);
                    objEmp.name = Convert.ToString(ds.Tables[0].Rows[i]["name"]);
                    objEmp.age = Convert.ToInt32(ds.Tables[0].Rows[i]["age"]);
                    objEmp.sex = Convert.ToString(ds.Tables[0].Rows[i]["sex"]);
                    eList.Add(objEmp);
                }
            }
            return eList;
    }



public Boolean insertEmployeeInfo(EmployeeInfo eInfo)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(xmlConString);
        DataRow dr = ds.Tables[0].NewRow();
        dr[0] = eInfo.ID;
        dr[1] = eInfo.name;
        dr[2] = eInfo.age;
        dr[3] = eInfo.sex;
        ds.Tables[0].Rows.Add(dr);
        ds.AcceptChanges();
        ds.WriteXml(xmlConString);
        return true;
    }

Edit

in Aspx.Cs Page Give the below query


protected void gvwExampleXML_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvwExampleXML.EditIndex = e.NewEditIndex;
        bindEmployeeGrid();
    }

Update

in Aspx.Cs Page Give the below query

protected void gvwExampleXML_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        EmployeeInfo einfo = new EmployeeInfo();
        einfo.ID = Convert.ToInt64(gvwExampleXML.DataKeys[e.RowIndex].Values[0].ToString());
        einfo.name = ((TextBox)gvwExampleXML.Rows[e.RowIndex].FindControl("txtName")).Text;
        einfo.age =Convert.ToInt32(((TextBox)gvwExampleXML.Rows[e.RowIndex].FindControl("txtAge")).Text);
        einfo.sex = ((DropDownList)gvwExampleXML.Rows[e.RowIndex].FindControl("ddlSex")).SelectedValue;
        new mainXML().updateEmployeeInfo(einfo);
        gvwExampleXML.EditIndex = -1;
        bindEmployeeGrid();
    }
 
in mainXML.cs Give the below query


public Boolean updateEmployeeInfo(EmployeeInfo eInfo)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(xmlConString);
        if (ds.Tables.Count != 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                if (Convert.ToInt32(ds.Tables[0].Rows[i]["ID"]) == eInfo.ID)
                {
                    ds.Tables[0].Rows[i]["name"] = eInfo.name;
                    ds.Tables[0].Rows[i]["age"] = eInfo.age;
                    ds.Tables[0].Rows[i]["sex"] = eInfo.sex;
                    ds.AcceptChanges();
                    ds.WriteXml(xmlConString);
                    break;
                }
            }
        }
        //XML Updated
        return true;
    }

Delete

 in Aspx.Cs Page Give the below query

protected void gvwExampleXML_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(gvwExampleXML.DataKeys[e.RowIndex].Values[0].ToString());
        new mainXML().deleteEmployeeInfo(id);
        bindEmployeeGrid();
    }

 in mainXML.cs Give the below query

public Boolean deleteEmployeeInfo(int id)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(xmlConString);
        if (ds.Tables.Count != 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                if (Convert.ToInt32(ds.Tables[0].Rows[i]["ID"]) == id)
                {
                    ds.Tables[0].Rows[i].Delete();
                    ds.AcceptChanges();
                    ds.WriteXml(xmlConString);
                    break;
                }
            }
        }
        //XML Delete
        return true;
    }

Then Run your Project 
The Output is Display same as given below
 

Thank You