Friday, 13 September 2013

FileUpload Save Images In Database In ASP.NET

This example explains how to Save Images In Sqlserver Database In Asp.Net Using File Upload Control.
I am Uploading Images using FileUpload Control and saving or storing them in SQL Server database in ASP.NET with C# and VB.NET.
FileUpload Save Images In Database In ASP.NET

Database is having a table named Images with three columns.
1. ID Numeric Primary key with Identity Increment.
2. ImageName Varchar to store Name of picture.
3. Image column to store image in binary format. 

After uploading and saving images in database, pics are displayed in GridView.


To know how to display images in gridview from database, read my post mentioned below
Display Images In GridView From DataBase in ASP.NET C# VB.NET

Html markup of the page look like
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server" Width="95px">
</asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Label ID="lblMessage" runat="server">
</asp:Label>
<asp:Button ID="btnUpload" runat="server" 
            OnClick="btnUpload_Click" Text="Upload"/>
</div>
</form>

Write this code in Click Event of Upload Button

C# Code behind

01protected void btnUpload_Click(object sender, EventArgs e)
02{
03 string strImageName = txtName.Text.ToString();
04 if (FileUpload1.PostedFile != null &&
05     FileUpload1.PostedFile.FileName != "")
06  {
07   byte[] imageSize = new byte
08                 [FileUpload1.PostedFile.ContentLength];
09  HttpPostedFile uploadedImage = FileUpload1.PostedFile;
10  uploadedImage.InputStream.Read
11     (imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
12 
13 // Create SQL Connection
14  SqlConnection con = new SqlConnection();
15  con.ConnectionString = ConfigurationManager.ConnectionStrings
16                         ["ConnectionString"].ConnectionString;
17 
18 // Create SQL Command
19 
20 SqlCommand cmd = new SqlCommand();
21 cmd.CommandText = "INSERT INTO Images(ImageName,Image)" +
22                   " VALUES (@ImageName,@Image)";
23 cmd.CommandType = CommandType.Text;
24 cmd.Connection = con;
25 
26 SqlParameter ImageName = new SqlParameter
27                     ("@ImageName", SqlDbType.VarChar, 50);
28 ImageName.Value = strImageName.ToString();
29 cmd.Parameters.Add(ImageName);
30 
31 SqlParameter UploadedImage = new SqlParameter
32               ("@Image", SqlDbType.Image, imageSize.Length);
33 UploadedImage.Value = imageSize;
34 cmd.Parameters.Add(UploadedImage);
35 con.Open();
36 int result = cmd.ExecuteNonQuery();
37 con.Close();
38 if (result > 0)
39 lblMessage.Text = "File Uploaded";
40 GridView1.DataBind();
41 }
42}

Hover Effects for GridView Rows Using CSS

The GridView HTML Code

The HTML code for the GridView in this article will looks like:
<asp:GridView ID="gvHover" BackColor="WhiteSmoke" runat="server" AutoGenerateColumns="False"
              GridLines="Vertical" CssClass="grid-view" OnRowCreated="gvHover_RowCreated">
   <Columns>
      <asp:BoundField HeaderText="n" DataField="n">
         <HeaderStyle Width="25px" />
         <ItemStyle Width="25px" />
      </asp:BoundField>
      <asp:BoundField HeaderText="sqrt(n)" DataField="sqrtn">
         <HeaderStyle Width="150px" />
         <ItemStyle Width="150px" />
      </asp:BoundField>
      <asp:BoundField HeaderText="qbrt(n)" DataField="qbrtn">
         <HeaderStyle Width="150px" />
         <ItemStyle Width="150px" />
      </asp:BoundField>
   </Columns>
</asp:GridView>

Styling the GridView

In order to style the Gridview, attach a CSS class to it, like so:
<asp:GridView ... CssClass="grid-view" ... > ... </asp:GridView>

Styling the GridView’s Header Row, Normal Row, and Alternate Row

In order to style the GridWiew’s header, normal, and alternate rows, attach the CSS classes to these rows through theRowCreated event of the GridView, as:
//Add CSS class on header row.
if (e.Row.RowType == DataControlRowType.Header)
   e.Row.CssClass = "header";

//Add CSS class on normal row.
if (e.Row.RowType == DataControlRowType.DataRow && 
          e.Row.RowState == DataControlRowState.Normal)
   e.Row.CssClass = "normal";

//Add CSS class on alternate row.
if (e.Row.RowType == DataControlRowType.DataRow && 
          e.Row.RowState == DataControlRowState.Alternate)
   e.Row.CssClass = "alternate";

The CSS Classes

Below are the CSS classes that have been used above to style the GridView and its header, normal, and alternate rows:
.grid-view
{
   padding: 0;
   margin: 0;
   border: 1px solid #333;
   font-family: "Verdana, Arial, Helvetica, sans-serif, Trebuchet MS";
   font-size: 0.9em;
}

.grid-view tr.header
{
   color: white;
   background-color: #FF5600;
   height: 25px;
   vertical-align: middle;
   text-align: center;
   font-weight: bold;
}

.grid-view tr.normal
{
   color: black;
   background-color: #FDC64E;
   height: 25px;
   vertical-align: middle;
   text-align: center;
}

.grid-view tr.alternate
{
   color: black;
   background-color: #D59200;
   height: 25px;
   vertical-align: middle;
   text-align: center;
}

Adding a Hover Effect to the GridView rows

Finally, to apply the hover effect to the GridView rows, the following CSS is used:
.grid-view tr.normal:hover, .grid-view tr.alternate:hover
{
   background-color: white;
   color: black;
   font-weight: bold;
}
Note that the hover effect has been applied to the normal and alternate rows only, not on the header row. You can also use different color schemes for the normal and alternate rows separately, for the hover effect.

Using the CSS Classes

Put all the corresponding CSS classes in a stylesheet and give its reference on the web page’s head section, as:
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />

Saturday, 17 August 2013

suggestion in textbox in asp.net

 <td>
    <asp:TextBox ID="TextBox1" runat="server" ForeColor="Black" AutoPostBack="True"></asp:TextBox>
    <asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
        CompletionInterval="10" DelimiterCharacters="" Enabled="True"
        MinimumPrefixLength="1" ServicePath="" TargetControlID="TextBox1"
        UseContextKey="True" ServiceMethod="GetCompletionList">
    </asp:AutoCompleteExtender>
    </td>


 [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
       
        public static string[] GetCompletionList(string prefixText, int count, string contextKey)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from Patient_master Where Patient_Code LIKE '" + prefixText + "%' order by Patient_Code", con);
            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            List<string> li = new List<string>();
            while (dr.Read())
            {
                li.Add(dr["Patient_Code"].ToString());
            }
            return li.ToArray();
        }

Friday, 2 August 2013

Trigger

What is a Trigger

A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or updation of data. It is a database object which is bound to a table and is executed automatically. You can’t explicitly invoke triggers. The only way to do this is by performing the required action no the table that they are assigned to.

Types Of Triggers

There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three types of triggers and hybrids that come from mixing and matching the events and timings that fire them.

Basically, triggers are classified into two main types:- 

(i) After Triggers (For Triggers) 
(ii) Instead Of Triggers 

(i) After Triggers

These triggers run after an insert, update or delete on a table. They are not supported for views. 
AFTER TRIGGERS can be classified further into three types as: 

(a) AFTER INSERT Trigger. 
(b) AFTER UPDATE Trigger. 
(c) AFTER DELETE Trigger. 

Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on this table, I will be attaching several triggers. 

CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);

I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into another audit table. The main purpose of this audit table is to record the changes in the main table. This can be thought of as a generic audit trigger. 

Now, create the audit table as:-
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)

(a) AFTRE INSERT Trigger

This trigger is fired after an INSERT on the table. Let’s create the trigger as:-
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test] 
FOR INSERT
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=i.Emp_ID from inserted i; 
 select @empname=i.Emp_Name from inserted i; 
 select @empsal=i.Emp_Sal from inserted i; 
 set @audit_action='Inserted Record -- After Insert Trigger.';

 insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER INSERT trigger fired.'
GO
The CREATE TRIGGER statement is used to create the trigger. THE ON clause specifies the table name on which the trigger is to be attached. The FOR INSERT specifies that this is an AFTER INSERT trigger. In place of FOR INSERT, AFTER INSERT can be used. Both of them mean the same. 
In the trigger body, table named inserted has been used. This table is a logical table and contains the row that has been inserted. I have selected the fields from the logical inserted table from the row that has been inserted into different variables, and finally inserted those values into the Audit table. 
To see the newly created trigger in action, lets insert a row into the main table as : 
 insert into Employee_Test values('Chris',1500);

Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached to this table has inserted the record into the Employee_Test_Audit as:-
6   Chris  1500.00   Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700

(b) AFTER UPDATE Trigger

This trigger is fired after an update on the table. Let’s create the trigger as:-
CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test] 
FOR UPDATE
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=i.Emp_ID from inserted i; 
 select @empname=i.Emp_Name from inserted i; 
 select @empsal=i.Emp_Sal from inserted i; 
 
 if update(Emp_Name)
  set @audit_action='Updated Record -- After Update Trigger.';
 if update(Emp_Sal)
  set @audit_action='Updated Record -- After Update Trigger.';

 insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER UPDATE Trigger fired.'
GO
The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table. There is no logical table updated like the logical table inserted. We can obtain the updated value of a field from theupdate(column_name) function. In our trigger, we have used, if update(Emp_Name) to check if the column Emp_Name has been updated. We have similarly checked the column Emp_Sal for an update. 
Let’s update a record column and see what happens. 
 update Employee_Test set Emp_Sal=1550 where Emp_ID=6
This inserts the row into the audit table as:- 
6  Chris  1550.00  Updated Record -- After Update Trigger.   2008-04-26 12:38:11.843 

(c) AFTER DELETE Trigger

This trigger is fired after a delete on the table. Let’s create the trigger as:- 
CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test] 
AFTER DELETE
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=d.Emp_ID from deleted d; 
 select @empname=d.Emp_Name from deleted d; 
 select @empsal=d.Emp_Sal from deleted d; 
 set @audit_action='Deleted -- After Delete Trigger.';

 insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER DELETE TRIGGER fired.'
GO
In this trigger, the deleted record’s data is picked from the logical deleted table and inserted into the audit table. 
Let’s fire a delete on the main table. 
A record has been inserted into the audit table as:- 
 6  Chris 1550.00  Deleted -- After Delete Trigger.  2008-04-26 12:52:13.867 
All the triggers can be enabled/disabled on the table using the statement 
ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL 
Specific Triggers can be enabled or disabled as :- 
ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete

This disables the After Delete Trigger named trgAfterDelete on the specified table. 

(ii) Instead Of Triggers

These can be used as an interceptor for anything that anyonr tried to do on our table or view. If you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and they will not actually get deleted (unless you issue another delete instruction from within the trigger)
INSTEAD OF TRIGGERS can be classified further into three types as:- 

(a) INSTEAD OF INSERT Trigger. 
(b) INSTEAD OF UPDATE Trigger. 
(c) INSTEAD OF DELETE Trigger. 

(a) Let’s create an Instead Of Delete Trigger as:-
CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test] 
INSTEAD OF DELETE
AS
 declare @emp_id int;
 declare @emp_name varchar(100);
 declare @emp_sal int;
 
 select @emp_id=d.Emp_ID from deleted d;
 select @emp_name=d.Emp_Name from deleted d;
 select @emp_sal=d.Emp_Sal from deleted d;

 BEGIN
  if(@emp_sal>1200)
  begin
   RAISERROR('Cannot delete where salary > 1200',16,1);
   ROLLBACK;
  end
  else
  begin
   delete from Employee_Test where Emp_ID=@emp_id;
   COMMIT;
   insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
   values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead Of Delete Trigger.',getdate());
   PRINT 'Record Deleted -- Instead Of Delete Trigger.'
  end
 END
GO
This trigger will prevent the deletion of records from the table where Emp_Sal > 1200. If such a record is deleted, the Instead Of Trigger will rollback the transaction, otherwise the transaction will be committed. 
Now, let’s try to delete a record with the Emp_Sal >1200 as:- 

delete from Employee_Test where Emp_ID=4
This will print an error message as defined in the RAISE ERROR statement as:- 

Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfDelete, Line 15
Cannot delete where salary > 1200 

And this record will not be deleted. 
In a similar way, you can code Instead of Insert and Instead Of Update triggers on your tables. 

stored procedure with front end coding

 protected void Button1_Click(object sender, EventArgs e)
        {
            if (TextBox1.Text != "")
            {
                //cmd = new SqlCommand("insert into unitmaster(unitname,description) values(@name,@des)", con);
                //cmd.Parameters.AddWithValue("@name", TextBox1.Text.Trim());
                //cmd.Parameters.AddWithValue("@des", TextBox2.Text.Trim());

                //con.Open();
                //cmd.ExecuteNonQuery();
                //con.Close();

                //TextBox1.Text = string.Empty;
                //TextBox2.Text = string.Empty;

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "insert_unitmaster";
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@unitname", TextBox1.Text.Trim());
                cmd.Parameters.AddWithValue("@description", TextBox2.Text.Trim());
             
                con.Open();
                int x = cmd.ExecuteNonQuery();
                con.Close();
                if (x == 0)
                {

                }
                if (x > 0)
                {
                    Response.Write("<script LANGUAGE='JavaScript' >alert('Insert Successful')</script>");
                }
                showdata();
            }
            else
            {
                Response.Write("Please fill Blood name");
            }
        }















 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //SqlCommand cmd = new SqlCommand("delete from unitmaster where id=@id", con);
            //cmd.Parameters.Add("@id", SqlDbType.BigInt).Value = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
            //con.Open();
            //cmd.ExecuteNonQuery();
            //con.Close();

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "delete_unitmaster";
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@id", Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value));
            con.Open();
            int x = cmd.ExecuteNonQuery();
            con.Close();
            if (x == 0)
            {

            }
            if (x > 0)
            {
                Response.Write("<script LANGUAGE='JavaScript' >alert('Delete Successful')</script>");
            }
            showdata();
        }














 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //SqlCommand cmd = new SqlCommand("update unitmaster set unitname=@name,description=@description where id=@id", con);
            //cmd.Parameters.Add("@id", SqlDbType.BigInt).Value = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

            //cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("ename"))).Text;

            //cmd.Parameters.Add("@description", SqlDbType.VarChar).Value = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("edescription"))).Text;
            ////cmd.Parameters.Add("@status", SqlDbType.NVarChar).Value = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("estatus"))).Text;
            //con.Open();
            //cmd.ExecuteNonQuery();
            //con.Close();
            //GridView1.EditIndex = -1;
            //showdata();

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "update_unitmaster";
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@id", Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value));
            cmd.Parameters.AddWithValue("@unitname",((TextBox)(GridView1.Rows[e.RowIndex].FindControl("ename"))).Text);
            cmd.Parameters.AddWithValue("@description",((TextBox)(GridView1.Rows[e.RowIndex].FindControl("edescription"))).Text);

            con.Open();
            int x = cmd.ExecuteNonQuery();
            con.Close();
            if (x == 0)
            {

            }
            if (x > 0)
            {
                Response.Write("<script LANGUAGE='JavaScript' >alert('Update Successful')</script>");
            }
            GridView1.EditIndex = -1;
            showdata();
        }

     












protected void showdata()
        {
            //DISCONNECTED MODE
           //SqlDataAdapter da =new SqlDataAdapter();
           //da.SelectCommand.CommandText = "select_unitmaster";
           //da.SelectCommand.CommandType = CommandType.StoredProcedure;
           //dt=new DataTable();
           //da.Fill(dt);
           //GridView1.DataSource=dt;
           //GridView1.DataBind();

         
            //CONNECTED MODE
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "select_unitmaster";
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
         
            GridView1.DataSource = cmd.ExecuteReader();
            GridView1.DataBind();
            con.Close();
         
         
        }









USE [hms]
GO

/****** Object:  StoredProcedure [dbo].[insert_unitmaster]    Script Date: 08/02/2013 17:13:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc [dbo].[insert_unitmaster]
(

@unitname varchar(50),
@description nvarchar(300)

)
as
begin

insert into unitmaster(unitname,description)
values(@unitname,@description)

end
GO














USE [hms]
GO

/****** Object:  StoredProcedure [dbo].[update_unitmaster]    Script Date: 08/02/2013 17:14:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc [dbo].[update_unitmaster]
(
@id int,
@unitname varchar(50),
@description nvarchar(300)
)
as
begin
update unitmaster set unitname=@unitname,description=@description where id=@id
end
GO





USE [hms]
GO

/****** Object:  StoredProcedure [dbo].[delete_unitmaster]    Script Date: 08/02/2013 17:14:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc [dbo].[delete_unitmaster]
(
@id int
)
as
begin
delete from unitmaster where id=@id
end
GO



stored procedure insert,update,delete and select in one code

Alter PROCEDURE MasterInsertUpdateDelete ( @id INTEGER, @first_name VARCHAR(10), @last_name VARCHAR(10), @salary DECIMAL(10,2), @city VARCHAR(20), @StatementType nvarchar(20) = '' ) AS BEGIN IF @StatementType = 'Insert' BEGIN insert into employee (id,first_name,last_name,salary,city) values( @id, @first_name, @last_name, @salary, @city) END IF @StatementType = 'Select' BEGIN select * from employee END IF @StatementType = 'Update' BEGIN UPDATE employee SET First_name = @first_name, last_name = @last_name, salary = @salary, city = @city WHERE id = @id END else IF @StatementType = 'Delete' BEGIN DELETE FROM employee WHERE id = @id END end
Now press F5 to execute the stored procedure.
Now open object explorer and select storeprocedure MasterInsertUpdateDelete.
Stored Procedure to Check Insert
StatementType = 'Insert'

stored procedure

create proc insert_departmentmaster

(
@Branch_Code nvarchar(MAX),
@Dept_No nvarchar(MAX),
@Dept_Name nvarchar(MAX)
)
as
begin
insert into DepartmentMaster(Branch_Code,Dept_No,Dept_Name)values(@Branch_Code,@Dept_No,@Dept_Name)
end

create proc delete_departmentmaster
(
@Id bigint
)
as
begin
delete from DepartmentMaster where Id=@Id
end

create proc update_departmentmaster
(
@Id bigint,
@Branch_Code nvarchar(MAX),
@Dept_No nvarchar(MAX),
@Dept_Name nvarchar(MAX)
)
as
begin
update DepartmentMaster set Branch_Code=@Branch_Code,Dept_No=@Dept_No,Dept_Name=@Dept_Name where Id=@Id
end

create proc select_departmentmaster
as
begin
select * from DepartmentMaster
end