Tuesday, June 12, 2012

Temporary Table Concept In SQL Server

Introduction


This article covers the concept of temporary tables and tables variables in SQL server database.




Temporary Tables


Lets take a look at a simple CREATE TABLE statement that is going to create a temporary table:



CREATE TABLE #Yaks (
YakID int,
YakName char(30) )

You'll notice I prefixed the table with a pound sign (#). This tells SQL Server that this table is a local temporary table. This table is only visible to this session of SQL Server. When I close this session, the table will be automatically dropped. You can treat this table just like any other table with a few exceptions. The only real major one is that you can't have foreign key constraints on a temporary table.

Points to consider while designing database

SQL Server DO's and DON'Ts



DO know your tools.


Please, don't underestimate this tip. This is the best of all of those you'll see in this article. You'd be surprised of how many SQL Server programmers don't even know all T-SQL commands and all of those effective tools SQL Server has.


"What? I need to spend a month learning all those SQL commands I'll never use???" you might say. No, you don't need to. But spend a weekend at MSDN and browse through all T-SQL commands: the mission here is to learn a lot of what can and what can't be done. And, in the future, when designing a query, you'll remember "Hey, there's this command that does exactly what I need", and then you'll refer again to MSDN to see its exact syntax.


In this article I'll assume that you already know the T-SQL syntax or can find about it on MSDN.

SQL Tuning or SQL Optimization

SQL Tuning or SQL Optimization


Sql Statements are used to retrieve data from the database. We can get same results by writing different sql queries. But use of the best query is important when performance is considered. So you need to sql query tuning based on the requirement. Here is the list of queries which we use reqularly and how these sql queries can be optimized for better performance.


 Following are some of the techniques that i remember now to optimize the SQL :--


1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.


For Example: Write the query as


SELECT id, first_name, last_name, age, subject FROM student_details;


Instead of:


SELECT * FROM student_details;

Store and Retrieve Images in Sql Server ASP.NET

Intruduction

In this article i am going to write that how to store and retrieve images in our Sql Server Database.Let us start off by first creating a sample database and adding a table to it. We will call the database ‘Employee’ and the table will be called ‘EmpDetails’. This table will contain an image column along with some other columns. Run the following script in your SQL 2005 Query window (or server explorer) to construct the database and the table.
Database Script

CREATE DATABASE [Employee]

GO

USE [Employee]

GO

CREATE TABLE EmpDetails

(

empid int IDENTITY NOT NULL,

empname varchar(20),

empimg image

)


Step 1: Create a new asp.net website. In the code-behind, add the following namespace

C#

using System.Data.SqlClient;


VB.NET

Imports System.Data.SqlClient


Step 2: Drag and drop two label and one textbox control. Also drag drop a FileUpload control and a button control to upload the selected image on button click. As mentioned earlier, there are no validations performed. The source would look similar to the following:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Save Retrieve Images</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

   

        <asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>

&nbsp;&nbsp;&nbsp;&nbsp;

        <asp:TextBox ID="txtEName" runat="server"></asp:TextBox>

        <br />

        <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>

&nbsp;&nbsp;&nbsp;&nbsp;

        <asp:FileUpload ID="imgUpload" runat="server" />

        <br />

        <br />

        <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"

            Text="Submit" />

   

    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp        <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>

    <br />

    <hr />

     <asp:Image ID="Image1" style="width:200px" Runat="server" />  

    </div>

    </form>

</body>

</html>


Step 3: In the button click event, add the following code:

 C#


protected void btnSubmit_Click(object sender, EventArgs e)

    {

        SqlConnection connection = null;

        try

        {

            FileUpload img = (FileUpload)imgUpload;

            Byte[] imgByte = null;

            if (img.HasFile && img.PostedFile != null)

            {

                //To create a PostedFile

                HttpPostedFile File = imgUpload.PostedFile;

                //Create byte Array with file len

                imgByte = new Byte[File.ContentLength];

                //force the control to load data in array

                File.InputStream.Read(imgByte, 0, File.ContentLength);

            }

            // Insert the employee name and image into db

string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;

            connection = new SqlConnection(conn);


            connection.Open();

string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";

            SqlCommand cmd = new SqlCommand(sql, connection);

            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());

            cmd.Parameters.AddWithValue("@eimg", imgByte);

            int id = Convert.ToInt32(cmd.ExecuteScalar());

            lblResult.Text = String.Format("Employee ID is {0}", id);

        }

        catch

        {

            lblResult.Text = "There was an error";

        }

        finally

        {

            connection.Close();

        }


    }



VB.NET


Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

        Dim connection As SqlConnection = Nothing

        Try

            Dim img As FileUpload = CType(imgUpload, FileUpload)

            Dim imgByte As Byte() = Nothing

            If img.HasFile AndAlso Not img.PostedFile Is Nothing Then

                'To create a PostedFile

                Dim File As HttpPostedFile = imgUpload.PostedFile

                'Create byte Array with file len

                imgByte = New Byte(File.ContentLength - 1) {}

                'force the control to load data in array

                File.InputStream.Read(imgByte, 0, File.ContentLength)

            End If

            ' Insert the employee name and image into db

            Dim conn As String = ConfigurationManager.ConnectionStrings("EmployeeConnString").ConnectionString

            connection = New SqlConnection(conn)


            connection.Open()

            Dim sql As String = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY"

            Dim cmd As SqlCommand = New SqlCommand(sql, connection)

            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim())

            cmd.Parameters.AddWithValue("@eimg", imgByte)

            Dim id As Integer = Convert.ToInt32(cmd.ExecuteScalar())

            lblResult.Text = String.Format("Employee ID is {0}", id)

        Catch

            lblResult.Text = "There was an error"

        Finally

            connection.Close()

        End Try

    End Sub


                         In the code above, i have created a byte array equal to the length of the file. The byte array will store the image. Then load the image data into the array. The record containing the Employee Name and Image is then inserted into the database using the ADO.NET code. The ID inserted is returned back using the @@Identity. We will shortly use this ID and pass it as a query string parameter to the ShowImage handler. The image will then be fetched against the EmployeeID (empid).


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 > ShowImage.ashx. The code shown below, uses the Request.QueryString[“id”] to retrieve the EmployeeID from it. The ID is then passed to the ‘ShowEmpImage()’ method where the image is fetched from the database and returned in a MemoryStream object. We then read the stream into a byte array. Using the OutputStream.Write(), we write the sequence of bytes to the current stream and you get to see your image.

C#


<%@ WebHandler Language="C#" Class="ShowImage" %>


using System;

using System.Configuration;

using System.Web;

using System.IO;

using System.Data;

using System.Data.SqlClient;


public class ShowImage : IHttpHandler

{

    public void ProcessRequest(HttpContext context)

    {

       Int32 empno;

       if (context.Request.QueryString["id"] != null)

            empno = Convert.ToInt32(context.Request.QueryString["id"]);

       else

            throw new ArgumentException("No parameter specified");


       context.Response.ContentType = "image/jpeg";

       Stream strm = ShowEmpImage(empno);

       byte[] buffer = new byte[4096];

       int byteSeq = strm.Read(buffer, 0, 4096);


       while (byteSeq > 0)

       {

           context.Response.OutputStream.Write(buffer, 0, byteSeq);

           byteSeq = strm.Read(buffer, 0, 4096);

       }       

       //context.Response.BinaryWrite(buffer);

    }


    public Stream ShowEmpImage(int empno)

    {

 string conn = ConfigurationManager.ConnectionStrings     ["EmployeeConnString"].ConnectionString;

        SqlConnection connection = new SqlConnection(conn);

        string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";

        SqlCommand cmd = new SqlCommand(sql,connection);

        cmd.CommandType = CommandType.Text;

        cmd.Parameters.AddWithValue("@ID", empno);

        connection.Open();

        object img = cmd.ExecuteScalar();

        try

        {

            return new MemoryStream((byte[])img);

        }

        catch

        {

            return null;

        }

        finally

        {

            connection.Close();

        }

    }


    public bool IsReusable

    {

        get

        {

            return false;

        }

    }



}


VB.NET

<%@ WebHandler Language="vb" Class="ShowImage" %>


Imports System

Imports System.Configuration

Imports System.Web

Imports System.IO

Imports System.Data

Imports System.Data.SqlClient


Public Class ShowImage

    Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim empno As Int32

        If Not context.Request.QueryString("id") Is Nothing Then

            empno = Convert.ToInt32(context.Request.QueryString("id"))

        Else

            Throw New ArgumentException("No parameter specified")

        End If


        context.Response.ContentType = "image/jpeg"

        Dim strm As Stream = ShowEmpImage(empno)

        Dim buffer As Byte() = New Byte(4095) {}

        Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)


        Do While byteSeq > 0

            context.Response.OutputStream.Write(buffer, 0, byteSeq)

            byteSeq = strm.Read(buffer, 0, 4096)

        Loop

        'context.Response.BinaryWrite(buffer);

    End Sub


    Public Function ShowEmpImage(ByVal empno As Integer) As Stream

        Dim conn As String = ConfigurationManager.ConnectionStrings("EmployeeConnString").ConnectionString

        Dim connection As SqlConnection = New SqlConnection(conn)

        Dim sql As String = "SELECT empimg FROM EmpDetails WHERE empid = @ID"

        Dim cmd As SqlCommand = New SqlCommand(sql, connection)

        cmd.CommandType = CommandType.Text

        cmd.Parameters.AddWithValue("@ID", empno)

        connection.Open()

        Dim img As Object = cmd.ExecuteScalar()

        Try

            Return New MemoryStream(CType(img, Byte()))

        Catch

            Return Nothing

        Finally

            connection.Close()

        End Try

    End Function


    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable

        Get

            Return False

        End Get

    End Property


End Class


Step 5: One final step. Add the following code in the button click (just above the catch block) to call the handler and display the newly inserted image from the database. In the code below, we pass the EmployeeID as a query string parameter to the Http Handler.


C#

// Display the image from the database

Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

VB.NET

' Display the image from the database

 Image1.ImageUrl = "~/ShowImage.ashx?id=" & id

That’s it. Run the code and check out the functionality. Just change the connection string in the web.config to point to your database. The code works fine for .jpg, .gif and .bmp images. I would encourage you to extend the sample and include validations in it. Some validations could be to check the size of the image uploaded, make sure that only images are uploaded, check the length of the Employee name, prevent the user from entering numeric and special characters, so on and so forth.



                   I hope this article was useful and I thank you for viewing it.If you like this post , i request you to rate this article.

3 Tier Architecture in C# .NET

Introduction


Here in this article, I would like to cover the typical three layer architecture in C# .NET. It is a very useful approach for coding due to easy code maintenance.

Overview


First let me give you a small overview about the topic I would like to cover in this article.

  1. Tier vs. Layer

  2. Three Tier/Layer Architecture Design Components

  3. Demo: Three Layer Windows Application in C#.NET


1. Tier vs. Layer


1.1 Tier: Tier indicates a physical separation of components, which may mean different assemblies such as DLL, EXE, etc. on the same server or multiple servers.



As you can see in the above figure, Data Tier have no direction with Presentation Tier, but there is an intermediate Tier called Business Tier which is mainly responsible to pass the data from Data Tier to Presentation Tier and to add defined business logic to Data.

So, if we separate each Tier by its functionality, then we come to know the below conclusion:



1.2 Layer: Layer indicates logical separation of components, such as having distinct namespaces and classes for the Database Access Layer, Business Logic Layer and User Interface Layer.


2. Three Tier/Layer Architecture Design Components


As we have already seen, tier is the sum of all the physical components. We can separate the three tiers as Data Tier, Business Tier and Presentation Tier.



  • Data Tier is basically the server which stores all the application’s data. Data tier contents Database Tables, XML Files and other means of storing Application Data.

  • Business Tier is mainly working as the bridge between Data Tier and Presentation Tier. All the Data passes through the Business Tier before passing to the presentation Tier. Business Tier is the sum of Business Logic Layer, Data Access Layer and Value Object and other components used to add business logic.

  • Presentation Tier is the tier in which the users interact with an application. Presentation Tier contents Shared UI code, Code Behind and Designers used to represent information to user.




The above figure is a mixture of Three Tier and Three Layer Architecture. Here, we can clearly see a different between Tier and Layer. Since each component is independent of each other, they are easily maintainable without changing the whole code.

This approach is really very important when several developers are working on the same project and some module needs to be re-used in another project. In a way, we can distribute work among developers and also maintain it in the future without much problems.

Testing is also a very important issue for Architecture when we are considering writing a test case for the project. Since it’s like a modular architecture, it’s very handy testing each module and to trace out bugs without going through the entire code.

3. Demo: 3 Layer Windows Application in C#.NET




Let’s go though from one module to other to have a better understanding of it.

dbConnection


This class is mainly used to do the database activity like Select, Update and Delete query to database. It also checks if the database connection is open or not. If database connection is not open, then it opens the connection and performs the database query. The database results are to be received and being passing in Data Table in this class.

This class takes the database setting from the app.config file so it’s really flexible to manage the database settings.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace ThreeLayerDemo.Core
{
public class dbConnection
{
private SqlDataAdapter myAdapter;
private SqlConnection conn;

/// <constructor>
/// Initialise Connection
/// </constructor>
public dbConnection()
{
myAdapter = new SqlDataAdapter();
conn = new SqlConnection(ConfigurationManager.ConnectionStrings
["dbConnectionString"].ConnectionString);
}

/// <method>
/// Open Database Connection if Closed or Broken
/// </method>
private SqlConnection openConnection()
{
if (conn.State == ConnectionState.Closed || conn.State ==
ConnectionState.Broken)
{
conn.Open();
}
return conn;
}

/// <method>
/// Select Query
/// </method>
public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
DataTable dataTable = new DataTable();
dataTable = null;
DataSet ds = new DataSet();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myCommand.ExecuteNonQuery();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(ds);
dataTable = ds.Tables[0];
}
catch (SqlException e)
{
Console.Write("Error - Connection.executeSelectQuery - Query:
" + _query + " nException: " + e.StackTrace.ToString());
return null;
}
finally
{

}
return dataTable;
}

/// <method>
/// Insert Query
/// </method>
public bool executeInsertQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myAdapter.InsertCommand = myCommand;
myCommand.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.Write("Error - Connection.executeInsertQuery - Query:
" + _query + " nException: n" + e.StackTrace.ToString());
return false;
}
finally
{
}
return true;
}

/// <method>
/// Update Query
/// </method>
public bool executeUpdateQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myAdapter.UpdateCommand = myCommand;
myCommand.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.Write("Error - Connection.executeUpdateQuery - Query:
" + _query + " nException: " + e.StackTrace.ToString());
return false;
}
finally
{
}
return true;
}
}
}

Database Access Layer


Database Access Layer (DAO) builds the query based on received parameters from the Business Logic Layer and passes it the dbConnection class for execution. And simple return results from the dbConnection class to Business Logic Layer.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ThreeLayerDemo.Core
{
public class UserDAO
{
private dbConnection conn;

/// <constructor>
/// Constructor UserDAO
/// </constructor>
public UserDAO()
{
conn = new dbConnection();
}

/// <method>
/// Get User Email By Firstname or Lastname and return DataTable
/// </method>
public DataTable searchByName(string _username)
{
string query = string.Format("select * from [t01_user]
where t01_firstname like @t01_firstname or t01_lastname
like @t01_lastname ");
SqlParameter[] sqlParameters = new SqlParameter[2];
sqlParameters[0] = new SqlParameter("@t01_firstname", SqlDbType.VarChar);
sqlParameters[0].Value = Convert.ToString(_username);
sqlParameters[1] = new SqlParameter("@t01_lastname", SqlDbType.VarChar);
sqlParameters[1].Value = Convert.ToString(_username);
return conn.executeSelectQuery(query, sqlParameters);
}

/// <method>
/// Get User Email By Id and return DataTable
/// </method>
public DataTable searchById(string _id)
{
string query = "select * from [t01_id] where t01_id = @t01_id";
SqlParameter[] sqlParameters = new SqlParameter[1];
sqlParameters[0] = new SqlParameter("@t01_id", SqlDbType.VarChar);
sqlParameters[0].Value = Convert.ToString(_id);
return conn.executeSelectQuery(query, sqlParameters);
}
}
}

Value Object


Value Object is nothing more but a class with the contents GET and SET methods. It’s mainly used to pass Data from one class to another. It’s directly connected with Business Logic Layer and Presentation Layer. As you can see in the diagram object values are being SET in Business Logic Layer and GET from Presentation Layer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThreeLayerDemo.Core
{
public class UserVO
{
private int _idUser;
private string _firstname;
private string _lastname;
private string _email;

/// <constructor>
/// Constructor UserVO
/// </constructor>
public UserVO()
{
//
// TODO: Add constructor logic here
//
}

public int idUser
{
get
{
return _idUser;
}

set
{
_idUser = value;
}
}

public string firstname
{
get
{
return _firstname;
}

set
{
_firstname = value;
}
}

public string lastname
{
get
{
return _lastname;
}
set
{
_lastname = value;
}
}

public string email
{
get
{
return _email;
}

set
{
_email = value;
}
}
}
}

Business Logic Layer


Business Logic Layer (BUS) works as a bridge between Presentation Layer and DAO. All the user values received from the presentation layer are being passed to BUS. The results received from the DAO are in row data in Data Table format but in BUS it’s converting into Value Objects (VO). Business Logic Layer (BUS) is the most important class in the whole architecture because it mainly contains all the business logic of the program. Whenever a user wants to update the business logic of the program only need to update this class.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ThreeLayerDemo.Core
{
/// <summary>
/// Summary description for UserBUS
/// </summary>
public class UserBUS
{
private UserDAO _userDAO;

/// <constructor>
/// Constructor UserBUS
/// </constructor>
public UserBUS()
{
_userDAO = new UserDAO();
}

/// <method>
/// Get User Email By Firstname or Lastname and return VO
/// </method>
public UserVO getUserEmailByName(string name)
{
UserVO userVO = new UserVO();
DataTable dataTable = new DataTable();

dataTable = _userDAO.searchByName(name);

foreach (DataRow dr in dataTable.Rows)
{
userVO.idUser = Int32.Parse(dr["t01_id"].ToString());
userVO.firstname = dr["t01_firstname"].ToString();
userVO.lastname = dr["t01_lastname"].ToString();
userVO.email = dr["t01_email"].ToString();
}
return userVO;
}

/// <method>
/// Get User Email By Id and return DataTable
/// </method>
public UserVO getUserById(string _id)
{
UserVO userVO = new UserVO();
DataTable dataTable = new DataTable();
dataTable = _userDAO.searchById(_id);

foreach (DataRow dr in dataTable.Rows)
{
userVO.idUser = Int32.Parse(dr["t01_id"].ToString());
userVO.firstname = dr["t01_firstname"].ToString();
userVO.lastname = dr["t01_lastname"].ToString();
userVO.email = dr["t01_email"].ToString();
}
return userVO;
}
}
}

Presentation Layer


Presentation Layer is the only layer which is directly connected with the user. So in this matter, it’s also a really important layer for marketing purposes. Presentation Layer is mainly used for getting user data and then passing it to Business Logic Layer for further procedure, and when data is received in Value Object then it’s responsible to represent value object in the appropriate form which user can understand.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ThreeLayerDemo.Core;

namespace ThreeLayerDemo
{
public partial class frmLogin : Form
{
private UserBUS _userBUS;

public frmLogin()
{
InitializeComponent();
_userBUS = new UserBUS();
}

private void btnSearch_Click(object sender, EventArgs e)
{
UserVO _userVO = new UserVO();
_userVO = _userBUS.getUserEmailByName(txtUsername.Text);
if (_userVO.email == null)
MessageBox.Show("No Match Found!", "Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else
MessageBox.Show(_userVO.email ,"Result",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}

private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}

Summary


Hope this explanation briefs the beginner specially looking for a generic approach. There are also some methods which are far better than the architecture described above, mostly with skipping Database Access Layer and Value Object Class, and making it dynamically which is really handy for maintenance in case of frequent database change. I will try to post some in the near future.