MY bLOG

Showing posts with label Asp.Net. Show all posts
Showing posts with label Asp.Net. Show all posts

Wednesday, 5 March 2014

How to add validation controls to update event in gridview?

In this article  i will explain how to validate the controls which are placed in grid view
http://aswinialuri.blogspot.in/2014/03/how-to-insert-editdelete-update-and.html

In the above article i explained how to insert,edit,delete,update and cancelling operations in grid view using Asp.net.
So here  i will explain how to update the data using validation to avoid  empty cell upadating

code in .aspx page:

 <div>
    <asp:GridView ID="gridview" runat="server" AutoGenerateColumns="False" 
            AutoGenerateEditButton="True"  AutoGenerateDeleteButton="True" 
             DataKeyNames="Id" onrowcancelingedit="gridview_RowCancelingEdit" 
            onrowdeleting="gridview_RowDeleting" onrowediting="gridview_RowEditing" 
            onrowupdating="gridview_RowUpdating" >
            
            <Columns><asp:TemplateField HeaderText="Id"><ItemTemplate><asp:Label ID="lbl_id" runat="server" Text='<%#Eval("Id")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_id" runat="server" Text='<%#Eval("Id")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name"><ItemTemplate><asp:Label ID="lbl_name" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_name" runat="server" Text='<%#Eval("Name")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Salary"><ItemTemplate><asp:Label ID="lbl_sal" runat="server" Text='<%#Eval("salary")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_salary" runat="server" Text='<%#Eval("salary")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Department"><ItemTemplate><asp:Label ID="lbl_dept" runat="server" Text='<%#Eval("Department")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_dept" runat="server" Text='<%#Eval("Department")%>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txt_dept" Text="*" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
            </EditItemTemplate>
            </asp:TemplateField>
             </Columns>
        </asp:GridView>
        <br />
    </div>
    <table><tr><td>Id:</td><td>
            <asp:TextBox ID="txt_id" runat="server"></asp:TextBox></td></tr>
            <tr><td>Name:</td><td>
                <asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td></tr>
                <tr><td>Salary:</td><td>
                    <asp:TextBox ID="txt_salary" runat="server"></asp:TextBox></td></tr>
                    <tr><td>Department:</td><td>
                        <asp:TextBox ID="txt_dept" runat="server"></asp:TextBox></td></tr>
                        <tr><td colspan="2" align="center">
                            <asp:Button ID="btn_submit" runat="server" Text="Submit" 
                                onclick="btn_submit_Click" /></td></tr>

            </table>

code in .aspx.cs page:

//To update a row event
 protected void gridview_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = gridview.Rows[e.RowIndex] as GridViewRow;
        int id = Convert.ToInt32(gridview.DataKeys[e.RowIndex].Values["Id"].ToString());
        TextBox txtname = (TextBox)gridview.Rows[e.RowIndex].FindControl("txt_name");
        TextBox txtsalary = (TextBox)gridview.Rows[e.RowIndex].FindControl("txt_salary");
        TextBox txtdepartment = (TextBox)gridview.Rows[e.RowIndex].FindControl("txt_dept");
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("update Emp1 set Name=@Name,salary=@salary,Department=@Department "+" where Id=@Id", con);
        cmd.Parameters.AddWithValue("@Name", txtname.Text);
        cmd.Parameters.AddWithValue("@salary", txtsalary.Text);
        cmd.Parameters.AddWithValue("@Department", txtdepartment.Text);
        cmd.Parameters.AddWithValue("@Id",id);
        con.Open();
        cmd.ExecuteNonQuery();
        gridview.EditIndex = -1;
        con.Close();
        binddata();

    }
I f you click on update button 
required field validator is set into the department if you leave the text box empty it shown an error so the row will not be updated and you will assign the text for particular department .

I hope you understand the article how to validate the text in row event
If you have any queries make a comment.

How to Insert, Edit,Delete ,Update and Canceling in Grid view using asp.net?

In this article i will explain how to insert edit update delete and canceling operations in grid view

You can achieve by using the
1.onrowediting-Is used to Edit the particular row
2.onrowupdating-Is used to update the particular row
3.onrowdeleting-Is used to delete the particular row
4.onrowcancelingedit-Is used to cancel the particular row

code in .aspx page:


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            AutoGenerateEditButton="True" onrowediting="GridView1_RowEditing" 
            onrowupdating="GridView1_RowUpdating" AutoGenerateDeleteButton="True" 
            onrowdeleting="GridView1_RowDeleting" DataKeyNames="Id" 
            onrowcancelingedit="GridView1_RowCancelingEdit">
            <Columns><asp:TemplateField HeaderText="Id"><ItemTemplate><asp:Label ID="lbl_id" runat="server" Text='<%#Eval("Id")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_id" runat="server" Text='<%#Eval("Id")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name"><ItemTemplate><asp:Label ID="lbl_name" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_name" runat="server" Text='<%#Eval("Name")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Salary"><ItemTemplate><asp:Label ID="lbl_sal" runat="server" Text='<%#Eval("salary")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_salary" runat="server" Text='<%#Eval("salary")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Department"><ItemTemplate><asp:Label ID="lbl_dept" runat="server" Text='<%#Eval("Department")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_dept" runat="server" Text='<%#Eval("Department")%>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
             </Columns>
        </asp:GridView>
        <br />
        <table><tr><td>Id:</td><td>
            <asp:TextBox ID="txt_id" runat="server"></asp:TextBox></td></tr>
            <tr><td>Name:</td><td>
                <asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td></tr>
                <tr><td>Salary:</td><td>
                    <asp:TextBox ID="txt_salary" runat="server"></asp:TextBox></td></tr>
                    <tr><td>Department:</td><td>
                        <asp:TextBox ID="txt_dept" runat="server"></asp:TextBox></td></tr>
                        <tr><td colspan="2" align="center">
                            <asp:Button ID="btn_submit" runat="server" Text="Submit" 
                                onclick="btn_submit_Click" /></td></tr>
            </table>
    </div>

    </form>
create table in sql server
column name                       datatype

Id                                         Int(set identity property =true)
Name                                     Nvarchar(100)
Salary                                    Nvarchar(50)
Deprtment                             Nvarchar(50)

code in .aspx.cs page:
Add namespaces 
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


 string strcon = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getdata();
        }
    }
//To bind the data from database to grid view
    public void getdata()
    {
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("select * from Emp", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource=ds;
        GridView1.DataBind();
    }
//To edit the the row event
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        getdata();
    }
//To update the row event
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
        int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Id"].ToString());
        TextBox tname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_name");
        TextBox tsalary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_salary");
        TextBox tdept = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_dept");
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("update Emp set Name=@Name,salary=@salary,Department=@Department"+" where Id=@Id", con);
        cmd.Parameters.AddWithValue("@Name", tname.Text.Trim());
        cmd.Parameters.AddWithValue("@salary",tsalary.Text.Trim());
        cmd.Parameters.AddWithValue("@Department", tdept.Text.Trim());
        cmd.Parameters.AddWithValue("@Id", Id);
        con.Open();
        cmd.ExecuteNonQuery();
        GridView1.EditIndex = -1;
        getdata();
        con.Close();
   
    }
//To delete the row event
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Id"].ToString());
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("delete from Emp where Id=@Id", con);
        con.Open();
        cmd.Parameters.AddWithValue("@Id", Id);
        cmd.ExecuteNonQuery();
        
        GridView1.DataBind();
        con.Close();
        getdata();
    }
//To canceling the row
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        getdata();
    }
    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
            }
//To insert the data and bind into gridview as well as data base
    protected void btn_submit_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(strcon);
        con.Open();
        SqlCommand cmd = new SqlCommand("emp_insert_sp", con);
        cmd.CommandType = CommandType.StoredProcedure;
        //cmd.Parameters.AddWithValue("@Id", txt_id.Text);
        cmd.Parameters.AddWithValue("@Name", txt_name.Text);
        cmd.Parameters.AddWithValue("@salary", txt_salary.Text);
        cmd.Parameters.AddWithValue("@Department", txt_dept.Text);
        cmd.ExecuteNonQuery();

        con.Close();
I hope you understand how to insert ,edit ,update ,delete and canceling in gridview using asp.net

Thursday, 30 January 2014

How to insert the data into gridview using textboxes in asp.net?


I would like to explain about inserting values into textbox and that will be displayed in grid view 
so  for that  
In visual studio click on file -->New project-->Add weapplication-> add new item-->
add new web form

In .aspx page:

  <table>
        <tr><td>Name:</td><td>
            <asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td></tr>
            <tr><td>Description:</td><td>
                <asp:TextBox ID="txt_description" runat="server"></asp:TextBox></td></tr>
                <tr><td>Department:</td><td>
                    <asp:TextBox ID="txt_depart" runat="server"></asp:TextBox></td></tr>
                    <tr><td colspan="2" align="center">
                        <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" /></td></tr>
        </table>
<asp:label: id="1abel1" runat="server" >
The page will be display like this 
code in .aspx.cs page:
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class insert : System.Web.UI.Page
    {
        string strcon = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
// you have to add configuration in name space .
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
        }
code in button click event

        protected void Button1_Click(object sender, EventArgs e)
        {
try
{
            SqlConnection con = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand("insert_sp_emp", con);
 //here i passed stored procedure instead ofinsert  query.
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Name", txt_name.Text);
            cmd.Parameters.AddWithValue("@Description", txt_description.Text);
            cmd.Parameters.AddWithValue("@Department", txt_depart.Text);
            con.Open();
            cmd.ExecuteNonQuery();
       label1.text="Record Inserted Succesfully;
            con.Close();
}
catch(Exception,ex)
{
label1.Text=ex.message;
}

        }
    }
}
in sql server 
 crete table 
and write  procedure for insert query i.e,

create procedure insert_sp_emp(@Name nvarchar(50),@Description nvarchar(50),@Department nvarchr(50))
AS
BEGIN
insert into tablename(Name,Description,Department) values(@Name,@Description,@Department)
END

if you set an identity true no need to mention id as parameter-(@Id int)

Web Config file:

<configuration>
  <connectionStrings>
    <add name="sqlconn" connectionString="Data Source=SYS-2;Initial Catalog=Emp;Integrated Security=True"/>

  </connectionStrings>

So build your application and start debugging then it shown your output like this 




then you have to display the complete record into gridview using asp.net:
in .aspx page:
drag and drop gridview from datbound controls
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" />
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Description" HeaderText="Description" />
                <asp:BoundField DataField="Department" HeaderText="Department" />
            </Columns>


        </asp:GridView>

code in .aspx.cs page:
 public void binddata()
        {
            SqlConnection con = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand("select* from Emp", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();

        }
In button click event  you have to mention 
bindata(); before con.close();//connection close
then build the and debug the code once
then it will be displayed liked this


so it is useful for beginners who are learning asp.net newly
I hope you understand  raise a query you have any doubt about this

Wednesday, 18 December 2013

Refresh web page

How to refresh a web page with out any button click events 
             
                we can achieve this writing a single line in aspx  page i.e, on html page in head section 
<meta http-equiv="refresh" content="30/>

After 30 sec it will be refreshed if you want to redirect to another page after refreshing then set an url  in the content
<meta http-equiv="refresh" content="30;url=http://www.google.com/> 

then after 30 secs it will be redirected to refresh button.
 or else 
in your project if you want to redirect to certain page then mention  localhost url in the content.


I hope it will help you

Tuesday, 17 December 2013

how to upload and view pdf files using file upload control ?

In this i would like to explain about upload pdf and view, using file upload control .
here i will explain already we studied about upload control in previous chapter.
So
code in .aspx page:
<form>
<div>
 Upload:<asp:FileUpload runat="server" ID="fileUpload" />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="FileUpload_Click" />
        <asp:HyperLink  runat="server" ID="lnkButton" Text="View File" />
    </div>
    </form>
code in .aspx.cs page:
  Add name space using sytem .IO;
//code in button click event.
Add  folder in solution explorer Resumes

 protected void FileUpload_Click(object sender, EventArgs e)
        {
            if (fileUpload.HasFile)
            {
                string strpath = "~/Resumes" + fileUpload.FileName;
                fileUpload.SaveAs(Server.MapPath(strpath));
                lnkButton.NavigateUrl = "~/Resumes/" + fileUpload.FileName;
//This link button redirects to our resume folder and display the pdf file.
                Response.Write("<script>alert('uploaded successfully');</script>");

            }
}
So your pdf is uploaded  here and if you click on view file then it show your pdf file formate.
maximum size for uploading a pdf file is 4096 i.e, 4mb only.
you will specify the size limit in web config file.
In <system.web> tag
system.web>
      <httpRuntime executionTimeout="90" maxRequestLength="16834" useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="100"
enableVersionHeader="true" />
(4096 for 4mb it is default,8192 for 8mb,16384 for 16 mb, 65536 for 64 mb .............
I hope you understand .
if you get any queries about this post a comment.

Monday, 16 December 2013

how to save and retrieve the images in database and show it in grid view using asp.net?

In previous post i explained how to save image in folder and image path in database now i will explain how to retrieve the image from database and display it in grid view.


create table in database:
CREATE TABLE [dbo].[photoalbum](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Images] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


GO
In .aspx page:

<body>
    <form id="form1" runat="server">
    <div align="center">
    <h2 align="center">Upload and Save</h2>
        <table align="center"><tr><td>
        <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label></td>
       <td><asp:TextBox  ID="TXT_NAME" runat="server"></asp:TextBox></td></tr>
       <tr><td>Image:</td><td><asp:FileUpload ID="fileupload1" runat="server" /></td></tr>
        <tr><td colspan="2" align="center">
           <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /></td></tr>
           <asp:Label ID="lbl_text" runat="server"></asp:Label>
        </table>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" />
               
                <asp:BoundField DataField="Name" HeaderText="ImageName" />
                <asp:ImageField DataImageUrlField="Images" HeaderText="Images">
                </asp:ImageField>
               
            </Columns>

        </asp:GridView>
    </div>
    </form>

</body>
In .aspx.cs page:
Add Namespaces :
using system.io;
using system.data;
using system.data.sqlclient;
using system.configuration;

 public partial class TouploadandView : System.Web.UI.Page
    {
        string strcon=ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
            }
        }
        public void getdata()
        {
            SqlConnection con = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand("select * from photoalbum", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
            SqlConnection con=new SqlConnection(strcon);
            if (fileupload1.HasFile)
            {
               
                
                    string path = "~/Images/" + fileupload1.FileName;
                    fileupload1.SaveAs(Server.MapPath(path));
                  string getfile=path;
                  SqlCommand cmd = new SqlCommand("sp_insert", con);
                    cmd.CommandType=CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Name",TXT_NAME.Text.Trim());
                    cmd.Parameters.AddWithValue("@Images",getfile);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    lbl_text.Text="Image upload successfull";
                    getdata();
                    con.Close();
               
            }
            }
                   catch(Exception ex)
            {
                   lbl_text.Text=ex.Message;

                   }

                   
                }
            }

        }
Web config file:
To set your database connection in web.config like this because we are using this connection in our datasource to get the data from database.
 <configuration>
  <connectionStrings>
    <add name="sqlconn" connectionString="Data Source=SYSTEM-05-PC;Initial Catalog=asw;Integrated Security=True"/>
  </connectionStrings>





i hope you understand this article

Saturday, 23 November 2013

How to upload file and save it in database?

I would like to explain about  upload images and save it in database you have already seen to upload an images .

In database:
create table & stored procedure:
CREATE TABLE [dbo].[photoalbum](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Images] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


GO
stored procedure:
create procedure sp_insert(@Name nvarchar(50),@Images nvarchar(MAX))
as
begin
insert into photoalbum values(@Name,@Images)

end
In .aspx page:

<body>
    <form id="form1" runat="server">
    <div>
    <h2 align="center">Upload and Save</h2>
        <table align="center">
<tr>
<td>
        <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>
</td>
       <td>
<asp:TextBox  ID="TXT_NAME" runat="server"></asp:TextBox>
</td>
</tr>
       <tr>
<td>
Image:</td><td><asp:FileUpload ID="fileupload1" runat="server" />
</td>
</tr>
        <tr>
<td colspan="2" align="center">
           <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /></td>
</tr>
        </table>
    <asp:Label ID="lbl_text" runat="server"></asp:Label>
    </div>
    </form>
</body>
you can add an Images folder in the solution Explorer
In .aspx.cs page:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
            SqlConnection con=new SqlConnection(strcon);
            if (fileupload1.HasFile)
            {
                if (fileupload1.PostedFile.ContentType == "image/jpeg" || fileupload1.PostedFile.ContentType == "image/gif" || fileupload1.PostedFile.ContentType == "image/x-png" && fileupload1.PostedFile.ContentLength == 1024)
                {
                    string path = "~/Images/" + fileupload1.FileName;
                    fileupload1.SaveAs(Server.MapPath(path));
                  string getfile=path;
                  SqlCommand cmd = new SqlCommand("sp_insert", con);
                    cmd.CommandType=CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Name",TXT_NAME.Text.Trim());
                    cmd.Parameters.AddWithValue("@Images",getfile);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    lbl_text.Text="Image upload successfull";
                    con.Close();
                }
            }
            }
                   catch(Exception ex)
            {
                   lbl_text.Text=ex.Message;


                   }
}
}
}


i hope you understand this article
Happy coding.........

Thursday, 14 November 2013

Captcha Image

In this article i would like to explain about captcha image code here
Right click on solution Explorer add new item
Code in .aspx pge:

<h1 align="center">captcha image</h1>
    <table align="center">
<tr>
<td>Prove You are not a robot:</td>
<td>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="txtrobocomp" runat="server"  Font-Names="Vivaldi" 
                        Font-Size="X-Large" Font-Bold="True" BackColor="#CC99FF" ForeColor="#CC0066" 
                        Width="148px" Height="33px"></asp:TextBox></td>
<td>
            <asp:ImageButton ID="ImageButton1" runat="server" 
                ImageUrl="~/images/14635845-recycling-reload-white-transparent-and-glossy-web-interface-icon-with-reflection.jpg" 
                Width="30px" Height="30px" AlternateText="refresh" 
                onclick="ImageButton1_Click" />
            </td>
<td>
                <asp:ImageButton ID="ImageButton2" runat="server"  
                    ImageUrl="~/images/download.jpg" Height="30px" Width="30px" 
                    onclick="ImageButton2_Click"/></td>
                    <td>
                        <asp:CompareValidator ID="CompareValidator1" runat="server" 
                            ControlToValidate="TextBox1" ControlToCompare="txtrobocomp" 
                            ErrorMessage="Please enter correct Text" ForeColor="Red"></asp:CompareValidator></td>

            </tr>

            <tr><td colspan="6" align="center">
                <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" 

                    style="height: 26px" /></td></tr></table>

Code in .aspx.cs page: 

Add Namespace for string buider
 using sytem.Text;

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(RandomNumber(10, 99));
                builder.Append(RandomString(3, true));
                builder.Append(RandomString(2, false));
                txtrobocomp.Text = builder.ToString();
            }
        }
        private int RandomNumber(int min, int max)
        {
            Random rd = new Random();
            return rd.Next(min, max);
        }

        private string RandomString(int size, bool lowerCase)

        {
            StringBuilder builder = new StringBuilder();
            Random rd = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rd.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

        {
            StringBuilder builder = new StringBuilder();
            builder.Append(RandomNumber(10, 99));
            builder.Append(RandomString(3, true));
            builder.Append(RandomString(2, false));
            txtrobocomp.Text = builder.ToString();
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)

        {
            SpVoice sp = new SpVoice();
            sp.Volume = 90;
            sp.Speak(txtrobocomp.Text);
         
        }
hope you understand .
In this article we have seen captcha image using asp.net with refresh and speech text.

Wednesday, 13 November 2013

speech recognition

Speech recognition :
This article will explain  how to convert entered text into speech format so here i will explain speech recognition using asp.net.

At first we have to create a single web application and then ->Add New Item in Solution Explorer

and then you have to add reference for speech library which was shown in above

We have to add reference at COM and select Microsoft Speech Object Library and click on Ok.
The speech library is added to our reference
Then at first we have to add namespace like using SpeechLib;
create an object of spvoice class in .aspx page.
 <table>
<tr>
<td>Type your Text:</td>
<td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
    <td><asp:ImageButton ID="ImageButton2" ImageUrl="~/images/download.jpg" 
            AlternateText="sppech" runat="server" Height="25px" Width="25px" 
            onclick="ImageButton2_Click" /></td>
</tr>
</table>
Write below code in.aspx.cs page in a button click event
 protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            SpVoice sp = new SpVoice();
            sp.Volume = 100; 
                sp.Speak(TextBox1.Text);
        }

write some text in textboxand then click on image button  to convert text into speech converter.
I hope you  understand the concept of speech recognition.

Saturday, 13 July 2013

How to upload images using file upload control in asp.net

Here how to upload images usig fileupload control

In aspx page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1 align="center" style="color: #FF00FF">File Upload Demo</h1>
    <table align="center"><tr><td>
        <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label></td>
       <td><asp:TextBox  ID="TXT_NAME" runat="server"></asp:TextBox></td></tr>
       <tr><td>Image:</td><td><asp:FileUpload ID="fileupload1" runat="server" /></td></tr>
       <tr><td>
           <asp:Image ID="Image1" runat="server" Height="182px" Width="172px" /></td></tr>
       <tr><td colspan="2" align="center">
           <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /></td></tr>
        </table>
    </div>
    </form>
</body>
</html>

In aspx.cs page:

 protected void Button1_Click(object sender, EventArgs e)
    {
     
        if (fileupload1.HasFile)
        {
            if (fileupload1.PostedFile.ContentType == "image/jpeg" || fileupload1.PostedFile.ContentType == "image/gif" || fileupload1.PostedFile.ContentType == "image/x-png" && fileupload1.PostedFile.ContentLength == 1024)
            {
                string path = "~/Images/" + fileupload1.FileName;
                fileupload1.SaveAs(Server.MapPath(path));


                Image1.ImageUrl = "~/Images/" + fileupload1.FileName;
                Image1.Visible = true;
            }
Output:





Tuesday, 9 July 2013

How to send an Email using asp.net?


Sending mail from asp.net:

   When we are working with mail system we need to have SMTP server, SMTP server will request from web site and will deliver the mail request to other SMTP servers associated with other websites.


Here iis and smtp are servers.when ever any SMTP server will be seen any mail msg then it will send the request of that mail to the web site.
So at the time of sending a mail we need to set our web site as client to the SMTP server prepare a mail msg
and send to smtp server.

To perform this we use three namespaces in asp.net
                     1)using system.net;
                     2)using system.net.mail;
                     3)using system.web.mail;

System.Net:
                         This namespace contains an important class known as network credentials.

System.Net.Mail:
                  
                       classes available in the namespaces are
                               1. Attachment
                               2.Mail Address.  
                               3.SMTP client
                               4.SMTP Exception
                               5.SMTP failed recipient exception
                               6.SMTP permission
System.Web.Mail:
                             Classes available in the namespaces are             
                          Mail Attachment
                           Mail message
                           SMTP Mail.     

By using this we can write a code
Source Code:

<body>
    <form id="form1" runat="server">
    <div>
    <h1 align="center">Sending an Email</h1>
    <table align="center">
    <tr><td>To:</td><td><asp:TextBox ID="txt1_to" runat="server"></asp:TextBox></td></tr>
     
    <tr><td>subject:</td><td><asp:TextBox ID="txt_sub" runat="server"></asp:TextBox></td></tr>
     
      <tr><td>Body:</td><td><asp:TextBox ID="txt_body" runat="server"></asp:TextBox></td></tr>
     
      <tr><td>Attachment:</td><td><asp:FileUpload ID="fle1" runat="server" /></td></tr>
     
       <tr><td colspan="2" align="center"><asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" /></td></tr>
        </table>
    </div>
    </form>
</body>
</html>
Code Behind:
in an button click event

 protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage msg = new MailMessage("aswinialuri@gmail.com", txt1_to.Text);
       
        msg.IsBodyHtml = true;
        msg.Subject=txt_sub.Text.ToString();
        msg.Body=txt_body.Text.ToString();
        if(fle1.HasFile)
        {
            msg.Attachments.Add(new Attachment(fle1.PostedFile.InputStream, fle1.FileName));
        }
        NetworkCredential nc = new NetworkCredential("aswinialuri@gmail.com", "yourpwd@");
        SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
        smtp.EnableSsl = true;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = nc;
        smtp.Send(msg);
    }