21 November, 2012

User-Defined Data Type (Table)



Creating a Table User-Defined Data Type
Creating a table user-defined data type works as something of a combination of the classic CREATE TYPE and table variable syntax. The tabular CREATE TYPE syntax looks like this:

CREATE TYPE [<schema name>.]<type name>
AS TABLE
(
{<column name><data type>
[ COLLATE <collation name>]
[ NULL | NOT NULL ]
[ DEFAULT <expression>]
[ IDENTITY [ ( <seed>, <increment>)]
[ ROWGUIDCOL ] [<column constraint> [ ...n ] ]
[<table constraint>]}
|<computed column definition>}
)[;]

Long ago, it seemed one address was generally enough for most people. The majority of systems out there stored a single address for most business entities they worked with. Today, however, one doesn’t seem to be enough. Between dealing with companies that have multiple locations, and even individuals deciding to receive bills at one location, but ship to a different location, many business entities we work with have multiple addresses. The AdventureWorks2008 database represents this by separating addresses out into their own table (Person.Address).We’ve decided that we want to represent this notion of an address in a consistent way across our systems, so we create our custom type:

USE AdventureWorks2008;
GO
CREATE TYPE Person.Address
AS TABLE(
AddressID int NULL,
AddressLine1 nvarchar(60) NOT NULL,
AddressLine2 nvarchar(60) NULL,
City nvarchar(30) NOT NULL,
StateProvinceID int NOT NULL,
PostalCode nvarchar(15) NOT NULL,
SpatialLocation geography NULL
);

There are a host of items to notice about this script:
Ø  I used the exact name of an existing object in the database (there is a table called Person.Address). The type can be considered to be much like the difference between a class and an object— that is, a type is a definition, and a table is an actual instance of something (though, the table is not an instance of the type definition the way an object is an instance of a class).
Ø  The syntax for creating the actual definition is very similar to the CREATE TABLE syntax.
Ø  The layout maps very closely to the Person.Address table in order to support moving data between the two relatively easily.

Note that I created my user-defined type with the same name as a table just to prove the point. I would
not recommend duplicating names in practice, as it is likely to lead to far more confusion than it is worth.

Let’s further our example just a bit by utilizing our new type:

DECLARE @Address Person.Address;
INSERT INTO @Address
(AddressID,AddressLine1,City,StateProvinceID,PostalCode) VALUES
(1,‘My first address’,‘MyTown’,1,‘21212’),
(1,‘My second address’,‘OtherTown’,5,‘43434’),
(1,‘My third address’,‘MyTown’,1,‘21214’);

SELECT * FROM @Address;
Notice that, with a simple declaration of our Person.Address user-defined type, we gained access to all
the columns for that tabular type. We’re able to insert rows, and select them back out:
(3 row(s) affected)
AddressID  AddressLine1
----------- --------------------
1 My first address ...
1 My second address ...
1 My third address ...
(3 row(s) affected)
Again, we’ll take a further look at uses for this in Chapter 10 as part of our table-valued parameter
discussion.

Dropping a User-Defined Type
It’s fairly intuitive, but just to make sure we’ve addressed the point; all varieties of UDTs are dropped using the very common DROP <object type> <object name> syntax:
DROP TYPE [<schema name>.]<type name>[;]

19 November, 2012

Common Table Expressions (CTEs)



Common Table Expressions (CTE) were first introduced back in SQL Server 2005. They provide a means to refer to a temporary result set by name, and thus utilize it as a table (albeit both temporary and virtual in nature). Perhaps the coolest thing about them is that you define them before actually using them, so you can avoid separate physical steps storing and re-referencing the table (as you would do with a temporary table — or even a table variable). This can have very favorable performance impacts since SQL Server can plan the work between the CTE and the queries that utilize it as part of one logical operation rather than as a series of separate activities. In their simplest form, CTEs are similar to views created on the fly, but a CTE can also enable other things that you can’t really do with a view (for example, see the following section on recursive queries).
The basic syntax for a CTE utilizes the WITH keyword followed by a name and definition:

WITH <CTE name> [( <column name> [,...n])]
AS
( <query returning tabular data> )
<statement that will make use of the CTE>

After the CTE is defined, you can refer to it by name just as if it were a table.
Note that while a CTE can nest, and a CTE can refer to a parent CTE, you cannot have completely inde-
pendent CTEs at the same time, nor can you reference forward in your nested CTEs. Indeed, whatever
statement is going to use the CTE must immediately follow the CTE declaration.
So, as an example of CTE use, we could replace part of our earlier derived table with a CTE reference:

USE AdventureWorks2008;

WITH pumps (BusinessEntityID)
AS
(
SELECT sc.PersonID AS BusinessEntityID
FROM Sales.Customer sc
JOIN Sales.SalesOrderHeader AS soh
ON sc.CustomerID = soh.CustomerID
JOIN Sales.SalesOrderDetail AS sod
ON soh.SalesOrderID = sod.SalesOrderID
JOIN Production.Product AS p
ON sod.ProductID = p.ProductID
WHERE p.Name = ‘Minipump’
)
SELECT DISTINCT pp.FirstName, pp.LastName
FROM Person.Person AS pp
JOIN pumps
ON pp.BusinessEntityID = pumps.BusinessEntityID
JOIN ( SELECT sc.PersonID AS BusinessEntityID
FROM Sales.Customer sc
JOIN Sales.SalesOrderHeader AS soh
ON sc.CustomerID = soh.CustomerID
JOIN Sales.SalesOrderDetail AS sod
ON soh.SalesOrderID = sod.SalesOrderID
JOIN Production.Product AS p
ON sod.ProductID = p.ProductID
WHERE p.Name = ‘AWC Logo Cap’) caps
ON pp.BusinessEntityID = caps.BusinessEntityID;

So here pumps is a temporary table with column name BusinessEntityID
Notice that I was able to cut the first derived table out entirely and replace it with the CTE reference. I
cannot, however, also replace the caps derived table, as I can only make one CTE reference at a time. I
can replace pumps, or I can replace caps, but not both.

It’s worth noting that certain constructs cannot be used within a CTE. These include:
COMPUTER and COMPUTE BY
ORDER BY
INTO
The FOR XML, FOR BROWSE, and OPTION query clauses

26 September, 2012

Export to .xls,.pdf,.doc and formatted .pdf from gridview using C# in ASP.NET

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

    protected void ASPNET_MSgBox(string L_Message)
    {
        string L_Script = "";
        L_Script = "<script> alert('" + L_Message + "');</script>";
        Page.RegisterClientScriptBlock("Information!!", L_Script);
    }
    private void loadData()
    {
        try
        {
            string query = "";
            using (SqlConnection _SqlConnection = new SqlConnection(Global.connString))
            {
                _SqlConnection.Open();
                SqlCommand _SqlCommand = _SqlConnection.CreateCommand();
                query = @"Exec Procedure 2";
                SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(query, _SqlConnection);
                DataSet ds = new DataSet();
                _SqlDataAdapter.Fill(ds, "dt");
                DataTable dt = ds.Tables["dt"];
                gvPVPFinal.DataSource = dt;               
                gvPVPFinal.DataBind();
            }
        }
        catch
        {
            ASPNET_MSgBox("ERROR: Approved Priority Visit Planning (PVP).\\nContact with Administrator");
        }
    }
    private void ExportGridViewToExcel()
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=Export.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        /*--------------Change GridView control under a Form------------------*/
        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(htmlWrite);
        /*--------------------------------*/
        //gvRegion.RenderControl(htmlWrite);
        Response.Write(stringWrite);
        Response.End();
    }
    private void ExportGridViewToFormatedPDF()
    {
        DataTable dt;
        try
        {
            string query = "";
            using (SqlConnection _SqlConnection = new SqlConnection(Global.connString))
            {
                _SqlConnection.Open();
                SqlCommand _SqlCommand = _SqlConnection.CreateCommand();
                query = @"Exec spPVPfinal '" + cmbTerritory.Text.ToString() + "',2";
                SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(query, _SqlConnection);
                DataSet ds = new DataSet();
                _SqlDataAdapter.Fill(ds, "PVPFianl");
                dt = ds.Tables["PVPFianl"];

                //Create a table
                iTextSharp.text.Table table = new iTextSharp.text.Table(GridView1.Columns.Count);
                table.Cellpadding = 5;
                //Set the column widths
                int[] widths = { 100, 250, 90, 50, 50, 380, 380 };

                for (int x = 0; x < GridView1.Columns.Count; x++)
                {
                    string cellText = Server.HtmlDecode(GridView1.HeaderRow.Cells[x].Text);
                    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
                    cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"));
                    table.AddCell(cell);
                }
                table.SetWidths(widths);
                //Transfer rows from GridView to table
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
                    {
                        for (int j = 0; j < GridView1.Columns.Count; j++)
                        {
                            string cellText = Server.HtmlDecode(dt.Rows[i][j].ToString());
                            iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
                            //Set Color of Alternating row
                            //if (i % 2 != 0)
                            //{
                            //    cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"));
                            //}                
                            table.AddCell(cell);
                        }
                    }
                }
                //Create the PDF Document
                Document pdfDoc = new Document(PageSize.A4.Rotate(), 5f, 5f, 5f, 5f);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                pdfDoc.Add(table);
                pdfDoc.Close();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
            }
        }
        catch
        {
            //ASPNET_MSgBox("ERROR: Download Priority Visit Planning (PVP).\\nContact with Administrator");
        }
    }
    private void ExportGridViewToPDF()
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4.Rotate(), 5f, 5f, 5f, 5f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
    private void ExportGridViewToWord()
    {
        Response.AddHeader("content-disposition", "attachment;filename=Export.doc");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.word";

        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());
        Response.End();
    }

 N.B.:
 add reference this dll : itextsharp.dll 
 please download .DLL from here : itextsharp.dll