Showing posts with label Asp.net C#. Show all posts
Showing posts with label Asp.net C#. Show all posts

Tuesday, 11 August 2015

Download files

  1.  Create interface for downloads method and path property.  Interface :  An interface contains only the signatures of methods, properties, events or indexers.  A class or struct that implements the interface must implement the members of the interface  that are specified in the interface definition.
     public interface downloads 
     {
         string path { get; set; }
         void download();
     }
    
  2.  create class name general and inherit the interface class in it  Inheritance :   Inheritance allows us to define a class in terms of another class,   which makes it easier to create and maintain an application.  set the property and method for download by using httpresponse download the file from server to local system.
     public class general  : downloads
     {
    
         public string path
         {
             get;
             set;
         }
    
         public void download()
         {
             using (FileStream fs = File.OpenRead(this.path))
             {
                 int length = (int)fs.Length;
                 byte[] buffer;
    
                 using (BinaryReader br = new BinaryReader(fs))
                 {
                     buffer = br.ReadBytes(length);
                 }
    
                 HttpContext.Current.Response.Clear();
                 HttpContext.Current.Response.Buffer = true;
                 HttpContext.Current.Response.AddHeader("content-disposition", 
                 String.Format("attachment;filename={0}",  Path.GetFileName(path)));
                 HttpContext.Current.Response.ContentType = 
                      "application/" + Path.GetExtension(path).Substring(1);
                 HttpContext.Current.Response.BinaryWrite(buffer);
                 HttpContext.Current.Response.End();
             }   //
         }
     }
    
    
    
  3.  create the object for class general and set the path to property  call the download method to make a download the file.  
      public void sDownload()
         {
             downloads obj = new general();
             obj.path = @"C:\GoogleBackup\googleService.txt";
             obj.download();
         }
    
    

Friday, 31 July 2015

Get RAM and CPU usage in C#

Get Cpu and Ram Usage by kernel132.dll in c# How to get CPU percentage ?
  1. Step 1: include namespace in class file
     using System;
     using System.Diagnostics;
     using System.Runtime.InteropServices;
     using System.IO;
    
  2. Step 2: Declare performance counter and other variables and we just get average of cpu 5 times with difference of 5 seconds
     Public string GetCpuPercentage()
      {
       PerformanceCounter cpuCounter;
       double cpuUsage = 0;
       int totalCpuUsage = 0;
       double returnLoopCount = 0;
    
       cpuCounter = new PerformanceCounter();
       cpuCounter.CategoryName = "Processor";
       cpuCounter.CounterName = "% Processor Time";
       cpuCounter.InstanceName = "_Total";
       for (int i = 0; i < 5; i++)
       {
       cpuUsage += cpuCounter.NextValue();
       System.Threading.Thread.Sleep(1000);
       }
       totalCpuUsage = Convert.ToInt32(Math.Ceiling(cpuUsage / 5));
       return totalCpuUsage;
      }
    
  3. Step 3:Declare performance counter and other variables and we just get average of RAM memory usage by using 'Kernel32.dll'
     public string GetRamPercentage()
      {
          PerformanceCounter ramCounter;
               double ramUsage = 0;
               int TotalRamMemory = 0;
               int AvailableRamMemory = 0;
               int UsedRamMemory = 0;
               int RamUsagePercentage = 0;
               double returnLoopCount = 0;
               MEMORYSTATUSEX statEX = new MEMORYSTATUSEX();
               statEX.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
               GlobalMemoryStatusEx(ref statEX);
    
               double ram = (double)statEX.ullTotalPhys;
               //float ram = (float)stat.TotalPhysical;
               ram /= 1024;
               ram /= 1024;
    
               TotalRamMemory = Convert.ToInt32(Math.Round(ram, 0));
               ramCounter = new PerformanceCounter("Memory", "Available MBytes");
               for (int i = 0; i < 5; i++)
               {
                   ramUsage += ramCounter.NextValue();
                   System.Threading.Thread.Sleep(1000);
               }
               AvailableRamMemory = Convert.ToInt32(Math.Round((ramUsage / 5), 0));
               UsedRamMemory = TotalRamMemory - AvailableRamMemory;
               RamUsagePercentage = ((UsedRamMemory * 100) / TotalRamMemory);
    
       return RamUsagePercentage;
            
      }
    
         [return: MarshalAs(UnmanagedType.Bool)]
         [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
         internal static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
    
     [StructLayout(LayoutKind.Sequential)]
     internal struct MEMORYSTATUSEX
      {
           internal uint dwLength;
           internal uint dwMemoryLoad;
           internal ulong ullTotalPhys;
           internal ulong ullAvailPhys;
           internal ulong ullTotalPageFile;
           internal ulong ullAvailPageFile;
           internal ulong ullTotalVirtual;
           internal ulong ullAvailVirtual;
           internal ulong ullAvailExtendedVirtual;
      }
    
    

Thursday, 20 December 2012

jQuery selected tab on postback -Asp.net C#


Its used to store the current tab after postback or reload the current page

in Style.css

.ui-tabs {
    zoom: 1;
}
.ui-tabs .ui-tabs-nav {
    list-style: none;
    position: relative;
    padding: 0;
    margin: 0;
}
.ui-tabs .ui-tabs-nav li {
    position: relative;
    float: left;
    margin: 0 3px -2px 0;
    padding: 0;
}
.ui-tabs .ui-tabs-nav li a {
    display: block;
    padding: 10px 20px;
    background: #f0f0f0;
    border: 2px #ccc solid;
    border-bottom-color: #ccc;
    outline: none;
}
.ui-tabs .ui-tabs-nav li.ui-tabs-selected a {
    padding: 10px 20px 12px 20px;
    background: #fff;
    border-bottom-style: none;
}
.ui-tabs .ui-tabs-nav li.ui-tabs-selected a,
.ui-tabs .ui-tabs-nav li.ui-state-disabled a,
.ui-tabs .ui-tabs-nav li.ui-state-processing a {
    cursor: default;
}
.ui-tabs .ui-tabs-nav li a,
.ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a {
    cursor: pointer;
}
.ui-tabs .ui-tabs-panel {
    display: block;
    clear: both;
    border: 2px #ccc solid;
    padding: 10px;
}
.ui-tabs .ui-tabs-hide {
    display: none;
}
.lab{ float:left; width:20%; font-family:Verdana; font-size:12px;}
.labn{ font-family:Verdana; font-size:12px;}
.head{ font-family:Verdana; font-size:18px; color:red; padding-left:200px;}
.bor{ border:1px dashed #000; width:600px; padding-left:100px; padding-top:10px;}
#container{ width:700px; margin:0 auto 0 auto;}
.textarea {
  -webkit-transition: all 0.30s ease-in-out;
  -moz-transition: all 0.30s ease-in-out;
  -ms-transition: all 0.30s ease-in-out;
  -o-transition: all 0.30s ease-in-out;
  outline: none;
  /*padding: 3px 0px 3px 3px;
  margin: 5px 1px 3px 0px;*/
  border: 1px solid #DDDDDD; width:200px; height:35px;
}

.textarea:focus {
  box-shadow: 0 0 5px rgba(81, 203, 238, 1);
  /*padding: 3px 0px 3px 3px;
  margin: 5px 1px 3px 0px;*/
  border: 1px solid rgba(81, 203, 238, 1);
}
.button {
   border: 1px solid #DDD;
   border-radius: 3px;
   text-shadow: 0 1px 1px white;
   -webkit-box-shadow: 0 1px 1px #fff;
   -moz-box-shadow:    0 1px 1px #fff;
   box-shadow:         0 1px 1px #fff;
   font: bold 11px Sans-Serif;
   padding: 6px 10px;
   white-space: nowrap;
   vertical-align: middle;
   color: #666;
   background: transparent;
   cursor: pointer;
   width:150px; height:35px;
}
.button:hover, .button:focus {
   border-color: #999;
   background: -webkit-linear-gradient(top, white, #E0E0E0);
   background:    -moz-linear-gradient(top, white, #E0E0E0);
   background:     -ms-linear-gradient(top, white, #E0E0E0);
   background:      -o-linear-gradient(top, white, #E0E0E0);
   -webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.25), inset 0 0 3px #fff;
   -moz-box-shadow:    0 1px 2px rgba(0,0,0,0.25), inset 0 0 3px #fff;
   box-shadow:         0 1px 2px rgba(0,0,0,0.25), inset 0 0 3px #fff;
}
.button:active {
   border: 1px solid #AAA;
   border-bottom-color: #CCC;
   border-top-color: #999;
   -webkit-box-shadow: inset 0 1px 2px #aaa;
   -moz-box-shadow:    inset 0 1px 2px #aaa;
   box-shadow:         inset 0 1px 2px #aaa;
   background: -webkit-linear-gradient(top, #E6E6E6, gainsboro);
   background:    -moz-linear-gradient(top, #E6E6E6, gainsboro);
   background:     -ms-linear-gradient(top, #E6E6E6, gainsboro);
   background:      -o-linear-gradient(top, #E6E6E6, gainsboro);
}
.but{ padding-left:130px;} 


in ASPX page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.tabs.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".ui-tabs").tabs();
        $('.ui-tabs').bind('tabsselect', function (event, ui) {
            var selectedTab = ui.index;
            $("#<%= hidLastTab.ClientID %>").val(selectedTab);
        });
    });
</script>

<body>
   
        <div class="ui-tabs">
    <ul class="ui-tabs-nav">
        <li><a href="#tabs-1">Tab One</a></li>
        <li><a href="#tabs-2">Tab Two</a></li>
        <li><a href="#tabs-3">Tab Three</a></li>
    </ul>
    <div id="tabs-1" class="ui-tabs-panel">
        <form id="form1" runat="server">
        <asp:HiddenField ID="hidLastTab" runat="server" Value="0" />
    <div>
    <div class="head">Login Here!!!</div><br />
    <div>
        <label class="lab">email</label><asp:TextBox ID="TextBox1" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
        <label class="lab">password</label><asp:TextBox ID="TextBox2" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
        <div class="but"><asp:Button ID="Button1" runat="server" Text="Button"
                CssClass="button" onclick="Button1_Click" /> 
            <asp:Label ID="lbl" runat="server"></asp:Label>
        </div>
    </div>
    </div>
  
    </div>
    <div id="tabs-2" class="ui-tabs-panel">
      <div class="head">Registeration form</div><br />  
    <div class="bor">
    <label class="lab">name</label><asp:TextBox ID="TextBox3" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">email</label><asp:TextBox ID="TextBox4" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">password</label><asp:TextBox ID="TextBox9" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">first name</label><asp:TextBox ID="TextBox5" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">last name</label><asp:TextBox ID="TextBox6" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">mobile number</label><asp:TextBox ID="TextBox7" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">state</label>
        <asp:TextBox ID="TextBox8" runat="server" CssClass="textarea"></asp:TextBox>
    <br /><br />
    <label class="lab">country</label><asp:TextBox ID="TextBox15" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">area</label><asp:TextBox ID="TextBox10" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">gender</label>
        <asp:RadioButtonList CssClass="labn"
            ID="RadioButtonList1" runat="server">
            <asp:ListItem>male</asp:ListItem>
            <asp:ListItem>female</asp:ListItem>
        </asp:RadioButtonList>
   
    <br />
    <div class="but"><asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click"  CssClass="button"/></div>
    <asp:Label ID="lblr" runat="server"></asp:Label><br />
    </div>
   
    </div>
    <div id="tabs-3" class="ui-tabs-panel">
        <p>Content three.</p>
        <asp:Button ID="Button3" runat="server" Text="Button" onclick="Button3_Click" />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</div>
   
</body>


in ASPX.CS page:

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

public partial class Default6 : System.Web.UI.Page
{

    static string strconn = ConfigurationManager.ConnectionStrings["reg"].ConnectionString;
    SqlConnection con = new SqlConnection(strconn);
    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "selecttab", "$('.ui-tabs').tabs({ selected: " + hidLastTab.Value + " });", true);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {


        con.Open();
        SqlCommand cmdd = new SqlCommand("select * from tb_reg where email='" + TextBox1.Text + "' AND password='" + TextBox2.Text + "'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmdd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            Session["user"] = TextBox1.Text;
            Response.Redirect("drop.aspx");
        }
        else
        {
            lbl.Text = "login failure";
        }
        con.Close();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
 
        SqlConnection con = new SqlConnection(strconn);
        SqlCommand insrt = new SqlCommand("insert into tb_reg (username,email,password,firstname,lastname,mobilenumber,state,country,area,gender) values ('" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox9.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox15.Text + "','" + TextBox10.Text + "','" + RadioButtonList1.Text + "')", con);
        con.Open();
        insrt.ExecuteNonQuery();

        //int arun;

        //SqlCommand sel = new SqlCommand("select * from tb_reg");
        //SqlDataAdapter da = new SqlDataAdapter(sel);
        //DataTable dt = new DataTable();
        //da.Fill(dt);
        //if (dt.Rows.Count > 0)
        //{
        //    lblr.Text = "register sucess";
        //}
        //else
        //{
        //    lblr.Text = "register failed";
        //}

        lblr.Text = "register sucess!!!";
        con.Close();

        TextBox1.Text = "";
        TextBox2.Text = "";
        TextBox9.Text = "";
        TextBox3.Text = "";
        TextBox4.Text = "";
        TextBox5.Text = "";
        TextBox6.Text = "";
        TextBox7.Text = "";
        TextBox8.Text = "";
        TextBox9.Text = "";

    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        Label1.Text = "test";
    }
}





Friday, 7 December 2012

Grid view edit delete and update in asp.net

Database-SQL


USE [sqlcon]
GO
/****** Object:  Table [dbo].[myTable]    Script Date: 12/08/2012 10:08:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[myTable](
[AutoID] [int] IDENTITY(1,1) NOT NULL,
[PageName] [varchar](50) NULL,
[PageDescription] [varchar](500) NULL,
[Active] [bit] NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF


Stored Procedure :


USE [sqlcon]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateData]    Script Date: 12/08/2012 10:09:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spUpdateData]
@AutoID [int],
@PageName [varchar](50),
@PageDescription [varchar](500),
@Active [Bit]
AS
UPDATE myTable
    SET PageName=@PageName,
        PageDescription=@PageDescription ,
Active=@Active
    WHERE AutoID=@AutoID

IN ASPX-Page :


 <form id="form1" runat="server">
    <div>
    <asp:Label ID="lblMessage" runat="Server" ForeColor="Red"></asp:Label>

            <asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False" BorderWidth="1"

                DataKeyNames="AutoID" AutoGenerateEditButton="True" OnRowEditing="EditRecord"

                OnRowCancelingEdit="CancelRecord" OnRowUpdating="UpdateRecord" CellPadding="4"

                HeaderStyle-HorizontalAlign="left" OnRowDeleting="DeleteRecord" RowStyle-VerticalAlign="Top"

                ForeColor="#333333" GridLines="None">

                <Columns>

                    <asp:BoundField DataField="AutoID" HeaderText="AutoID" ReadOnly="True" />

                    <asp:TemplateField HeaderText="Page Name">

                        <ItemTemplate>

                            <%# Eval("PageName") %>

                        </ItemTemplate>

                        <EditItemTemplate>

                            <asp:TextBox ID="txtPageName" runat="Server" Text='<%# Eval("PageName") %>' Columns="30"></asp:TextBox>

                            <asp:RequiredFieldValidator ID="req1" runat="Server" Text="*" ControlToValidate="txtPageName"></asp:RequiredFieldValidator>

                        </EditItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Page Description">

                        <ItemTemplate>

                            <%# Eval("PageDescription") %>

                        </ItemTemplate>

                        <EditItemTemplate>

                            <asp:TextBox ID="txtPageDesc" runat="Server" TextMode="MultiLine" Rows="10" Columns="50"

                                Text='<%# Eval("PageDescription") %>'></asp:TextBox>

                            <asp:RequiredFieldValidator ID="req2" runat="Server" Text="*" ControlToValidate="txtPageDesc"></asp:RequiredFieldValidator>

                        </EditItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Active">

                        <ItemTemplate>

                            <%# Eval("Active") %>

                        </ItemTemplate>

                        <EditItemTemplate>

                            <asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active").ToString().ToLower().Equals("true") ? "True" : "False" %>'>

                                <asp:ListItem Text="Yes" Value="True"></asp:ListItem>

                                <asp:ListItem Text="No" Value="False"></asp:ListItem>

                            </asp:DropDownList>

                        </EditItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Delete">

                        <ItemTemplate>

                            <span onclick="return confirm('Are you sure to Delete the record?')">

                                <asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandName="Delete"></asp:LinkButton>

                            </span>

                        </ItemTemplate>

                    </asp:TemplateField>

                </Columns>

                <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

                <RowStyle BackColor="#FFFBD6" ForeColor="#333333" VerticalAlign="Top" />

                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />

                <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />

                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />

                <AlternatingRowStyle BackColor="White" />

            </asp:GridView>


    </div>
    </form>

IN CS page:


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

public partial class samplegrid : System.Web.UI.Page
{

    static string connStr = ConfigurationManager.ConnectionStrings["reg"].ConnectionString;
    SqlConnection conn = new SqlConnection(connStr);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            BindData();

        }

    }


    private void BindData()
    {

       

        SqlDataAdapter dAd = new SqlDataAdapter("select * from myTable", conn);

        DataSet dSet = new DataSet();

        try
        {



            dAd.Fill(dSet, "PagesData");

            GridView1.DataSource = dSet.Tables["PagesData"].DefaultView;

            GridView1.DataBind();

        }

        catch (Exception ee)
        {

            lblMessage.Text = ee.Message.ToString();

        }

        finally
        {

            dSet.Dispose();

            dAd.Dispose();

            conn.Close();

            conn.Dispose();

        }

    }

    protected void EditRecord(object sender, GridViewEditEventArgs e)
    {

        GridView1.EditIndex = e.NewEditIndex;

        BindData();

    }

    protected void CancelRecord(object sender, GridViewCancelEditEventArgs e)
    {

        GridView1.EditIndex = -1;

        BindData();

    }

    protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)
    {

        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];



        int autoid = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());

        TextBox tPageName = (TextBox)row.FindControl("txtPageName");

        TextBox tPageDesc = (TextBox)row.FindControl("txtPageDesc");

        DropDownList dActive = (DropDownList)row.FindControl("dropActive");



        //SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ToString());

        SqlCommand dCmd = new SqlCommand();

        try
        {

            conn.Open();

            dCmd.CommandText = "spUpdateData";

            dCmd.CommandType = CommandType.StoredProcedure;

            dCmd.Parameters.Add("@AutoID", SqlDbType.Int).Value = autoid;

            dCmd.Parameters.Add("@PageName", SqlDbType.VarChar, 50).Value = tPageName.Text.Trim();

            dCmd.Parameters.Add("@PageDescription", SqlDbType.VarChar, 500).Value = tPageDesc.Text.Trim();

            dCmd.Parameters.Add("@Active", SqlDbType.Bit).Value = bool.Parse(dActive.SelectedValue);

            dCmd.Connection = conn;

            dCmd.ExecuteNonQuery();
         
            //conn.Open();
            //SqlCommand cmd = new SqlCommand("update myTable SET PageName='"+tPageName.Text+"',PageDescription='"+tPageDesc.Text+"',Active='"+dActive.SelectedValue+"' where AutoID='"+autoid+"'", conn);
            //int result = cmd.ExecuteNonQuery();
            //conn.Close();
            //if (result == 1)
            //{
            //    BindData();
               
            //}

            //lblMessage.Text = "Record Updated successfully.";





            // Refresh the data

            GridView1.EditIndex = -1;

            BindData();

        }

        catch (SqlException ee)
        {

            lblMessage.Text = ee.Message;

        }

        finally
        {

            //dCmd.Dispose();

            conn.Close();

            conn.Dispose();

        }



    }

    protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
    {

        string autoid = GridView1.DataKeys[e.RowIndex].Value.ToString();

        //SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ToString());

        SqlCommand dCmd = new SqlCommand();

        try
        {

         



       LinkButton lnkbtn = sender as LinkButton;
       //getting particular row linkbutton
      // GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
       //getting userid of particular row
      // int userid = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Value.ToString());
      // string username = gvrow.Cells[0].Text;
       conn.Open();
       SqlCommand cmd = new SqlCommand("delete from myTable where AutoID=" + autoid, conn);
       int result = cmd.ExecuteNonQuery();
       conn.Close();
       if (result == 1)
       {
           BindData();
           //Displaying alert message after successfully deletion of user
           //ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + PackageName + " details deleted successfully')", true);
           //GridView1.DataSourceID = null;
           //GridView1.DataSourceID = "SqlDataSource1";
       }
 
            //dCmd.CommandText = "spDeleteData";
            //dCmd.CommandType = CommandType.StoredProcedure;
            //dCmd.Parameters.Add("@AutoID", SqlDbType.Int).Value = Int32.Parse(autoid);
            //dCmd.Connection = conn;
            //dCmd.ExecuteNonQuery();
            //lblMessage.Text = "Record Deleted successfully.";
            // Refresh the data

            BindData();

        }

        catch (SqlException ee)
        {

            lblMessage.Text = ee.Message;

        }

        finally
        {

            dCmd.Dispose();

            conn.Close();

            conn.Dispose();

        }

    }

}








Tuesday, 27 November 2012

Dynamic Drop Down list and fetchin value without using ajax in asp.net

in drop.aspx

<script type="text/javascript">
        function selectDropdown() {
        var dropdownValue = document.getElementById("DropDownList1").value;
        //alert("You selected : " + dropdownValue);
        document.getElementById("Textbox1").value = dropdownValue;
   }
</script>
  
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="DropDownList1" runat="server">
    </asp:DropDownList>
     <asp:textbox ID="Textbox1" runat="server" CssClass="textarea"></asp:textbox>
    </div>
      </form>

in drop.aspx.cs page

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

public partial class Default3 : System.Web.UI.Page
{
    static string strconn = ConfigurationManager.ConnectionStrings["reg"].ConnectionString;
    SqlConnection con = new SqlConnection(strconn);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.Attributes.Add("onchange", "javscript:selectDropdown();");
            BindDrop();
        }
    }

    protected void BindDrop()
    {
        con.Open();
        SqlCommand comma = new SqlCommand("select username,mobilenumber from tb_reg", con);
        SqlDataAdapter da = new SqlDataAdapter(comma);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "username";
        DropDownList1.DataValueField = "mobilenumber";
        DropDownList1.DataBind();
        Textbox1.Text = DropDownList1.SelectedItem.Value.ToString();
        con.Close();

    }

}


Output:




simple login form in asp.net

In aspx page:

<div id="container">
    <form id="form1" runat="server">
    <div>
    <div class="head">Login Here!!!</div><br />
    <div>
        <label class="lab">email</label><asp:TextBox ID="TextBox1" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
        <label class="lab">password</label><asp:TextBox ID="TextBox2" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
        <div class="but"><asp:Button ID="Button1" runat="server" Text="Button"
                CssClass="button" onclick="Button1_Click" /> 
            <asp:Label ID="lbl" runat="server"></asp:Label>
        </div>
    </div>
    </div>
    </form>
    </div>

IN CS PAGE

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

public partial class Default3 : System.Web.UI.Page
{
    static string strconn = ConfigurationManager.ConnectionStrings["reg"].ConnectionString;
    SqlConnection con = new SqlConnection(strconn);
    protected void Page_Load(object sender, EventArgs e)
    {

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

      
        con.Open();
        SqlCommand cmdd = new SqlCommand("select * from tb_reg where email='" + TextBox1.Text + "' AND password='" + TextBox2.Text + "'",con);  
        SqlDataAdapter da = new SqlDataAdapter(cmdd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            Session["user"] = TextBox1.Text;
            Response.Redirect("drop.aspx");   
        }
        else
        {
            lbl.Text = "login failure";
        }
        con.Close();
    }
}


simple register form in asp.net


WEB-CONFIG FILE:
<add name="reg" connectionString="Data Source=AAGNA-PC\SQLEXPRESS;Initial Catalog=sqlcon;User id=;Password=; Integrated Security=SSPI"/>

CSS-FOR FORM STYLE NAMED MAIN.CSS:

.lab{ float:left; width:20%; font-family:Verdana; font-size:12px;}
.labn{ font-family:Verdana; font-size:12px;}
.head{ font-family:Verdana; font-size:18px; color:red; padding-left:200px;}
.bor{ border:1px dashed #000; width:600px; padding-left:100px; padding-top:10px;}
#container{ width:700px; margin:0 auto 0 auto;}
.textarea {
  -webkit-transition: all 0.30s ease-in-out;
  -moz-transition: all 0.30s ease-in-out;
  -ms-transition: all 0.30s ease-in-out;
  -o-transition: all 0.30s ease-in-out;
  outline: none;
  /*padding: 3px 0px 3px 3px;
  margin: 5px 1px 3px 0px;*/
  border: 1px solid #DDDDDD; width:200px; height:35px;
}

.textarea:focus {
  box-shadow: 0 0 5px rgba(81, 203, 238, 1);
  /*padding: 3px 0px 3px 3px;
  margin: 5px 1px 3px 0px;*/
  border: 1px solid rgba(81, 203, 238, 1);
}
.button {
   border: 1px solid #DDD;
   border-radius: 3px;
   text-shadow: 0 1px 1px white;
   -webkit-box-shadow: 0 1px 1px #fff;
   -moz-box-shadow:    0 1px 1px #fff;
   box-shadow:         0 1px 1px #fff;
   font: bold 11px Sans-Serif;
   padding: 6px 10px;
   white-space: nowrap;
   vertical-align: middle;
   color: #666;
   background: transparent;
   cursor: pointer;
   width:150px; height:35px;
}
.button:hover, .button:focus {
   border-color: #999;
   background: -webkit-linear-gradient(top, white, #E0E0E0);
   background:    -moz-linear-gradient(top, white, #E0E0E0);
   background:     -ms-linear-gradient(top, white, #E0E0E0);
   background:      -o-linear-gradient(top, white, #E0E0E0);
   -webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.25), inset 0 0 3px #fff;
   -moz-box-shadow:    0 1px 2px rgba(0,0,0,0.25), inset 0 0 3px #fff;
   box-shadow:         0 1px 2px rgba(0,0,0,0.25), inset 0 0 3px #fff;
}
.button:active {
   border: 1px solid #AAA;
   border-bottom-color: #CCC;
   border-top-color: #999;
   -webkit-box-shadow: inset 0 1px 2px #aaa;
   -moz-box-shadow:    inset 0 1px 2px #aaa;
   box-shadow:         inset 0 1px 2px #aaa;
   background: -webkit-linear-gradient(top, #E6E6E6, gainsboro);
   background:    -moz-linear-gradient(top, #E6E6E6, gainsboro);
   background:     -ms-linear-gradient(top, #E6E6E6, gainsboro);
   background:      -o-linear-gradient(top, #E6E6E6, gainsboro);
}
.but{ padding-left:130px;}



IN ASPX-FILE

 <div id="container">
      <div class="head">Registeration form</div><br />
    <form id="form1" runat="server">
    <div class="bor">
   
   
    <label class="lab">name</label><asp:TextBox ID="TextBox1" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">email</label><asp:TextBox ID="TextBox2" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">password</label><asp:TextBox ID="TextBox9" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">first name</label><asp:TextBox ID="TextBox3" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">last name</label><asp:TextBox ID="TextBox4" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">mobile number</label><asp:TextBox ID="TextBox5" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">state</label>
        <asp:TextBox ID="TextBox6" runat="server" CssClass="textarea"></asp:TextBox>
    <br /><br />
    <label class="lab">country</label><asp:TextBox ID="TextBox7" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">area</label><asp:TextBox ID="TextBox8" runat="server" CssClass="textarea"></asp:TextBox>
        <br /><br />
    <label class="lab">gender</label>
        <asp:RadioButtonList CssClass="labn"
            ID="RadioButtonList1" runat="server">
            <asp:ListItem>male</asp:ListItem>
            <asp:ListItem>female</asp:ListItem>
        </asp:RadioButtonList>
   
    <br />
    <div class="but"><asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"  CssClass="button"/></div>
    <asp:Label ID="lblr" runat="server"></asp:Label><br />
    </div>
    </form>
    </div>



IN ASPX.CS FILE:

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

public partial class Default2 : System.Web.UI.Page
{
    static string strconn = ConfigurationManager.ConnectionStrings["reg"].ConnectionString;   
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(strconn);
        SqlCommand insrt = new SqlCommand("insert into tb_reg (username,email,password,firstname,lastname,mobilenumber,state,country,area,gender) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox9.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','"+ RadioButtonList1.Text +"')",con);
        con.Open();
        insrt.ExecuteNonQuery();

        //int arun;
       
        //SqlCommand sel = new SqlCommand("select * from tb_reg");
        //SqlDataAdapter da = new SqlDataAdapter(sel);
        //DataTable dt = new DataTable();
        //da.Fill(dt);
        //if (dt.Rows.Count > 0)
        //{
        //    lblr.Text = "register sucess";
        //}
        //else
        //{
        //    lblr.Text = "register failed";
        //}

        lblr.Text = "register sucess!!!";
        con.Close();

        TextBox1.Text = "";
        TextBox2.Text = "";
        TextBox9.Text = "";
        TextBox3.Text = "";
        TextBox4.Text = "";
        TextBox5.Text = "";
        TextBox6.Text = "";
        TextBox7.Text = "";
        TextBox8.Text = "";
        TextBox9.Text = "";



    }
}

DATABASE-FILE:
USE [sqlcon]
GO
/****** Object:  Table [dbo].[tb_reg]    Script Date: 11/28/2012 11:27:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tb_reg](
 [username] [varchar](50) NULL,
 [email] [varchar](50) NULL,
 [password] [varchar](50) NULL,
 [firstname] [varchar](50) NULL,
 [lastname] [varchar](50) NULL,
 [mobilenumber] [bigint] NULL,
 [state] [varchar](50) NULL,
 [country] [varchar](50) NULL,
 [area] [varchar](50) NULL,
 [gender] [varchar](50) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

OUTPUT:


Sunday, 25 November 2012

Asp.net config file for upload datas in sql db

webconfig file:
<connectionStrings>
    <add name="arunkumar" connectionString="Data Source=AAGNA-PC\SQLEXPRESS;Initial Catalog=giri;Integrated Security=true;User id=sa;Password=;"/>
  </connectionStrings>

in public class file:
static string strcon = ConfigurationManager.ConnectionStrings["arunkumar"].ConnectionString;
    SqlConnection con = new SqlConnection(strcon);

button_click coding:
 protected void Button1_Click(object sender, EventArgs e)
    {
        //SqlConnection con = new SqlConnection("data source=AAGNA-PC;I ntegrated Security=SSPI;Initial Catalog:tb_login ;User Instance=true;");
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into tb_login(username,password) values('"+ txt.Text  +"','"+ txt1.Text +"') ", con);
        cmd.ExecuteNonQuery();
        con.Close();
    }


button_click for grid view display:
protected void Button2_Click(object sender, EventArgs e)
    {
        SqlCommand cmd1 = new SqlCommand("select * from tb_login",con);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd1);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }

database sql coding :
after creating database named giri after workout this query !

USE [giri]
GO
/****** Object:  Table [dbo].[tb_login]    Script Date: 11/26/2012 12:30:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tb_login](
    [username] [varchar](50) NULL,
    [password] [varchar](50) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

output :