Thursday, November 24, 2011

gridview stuff

   <div>
    <asp:GridView ID="GridView1" runat="server"
              AutoGenerateColumns="False"
              CellPadding="2" ForeColor="#333333"
              DataKeyNames="EMPID"
           OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server"
              AutoPostBack="true"
              OnCheckedChanged="chkSelectAll_CheckedChanged"/>
                                       
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server"
              AutoPostBack="true"
              OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="EMPID" HeaderText="ID"
                SortExpression="ID"/>
<asp:TemplateField HeaderText="EMPName" SortExpression="EMPName">
<ItemTemplate>
<asp:TextBox ID="txtEName" runat="server"
             Text='<%# Bind("EMPNAME") %>' ForeColor="Blue"
             BorderStyle="none" BorderWidth="0px"
             ReadOnly="true" >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Location" SortExpression
="Location">
<ItemTemplate>
<asp:TextBox ID="txtLocation" runat="server"
             Text='<%# Bind("ADDRESS") %>'
             ForeColor="Blue" BorderStyle="none"
             ReadOnly="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SALARY" SortExpression
="SALARY">
<ItemTemplate>
<asp:TextBox ID="txtSAL" runat="server"
             Text='<%# Bind("SALARY") %>'
             ForeColor="Blue" BorderStyle="none"
             ReadOnly="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
    </div>
-----------------------
.cs file
-------------------------
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;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    private string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["DEMO"].ConnectionString;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Show();

        }

    }
    private void Show()
    {
        SqlConnection con = new SqlConnection(GetConnectionString());
        con.Open();
        DataTable dt = new DataTable();

        SqlCommand command = new SqlCommand("SELECT * from [EMPLOYEE]", con);
        SqlDataAdapter ada = new SqlDataAdapter(command);
        ada.Fill(dt);
       GridView1. DataSource = dt;
       GridView1.DataBind();
        con.Close();

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


        CheckBox chkAll =

           (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");

        if (chkAll.Checked == true)
        {

            foreach (GridViewRow gvRow in GridView1.Rows)
            {

                CheckBox chkSel =

                     (CheckBox)gvRow.FindControl("chkSelect");

                chkSel.Checked = true;

                TextBox txtEName = (TextBox)gvRow.FindControl("txtEName");

                TextBox txtAdd = (TextBox)gvRow.FindControl("txtAdd");
                TextBox txtSal = (TextBox)gvRow.FindControl("txtSal");


                //txtEName.ReadOnly = false;

                //txtAdd.ReadOnly = false;
                ////txtSal.ReadOnly = false;

                //txtEName.ForeColor = System.Drawing.Color.Black;

                //txtAdd.ForeColor = System.Drawing.Color.Black;
                //txtSal.ForeColor = System.Drawing.Color.Black;

            }

        }

        else
        {

            foreach (GridViewRow gvRow in GridView1.Rows)
            {

                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");

                chkSel.Checked = false;

                TextBox txtEName = (TextBox)gvRow.FindControl("txtEName");

                TextBox txtAdd = (TextBox)gvRow.FindControl("txtAdd");
                TextBox txtSal = (TextBox)gvRow.FindControl("txtSal");

                //txtEName.ReadOnly = true;

                //txtAdd.ReadOnly = true;
                //txtSal.ReadOnly = true;

                //txtEName.ForeColor = System.Drawing.Color.Blue;

                //txtAdd.ForeColor = System.Drawing.Color.Blue;
                //txtSal.ForeColor = System.Drawing.Color.Blue;
                //Show();
            }

        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox status = ((CheckBox)(row.Cells[0].Controls[1]));

            if (status.Checked == true)
            {

                row.BackColor = System.Drawing.Color.Red;

            }
            else if (status.Checked == false)
            {
                row.BackColor = System.Drawing.Color.White;
            }

        }


    }
    //protected void rowedit(object sender, EventArgs e)
    //{
       
    //}
   

    protected void chkSelect_CheckedChanged(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox status = ((CheckBox)(row.Cells[0].Controls[1]));

            if (status.Checked == true)
            {

                row.BackColor = System.Drawing.Color.Red;

            }
            else if (status.Checked == false)
            {
                row.BackColor = System.Drawing.Color.White;
            }

        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      // Checking if row type
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        // find the textbox control
       TextBox txtSAL = e.Row.FindControl("txtSAL") as TextBox;
        // read the value from the datasoure
        Double Salary= Convert.ToDouble(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Salary")));
  
        if (Salary > 15000.00)
        {
          // get the cell where that textbox contains
             DataControlFieldCell d = txtSAL.Parent as DataControlFieldCell;
  
          // to change the backcolor
          d.BackColor = System.Drawing.Color.Green;
  
          // to change the row color by setting
           
          //e.Row.BackColor = System.Drawing.Color.Blue;
  
          // to change the text color like this
         
            txtSAL.ForeColor = System.Drawing.Color.Chocolate;
         }
      }
     }

}





Wednesday, November 23, 2011

how to increase web application performance.....

1) Set debug=false under compilation as follows:
<compilation default Language="c#" debug="false">
2) Use Server.Transfer instead of Response.Redirect.
3) Always check Page.IsValid when using Validator Controls
4) Use Foreach loop instead of For loop for String Iteration.
5) Use Client-Side Validation. (but not all the time you have to validate even on the server side)
6) Check “Page.IsPostBack”. To avoid repetition code execution.
7) GIF and PNG are similar, but PNG typically produces a lower file size. (True, but some browsers not supporting PNG format)
8) Use the AppOffline.htm when updating binaries
9) Turn off Tracing unless until required. (by default it's off, use on the pages where it's required)
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
10) Precompiled pages and disable AutoEventWireup; setting the AutoEventWireup attribute to false in the Machine.config file. 11) Turn off Session State, if not required.
<sessionstate timeout="20" cookieless="false" mode="Off" stateconnectionstring="tcpip=127.0.0.1:42424" sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=no">
12) Select the Release mode before making the final Build for your application.
This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug
13) Disable ViewState when not required.
EnableViewState="false"
14) Avoid frequent round trips to the Database.
15) Use Caching to improve the performance of your application.
16) Validate all Input received from the Users.
17) Use Finally Method to kill resources. (But not in the case of using)
18) The String and Stringbuilder Magic.
It is nice to use Stringbuilder instead of String when string are Amended. Strings occupy different memory location in every time of amended where stringbuilder use single memory location
19) Never use object value directly; first get object value in local variable and then use. It takes more time then variable reading.
20) Avoid Exceptions: Use If condition (if it is check proper condition)
21) Code optimization:  Avoid using code like x = x +1; it is always better to use x+=1.
22) Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned
23) Before doing a bulky ASP code processing, you can check to make sure Response.IsClientConnected.
24) As always, avoid session variables because each ASP page runs in a different thread and session calls will be serialized one by one. So, this will slow down the application. Instead of session variables you can use the QueryString collection or hidden variables in the form which holds the values.
25) Enabling buffering will improve the performance, like
<% response.buffer=true %>
Then use:
<% response.flush=true %> 
26) Use Repeater control instead of DataGrid , DataList, Because It is efficient, customizable, and programmable.
27) Data listing is more time consume when large data are retrieve from database.
Paging will display only particular data but take load of all data.
Fetch only data that is needed for current page.
28) Avoid Inline JavaScript and CSS
29) Use single css file instead of multiple css file.
Try your best to combine all your CSS based classes into a single .css file as lot of .css files will cause a large amount of requests, regardless of the file sizes.
.css files are normally cached by browsers, so a single and heavy .css file doesn’t cause a long wait on each page request.
Inline .css classes could make HTML heavy, so again: go ahead with a single.css file.
30) Reduce cookie size
31) Compress CSS, JavaScript and Images
Online compressors are available; to compress file please refers following web and Replace your file content with optimize code.
http://iceyboard.no-ip.org/projects/css_compressor for CSS compression
www.xtreeme.com/javascript-optimizer/ . For JS Compression
32 .Use Cache appropriately
i. Page output caching:
<%@ OutputCache Duration="3600" VaryByParam="none" %>
ii. Page fragment caching:
Write a Page output caching code into each User Control
iii. Data caching:
<script language="C#" runat="server">
Protected void Page_Load (Object src, EventArgs e) {
DataView dv = (DataView) Cache. Get ("EmployeesDataView");
If (dv == null) { // wasn't thereSqlConnection conn =
new SqlConnection ("server=localhost;uid=sa;pwd=;database=Test");
SqlDataAdapter da =new SqlDataAdapter ("select * from Employees", conn);
Dataset ds = new DataSet();da.Fill(ds, "Employees");
dv = ds.Tables["Employees"].DefaultView;
Cache.Insert ("EmployeesDataView", dv);conn.Close();}
Else
Response.Write ("<h2>Loaded employees from data cache! </h2>");
lb1.DataSource = dv;
lb1.DataTextField = "Name";
lb1.DataValueField = "Age";
DataBind () ;}
</script>
33) Use server side compression software such as Port80s http://www.port80software.com/products/httpzip/ 
34) Usage of "using" and I don't know why it's not yet published.
35) Don't make the member variables public or proteted, try to keep private and use public/protected as properties.
36) Use strString=string.Empty instead of strString="" . [And perhaps instead of strString=null also (?)]
37) Make your page files as light as possible. That is try to avoid unnecessary markups, e.g. use div elements instead of tables.
38) Write static messages in div and make it visible when necessary. This is faster than letting server set Text property of your label or div.
39) Retrieve data from database at once, if possible. Don't add up to database trip as far as possible. For this, combine the datafields from different tables and select them.
40) Use short ID name for WebControl.

MS SQL SERVER Stuff

TBL_Demo1

id  name       salary
1   Avik       23000
2   jitesh     32000
3   Neeru      25000
4   anurag     50000
5   paras      21010
6   avik       23000
7   Neeru      25000



Q.1 write a query for following output

id  name       repetedno
1   Avik       2
4   anurag     1
2   jitesh     1
3   Neeru      2
5   paras      1


Query :
SELECT id,name,count(name) as repetedno from TBL_Demo1 group by name

2.


Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego


SELECT CONCAT(region_name,store_name) FROM Geography
WHERE store_name = 'Boston';

Result:
'EastBoston'.



Sunday, November 20, 2011

javaScript Stuff

  
Step 1.
 <script type="text/javascript">
  function SwitchMenu(obj){
    if(document.getElementById)
{
    var el = document.getElementById(obj);
    var ar = document.getElementById("masterdiv").getElementsByTagName("span");
        if(el.style.display != "block"){
            for (var i=0; i<ar.length; i++){
                if (ar[i].className=="submenu")
                ar[i].style.display = "none";
            }
            el.style.display = "block";
        }else{
            el.style.display = "none";
        }
    }
}
</script>

------------------------------------
Step2.
   <div class="Demo" onclick="SwitchMenu('sub1')">
                              <img src="tidf.gif" width="12" height="19" border="1" />
                              </div>

--------------------------------
Step3.
<div id="masterdiv">
    <span class="submenu" id="sub1">

                          <table width="775" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                  

                                </tr>
                              </table>
                              </span>
                          </div>

Monday, November 14, 2011

SMTP mail via ASP.net

  private bool SendMail(string mailto, string username, string pasword)
    {
        bool chkstatus = false;
        try
        {
            string verifyurl;
            verifyurl = "http://www.demo.com/demos1/SignIn.aspx";
            string boardurl = "http://Shera.com";

            MailMessage mailmsg = new MailMessage();
            mailmsg.From =  new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["FromAdminAddress"].ToString());
            mailmsg.To.Add(mailto);

            mailmsg.Subject = "Account activation mail: " + ' ' + " " + '"' + "Demo....." + '"' + "";

            string msgBody = "Hi,<BR><BR>";
            msgBody += "Welcome to my Demo..... <BR><BR>";
            msgBody += "Please keep this e-mail for your records. Your account information is as follows:<BR><BR>";
            msgBody += "--------------------------------------------------------";
            msgBody += "<table  border='0'>      " +
                          "  <tr>                           " +
                          "  <td>                           " +
                          "      Username:</td>             " +
                          "  <td align='left'>      " +
                          "     " + username + "                " +
                          "  </td>                          " +
                          " </tr>                           " +
                          "<tr>                             " +
                          " <td>                            " +
                          "      Board URL:</td>         " +
                          "   <td  align='left'>     " +
                          "  <A HREF=" + pasword + " >" + pasword + "</A>  " +
                          "        </td>                    " +
                          " </tr>                           " +
                          "<tr>                             " +
                          " <td>                            " +
                          "      Board URL:</td>         " +
                          "   <td  align='left'>     " +
                          "  <A HREF=" + boardurl + " >" + boardurl + "</A>  " +
                          "        </td>                    " +
                          " </tr>                           " +
                          "</table>                         ";
            msgBody += "--------------------------------------------------------<BR>";
            msgBody += "Please visit the following link in order to activate your account:<BR><BR>";
            msgBody += "<p><a href=" + verifyurl + " >" + verifyurl + "</a></p>";
            msgBody += "<BR>Thank you for registering.";
            msgBody += "<BR><BR>The Demo..... Team";
            msgBody += "<BR>-------------------------------";
            mailmsg.Body = msgBody;
            mailmsg.IsBodyHtml = true;


            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = ConfigurationManager.AppSettings["SmtpHost"].ToString();
            smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"].ToString());
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["UserName"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
            smtpClient.EnableSsl = false;

            smtpClient.Send(mailmsg);

            mailmsg.Dispose();
            chkstatus = true;

        }

        catch (Exception ex)
        {
           
            chkstatus = false;
        }

        return chkstatus;
    }

---------------------------
web.config
<add key="FromAdminAddress" value="shera@vedangsoftware.com"/>
    <add key="SmtpHost" value="60.5.523.212"/>
    <add key="SmtpPort" value="15"/>
    <add key="UserName" value="Shera@demos.com"/>
    <add key="Password" value="123456"/>
    




Sunday, November 6, 2011

operation with xml

download XML Fundamental

XMLFILE.xml
.........................
<?xml version="1.0" encoding="utf-8" ?>
<countries>

  <country>
    <text>Norway</text>
    <value>N</value>
  </country>

  <country>
    <text>Sweden</text>
    <value>S</value>
  </country>

  <country>
    <text>France</text>
    <value>F</value>
  </country>

  <country>
    <text>Italy</text>
    <value>I</value>
  </country>

</countries>
--------------------------------
Read data from  xml file
@@@@@@@@@@@@@@@@



 ds.ReadXml(MapPath("XMLFile.xml"));

        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "text";
        DropDownList1.DataValueField = "value";
        DropDownList1.DataBind();

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Write XML
---------------------
  protected void btnUpdate_Click(object sender, EventArgs e)
    {
        ds.ReadXml(MapPath("XMLFile.xml"));
        ds.Tables["country"].Rows[0]["text"] = txtName.Text;
              ds.WriteXml(MapPath("XMLFile.xml"));
             ds.Clear();
        bindD();

    }


 private void bindD()
    {
        ds.ReadXml(MapPath("XMLFile.xml"));
        //  Label1.Text=  ds.Tables[0].Rows[0]["text"].ToString();
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "text";
        DropDownList1.DataValueField = "value";
        DropDownList1.DataBind();
    }

Add A New Record..
--------------------


protected void btnAdd_Click(object sender, EventArgs e)
    {
        ds.ReadXml(MapPath("XMLFile.xml"));
        DataTable dt = null;
        DataRow dr = null;
        dt = ds.Tables[0];
        dr = dt.NewRow();
        dr["text"] = txtName.Text;
        dt.Rows.Add(dr);
       
       
        ds.WriteXml(Server.MapPath("XMLFile.xml"));
        // Save it to a new file
   

       
        ds.Clear();
        bindD();
    }

DELETE OPERATION
-----------------------


 protected void btnDelete_Click(object sender, EventArgs e)
    {
        ds.ReadXml(MapPath("XMLFile.xml"));
        DataRow dr1 = ds.Tables[0].Rows[0];
        dr1.Delete();
        ds.WriteXml(Server.MapPath("XMLFile.xml"));
        ds.Clear();
        bindD();
    }