Friday 6 September 2013

How to save images in database and retrieve image from database

How to save images in database and retrieve image from database


-Joseph Paul Moonjely
Hello friends
In this article, we will explore how to store images in the database and then display those images along with the other server controls
Today I am going to show how you can save   image from web page to database using asp File Upload Control and retrieve same image . There might be various approaches for this I am going show one of them  

Using handlers : by converting image into binary format




I am going to a build a form, with the person’s details and his photo along with it, or for that case, display the image in an ASP.NET server control along with other controls?

Let us start off by first creating a sample database and adding a table to it. We will call the database and the table will be called ‘Tbl_Emp’

Database structure will be like this

            


Step 1: Create a new asp.net website and add a webpage to it    
Step2: Drag and drop two textbox controls. Also drag drop a File Upload control and two button control to upload the selected image on button click and to retrieve record from database. Dropdown List to select list ID which will be used to retrieve selected record from database
Aspx page code will look like below
<div>
      Enter ID  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
      Enter Name <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
      Enter Pic  <asp:FileUpload ID="FileUpload1" runat="server" /><br />
      <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" /><br >

       <asp:Image ID="Image1"  runat="server" Height="137px" Width="130px" /><br />
       
        <asp:DropDownList ID="TextBox3" runat="server">
        </asp:DropDownList>
       
        <asp:Button ID="Button2" runat="server" Text="Search" onclick="Button2_Click" />

    </div>



Step3: code on .cs page
On my code there are three methods
Filldropdown() : used to fill dropdown
Button1_Click : used to save image into database
Button2_Click : used to retrieve image from database


 static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            filldropdown();
        }
    }

    public void filldropdown()
    {
        SqlCommand cmd = new SqlCommand("Select EmpID from Tbl_Emp", con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        TextBox3.Items.Clear();
        if (dr.HasRows)
        {
            //TextBox3.DataSource = dr["EmpID"].ToString();
            //TextBox3.DataBind();

            while (dr.Read())
            {
                TextBox3.Items.Add(dr["EmpID"].ToString());
            }
        }
        con.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Tbl_Emp values(@id,@name,@image)",con);
        cmd.Parameters.AddWithValue("@id", TextBox1.Text);
        cmd.Parameters.AddWithValue("@name", TextBox2.Text);

        int img = FileUpload1.PostedFile.ContentLength;

        byte[] msdata = new byte[img];

        FileUpload1.PostedFile.InputStream.Read(msdata,0,img);

        cmd.Parameters.AddWithValue("@image", msdata);

        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd.ExecuteNonQuery();

        con.Close();

        filldropdown();

        Response.Write("Data Saved ....");

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("select * from Tbl_Emp where EmpID=@id", con);
        cmd.Parameters.AddWithValue("@id", TextBox3.Text);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows && dr.Read())
        {
            TextBox1.Text = dr["EmpID"].ToString();
            TextBox2.Text = dr["EmpName"].ToString();
            Image1.ImageUrl = "Handler.ashx?EmpID=" + TextBox3.Text;
        }
        else
        {
            Response.Write("Record With This ID Note Found");
        }
      
    }

Step 4: In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > Handler.ashx. The code shown below, uses the Request.QueryString[“id”] to retrieve the EmpID from it. The ID is then passed to  this handler from drop on button 2 click
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;

public class Handler : IHttpHandler {

    static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
   
    public void ProcessRequest (HttpContext context) {
       // context.Response.ContentType = "text/plain";
       // context.Response.Write("Hello World");
        SqlCommand cmd = new SqlCommand("select EmpPic from Tbl_Emp where EmpID=@EmpID",con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd.Parameters.AddWithValue("@EmpID", context.Request.QueryString["EmpID"].ToString());
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.HasRows && dr.Read())
        {
            context.Response.BinaryWrite((byte[])(dr["EmpPic"]));
        }
      
        con.Close();
       
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}



I hope this article was useful 

Friday 19 July 2013

Recursive queries in SQL Server 2008



-          Joseph Paul Moonjely

This is just a small test on recursion using T-SQL.In SQL Server Management Studio, we connect to our local server, we open a new query window and we create a new database for our test.
CREATE DATABASE [RecursionTest]


USE RecursionTest

Next, we create a simple table that links an employee to his direct manager
CREATE TABLE DirectManager
(
  EmployeeId INT,
  DirectManagerId INT NULL
)

and we populate the table with a hierarchy of employee-manager relationships.
DECLARE @counter INT
SET @counter = 2
WHILE @counter < 18
  BEGIN
    INSERT INTO DirectManager (EmployeeId, DirectManagerId)
      VALUES(@counter, @counter / 2)
    SET @counter = @counter + 1
  END

The contents of the table are listed below.
http://www.codiply.com/blog/files/recursive-queries-in-t-sql-001.png
We have a simple hierarchy with each direct manager managing up to 2 employees. We assume that both DirectManagerId and EmployeeId are foreign keys to an Employee table.
Now, we want to find all employees below a certain manager, i.e. the employees managed directly by him/her, the employees they manage and so on. If we think of the relationship manager-employee as parent-child relationship, we want to find all ancestors. To do this we need to use recursion, as we do not know a priori how deep we need to go. For example, if we needed to find all grandchildren we know we need to perform a single self-join to get the answer, or for all grand-grandchildren we need two self-joins. However, in our case we need an arbitrary number of joins.
To perform recursion, we are going to use the WITH keyword to name a temporary set, and within its definition we are going to query the very same temporary set.
We define a set ManagedEmployee that contains an employee that falls under a specific manager. The recursive query always contains three parts
  1. A base query that contains the seed of our query,
  2. a recursive query that references the set we are defining, and
  3. the keyword UNION ALL between the two queries that joins the two sets.
For a given manager with id equal to ManagerId we first find all the employees that he/she is directly managing. Next, we do a join on the result and find the employees that they are managing directly, and then recursion takes over to do the rest.
DECLARE @managerId INT
SET @managerId = 3

;WITH ManagedEmployee(ManagerId, EmployeeId) as
(
    -- Base or anchor query
    SELECT DirectManagerId, EmployeeId
    FROM DirectManager
    WHERE DirectManagerId = @managerId
    UNION ALL
    -- Recursive query
    SELECT me.ManagerId, dm.EmployeeId
    FROM ManagedEmployee AS me
    JOIN DirectManager AS dm
    ON me.EmployeeId = dm.DirectManagerId
    WHERE me.ManagerId = @managerId
)
SELECT * FROM ManagedEmployee ORDER BY EmployeeId
The result we get is the following.
http://www.codiply.com/blog/files/recursive-queries-in-t-sql-002.png
Employee 3 is managing directly employees 6, 7, and they are managing employees 12, 13, 14 and 15. Therefore, they are all under employee 3.
Similarly, to find all the employees managed by employee 2 we just need to change @managerId value in the recursive query above
SET @managerId = 2
and the result we get is
http://www.codiply.com/blog/files/recursive-queries-in-t-sql-003.png
Some final comments (using SQL SERVER 2008):
  1. The keyword WITH RECURSIVE cannot be used in T-SQL to declare explicitly that the set is recursive, we simply use WITH.
  2. It is not possible to use UNION instead of UNION ALL when joining the base query with the recursive query.
  3. It is not possible to perform nonlinear recursion where we perform a join of the recursive set ManagedEmployee on itself within the recursive query.

Sunday 14 July 2013

Crystal Report in Asp.net

Making Of Crystal report

-Joseph Paul Moonjely
Introduction: 

In this article I will explain how to create crystal reports example in asp.net.


Description: 

In Previous posts I explained 
how to install crystal reports in visual studio 2010 and how to create rdlc reports using asp.net and pass parameters to rdlc reports using asp.net. Now I will explain how to create basic crystal reports using asp.net. Crystal Report is standard reporting tool for visual studio by using these we can display reports regarding employee details and display charts etc and crystal reports need minimal coding to display result. 

To implement crystal reports first design the table in database and give name UserInfomation

ColumnName
DataType
UserId
Int(set identity property=true)
UserName
varchar(50)
FirstName
Varchar(50)
LastName
varchar(50)
Location
varchar(50)

After completion of table creation enter some dummy data because we need to use that data to populate reports.

Now Open visual studio and create new website after that right click on your website and select Add new item in that select Crystal Report and click Add
 
After that add crystal report then it will prompt Crystal Report Gallery window in that select blank solution and click OK

A blank report will create in our application now click on CrystalReports menu under that select Database under that select Database Expert
 
After click on Database Expert now Database Expert wizard will open in that select Create New Section>> select OLE DB (ADO) >> in that click on + sign of OLE DB (ADO)

Now select Microsoft OLE DB Provider for SQL Server and click Next (Here we can select SQL Native client option also but sometimes during deployment if servers not contains this native client it will throw error).
 
Now enter SQL Server name, username, password and required database and click Next

After enter credentials for your required database click Next then click Finish (Here for my database I didn’t set any credentials for that reason I didn’t enter userid and password details don’t get confused).

After click Finish now our database loaded in OLEDB (ADO) section >> select your database >> select dbo >> select required tables

Now open tables in that select required table and move to selected tables section and click OK

After that Database Fields in Field Explorer populated with our required data table now drag and drop the required fields from data table to reports Details section

Now open your Default.aspx page drag and drop CrystalReportViewer control from Reporting tab.


Now select CrystalReportViewer and click on smart tag in right hand side and Choose new Report Source

Whenever we click on New report source one window will open in that select crystal report for Report Source from the available reports in dropdownlist and click OK.

After assign available report to CrystalReportViewer control check your code that would be like this

<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Crystal Report Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True"ReportSourceID="CrystalReportSource1" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="CrystalReport.rpt">
</Report>
</CR:CrystalReportSource>
</div>
</form>
</body>
</html>
Now run your application your report will be like this

In case your report prompt window for UserName and password before we access data in that situation we need to set those details in code behind instead of assign crystal report to CrystalReportViewer control

Drag and drop CrystalReportViewer control click on right side smart tag of your CrystalReportViewer control and uncheck EnableDatabaseLogonPrompt

Our aspx code will be like this

<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Crystal Report Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True"ReportSourceID="CrystalReportSource1" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="CrystalReport.rpt">
</Report>
</CR:CrystalReportSource>
</div>
</form>
</body>
</html>
Now Open your code behind file and set database connection settings and assign reports to the control before that first add following namespaces


using System;
using CrystalDecisions.CrystalReports.Engine;
After add namespaces write the following code in page load event

C# code


protected void Page_Load(object sender, EventArgs e)
{
ReportDocument reportdocument = new ReportDocument();
reportdocument.Load(Server.MapPath("CrystalReport.rpt"));
reportdocument.SetDatabaseLogon("username","password","SureshDasari","MySampleDB");
CrystalReportViewer1.ReportSource = reportdocument;
}
VB.NET Code


Imports CrystalDecisions.CrystalReports.Engine

Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
Dim reportdocument As New ReportDocument()
reportdocument.Load(Server.MapPath("CrystalReport.rpt"))
reportdocument.SetDatabaseLogon("""""SureshDasari""MySampleDB")
CrystalReportViewer1.ReportSource = reportdocument
End Sub
End Class
Now run your application and check your output that would be like this