Thursday, December 2, 2010

Generate Insert Multiple Records Using One Insert Statement – Use of UNION ALL

Version I
DECLARE @TableName            VARCHAR(50)
DECLARE @ColNames AS          VARCHAR(8000)
DECLARE @InsColNames AS       VARCHAR(8000)
DECLARE @NewLineChar AS       VARCHAR(2)
DECLARE @HorizontalTabChar AS VARCHAR(1)
DECLARE @SQuoteFront AS       VARCHAR(15)
DECLARE @SQuoteBack AS        VARCHAR(15)
DECLARE @Comma AS             VARCHAR(150)

SET @SQuoteFront       = '''''''''+'
SET @SQuoteBack        = '+'''''''''
SET @Comma             = ''',''' + ', '
SET @TableName         = 'NetworkPath'
SET @NewLineChar       = CHAR(13) + CHAR(10)
SET @HorizontalTabChar = CHAR(9)

SELECT   @ColNames     = ( COALESCE (@ColNames + ( '''' + column_name + '''' + ', ' ), '') ),
         @InsColNames  = (
                  CASE
                           WHEN
                                    (
                                             data_type = 'bit'
                                    OR       data_type = 'bigint'
                                    OR       data_type = 'decimal'
                                    OR       data_type = 'float'
                                    OR       data_type = 'int'
                                    OR       data_type = 'money'
                                    OR       data_type = 'numeric'
                                    OR       data_type = 'tinyint'
                                    OR       data_type = 'image'
                                    )
                           THEN COALESCE (@InsColNames, '') + ( 'CAST( ' + column_name  + ' AS VARCHAR)' + ' + ' + '''' + ' AS ' + column_name + ''''   + ', ' + '''' + ',' + '''' + ',' )
                           ELSE COALESCE (@InsColNames, '') + ( @SQuoteFront + 'CAST( ' + column_name + ' AS VARCHAR('+ CAST(character_maximum_length AS VARCHAR)  +') )' + @SQuoteBack + ' + ' + '''' + ' AS ' + column_name + '''' + ', ' + @Comma )
                  END )
FROM     information_schema.columns
WHERE    table_name = @TableName
ORDER BY ordinal_position ASC

--Remove comma(,) at the end
SET @ColNames = LEFT(@ColNames, LEN(@ColNames) - 1)

--PRINT 'INSERT INTO ' + @TableName + ' ( ' + @ColNames + ' )'
--Generate Inserte statement for the given table
SELECT 'INSERT INTO ' + @TableName + ' ( ' + @ColNames + ' )' AS InsertStatement

--PRINT 'SELECT '+  @InsColNames + ' FROM ' + @TableName

--Remove ,',', at the end
SET @InsColNames = LEFT(@InsColNames, LEN(@InsColNames) - 5)
PRINT CHAR(13) + CHAR(10)

SELECT @InsColNames

/*
PRINT 'SELECT ' + '''SELECT ' + '''' + ' ,' + ' ' + @InsColNames +
''' UNION ALL' +
'''' + CHAR(13) + CHAR(10) + 'FROM ' + @TableName
*/

EXEC( 'SELECT ' + '''SELECT ' + '''' + ' ,' + ' ' + @InsColNames + ''' UNION ALL' + '''' + 'FROM ' + @TableName )

Version II
DECLARE @TableName            VARCHAR(50)
DECLARE @ColNames AS          VARCHAR(8000)
DECLARE @InsColNames AS       VARCHAR(8000)
DECLARE @NewLineChar AS       VARCHAR(2)
DECLARE @HorizontalTabChar AS VARCHAR(1)
DECLARE @SQuoteFront AS       VARCHAR(15)
DECLARE @SQuoteBack AS        VARCHAR(15)
DECLARE @Comma AS             VARCHAR(150)
SET @SQuoteFront       = '''''''''+'
SET @SQuoteBack        = '+'''''''''
SET @Comma             = ''',''' + ', '
SET @TableName         = 'NetworkPath'
SET @NewLineChar       = CHAR(13) + CHAR(10)
SET @HorizontalTabChar = CHAR(9)
SELECT   @ColNames     = ( COALESCE (@ColNames + ( '''' + column_name + '''' + ', ' ), '') ),
         @InsColNames  = (
         CASE
                  WHEN
                           (
                                    data_type = 'bit'
                           OR       data_type = 'bigint'
                           OR       data_type = 'decimal'
                           OR       data_type = 'float'
                           OR       data_type = 'int'
                           OR       data_type = 'money'
                           OR       data_type = 'numeric'
                           OR       data_type = 'tinyint'
                           OR       data_type = 'image'
                           )
                  THEN COALESCE (@InsColNames, '') + ( 'CAST( ' + column_name + ' AS VARCHAR)' + ' + ' + '''' + ' AS ' + column_name + '''' + ', ' + '''' + ',' + '''' + ',' )
                  ELSE COALESCE (@InsColNames, '') + ( @SQuoteFront + 'CAST( ' + column_name + ' AS VARCHAR('+ CAST(character_maximum_length AS VARCHAR) +') )' + @SQuoteBack + ' + ' + '''' + ' AS ' + column_name + '''' + ', ' + @Comma )
         END )
FROM     information_schema.columns
WHERE    table_name = @TableName
ORDER BY ordinal_position ASC
--Remove comma(,) at the end
SET @ColNames = LEFT(@ColNames, LEN(@ColNames) - 1)
--PRINT 'INSERT INTO ' + @TableName + ' ( ' + @ColNames + ' )'
--Generate Inserte statement for the given table
SELECT 'INSERT INTO ' + @TableName + ' ( ' + @ColNames + ' )' AS InsertStatement
--PRINT 'SELECT '+  @InsColNames + ' FROM ' + @TableName
--Remove ,',', at the end
SET @InsColNames = LEFT(@InsColNames, LEN(@InsColNames) - 5)
PRINT CHAR(13)                                          + CHAR(10)
SELECT @InsColNames
/*
PRINT 'SELECT ' + '''SELECT ' + '''' + ' ,' + ' ' + @InsColNames +
''' UNION ALL' +
'''' + CHAR(13) + CHAR(10) + 'FROM ' + @TableName
*/
EXEC( 'SELECT ' + '''SELECT ' + '''' + ' ,' + ' ' + @InsColNames + ''' UNION ALL' + '''' + 'FROM ' + @TableName )
Reference

Thursday, September 2, 2010

Collapsible Div

function ToggleCollapsible(ControlIdToShow, SaveStateField, ControlFireID) {
    var control = document.all[ControlIdToShow].style;
    var expandstate = document.all[SaveStateField];

    var ControlFireID = document.getElementById(ControlFireID);

    if (control.display == 'none') {
        control.display = '';
        expandstate.value = 'true';

        if (ControlIdToShow == "ToShow") {
            //showImageID.style.display = "none";
            //hideImageID.style.display = "block";
            //On button click change the image
            ControlFireID.src = "Collapsible/collapse.gif";
            ControlFireID.title = "Hide";
        }
    }
    else {
        control.display = 'none';
        expandstate.value = 'false';

        if (ControlIdToShow == "ToShow") {
            //showImageID.style.display = "block";
            //hideImageID.style.display = "none";
            //On button click change the image
            ControlFireID.src = "Collapsible/expand.gif";
            ControlFireID.title = "Show";
        }
    }

    return false;
}

<input type="hidden" name="CollapsiblePanelHidden" value="True" />
<input id="imgBtnShow" name="imgBtnShow" type="image" src="Collapsible/expand.gif"
onclick="return ToggleCollapsible (&#39;ToShow&#39;, &#39;CollapsiblePanelHidden&#39;, &#39;imgBtnShow&#39;)"
title="Show" style="display: block;" />
<div id="ToShow" style="display: none;">
<table id="ShowTable">
<tr>
<td>
<a id="ShowTableContent"
title="Click to expand/collapse" onclick="return ToggleCollapsible (&#39;PanelToShowOrHide&#39;, &#39;CollapsiblePanelHidden&#39;, &#39;imgBtnShow&#39;, &#39;imgBtnHide&#39;)"
href="#">Collapsible panel (click to expand).</a></td>
</tr>
<tr>
<td id="PanelToShowOrHide" style="width: 100%; display: none; color: Red;">
http://asp-tech.blogspot.com/
</td>
</tr>
</table>
</div>

Wednesday, September 1, 2010

Generate CSS DropDown Menu from DataBase

IF OBJECT_ID (N'dbo.MenuMain', N'U') IS NOT NULL
 DROP TABLE dbo.MenuMain;
GO

CREATE TABLE dbo.MenuMain(ID INT, [Name] VARCHAR(50),[Link] VARCHAR(50), [Title] VARCHAR(50), ParentID INT, [Order] INT)

INSERT INTO dbo.MenuMain

SELECT 1, 'CSS Drop Down Menus', NULL, NULL, 0, 1 UNION ALL
SELECT 2, 'Vertical CSS Pop-Out Menu', NULL, NULL, 0, 2 UNION ALL
SELECT 3, 'CSS Hover Navigation',     '#', 'SEO Consultants Directory', 2, 1 UNION ALL
SELECT 4, 'Horizontal Drop & Pop Menu', NULL, NULL, 0, 3 UNION ALL
SELECT 5, 'SEO Consultants Sample',     '#', 'SEO Consultants Vertical Example', 2, 2 UNION ALL
SELECT 6, 'Tanfa Demo example',         '#', 'Complete Example', 5, 1 UNION ALL
SELECT 7, 'Stage 1',                    '#', 'Vertical Menu - Page 1', 6, 1 UNION ALL
SELECT 8, 'Stage 2',                    '#', 'Vertical Menu - Page 2', 6, 2 UNION ALL
SELECT 9, 'Stage 3',                    '#', 'Vertical Menu - Page 3', 6, 3 UNION ALL
SELECT 10, 'Stage 4',                   '#', 'Vertical Menu - Page 4', 6, 4 UNION ALL
SELECT 11, 'Stage 5',                   '#', 'Vertical Menu - Page 5', 6, 5

SELECT   ID    ,
         [Name],
		 [Link],
		 [Title],
         CASE WHEN ParentID = 0
              THEN NULL
              ELSE ParentID
         END AS ParentID,
         [Order]
FROM     dbo.MenuMain
ORDER BY ParentID,
         [Order]
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;

public partial class HorizontalCssMenu : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //http://ago.tanfa.co.uk/css/examples/menu/tutorial-h.html#hs7
        //http://www.alistapart.com/articles/horizdropdowns/

        if (!IsPostBack)
        {
            LoadMenu();
        }
    }

    private void LoadMenu()
    {
        DataTable dtMenu = LoadData();
        
        StringBuilder sbMenu = new StringBuilder();

        foreach (DataRow dr in dtMenu.Rows)
        {
            if (string.IsNullOrEmpty(Convert.ToString(dr["ParentID"]))
                || Convert.ToString(dr["ParentID"]) == "0")
            {
                if (sbMenu.Length != 0)
                    sbMenu.Append(Environment.NewLine);
                sbMenu.Append("
    " + Environment.NewLine); sbMenu.Append("
  • ");
    sbMenu.Append("

    " + Convert.ToString(dr["Name"]) + "

    " + Environment.NewLine);
    sbMenu.Append("
  • " + Environment.NewLine + "
"); } else { StringBuilder sbTemp = new StringBuilder(); if (Convert.ToInt32(dr["Order"]) == 1) sbTemp.Append(Environment.NewLine + "
    "); sbTemp.Append(Environment.NewLine + "
  • ");
    sbTemp.Append("" + Convert.ToString(dr["Name"]) + "");
    sbTemp.Append(Environment.NewLine + "
  • "); if (Convert.ToInt32(dr["Order"]) == 1) sbTemp.Append(Environment.NewLine + "
"); string id = "ID=\"" + Convert.ToString(dr["ParentID"]) + "\""; int length = sbMenu.ToString().IndexOf(id); if (length != -1) { string Previous = sbMenu.ToString().Substring(0, length); string Next = sbMenu.ToString().Substring(length); if (Convert.ToInt32(dr["Order"]) == 1) sbMenu.Insert((Previous.Length + Next.IndexOf(" ")), sbTemp); else sbMenu.Insert((Previous.Length + Next.IndexOf("")), sbTemp); } else sbMenu.Append(sbTemp); } } if (sbMenu.ToString().Length > 0) { menu.InnerHtml = sbMenu.ToString(); } } public DataTable LoadData() { DataSet dsUserMenu = null; try { //Connection string from Web.Config string sDBConnection = "SERVER=;DATABASE=;UID=;pwd="; string[] sTableName = { "Menu" }; string sQuery = @"SELECT ID , [Name], [Link], [Title], CASE WHEN ParentID = 0 THEN NULL ELSE ParentID END AS ParentID, [Order] FROM dbo.MenuMain ORDER BY ParentID, [Order]"; dsUserMenu = new DataSet(); DBHelper.FillDataset(sDBConnection, CommandType.Text, sQuery, dsUserMenu, sTableName); dsUserMenu.DataSetName = "Menus"; DataRelation objMenuRelation = new DataRelation("ParentChild", dsUserMenu.Tables["Menu"].Columns["ID"], dsUserMenu.Tables["Menu"].Columns["ParentID"], false); objMenuRelation.Nested = true; dsUserMenu.Relations.Add(objMenuRelation); return dsUserMenu.Tables[0]; } catch (Exception ex) { throw ex; } } }

Download .cs, .aspx, .css, .sql file form below
HorizontalCssMenu.zip


References
ago.tanfa.co.uk
Example
alistapart

Saturday, August 28, 2010

Joins in SQL SERVER



DECLARE @Employee TABLE
(
 EmpID  INT,
 EmpName  VARCHAR(50),
 DeptID  INT
)

INSERT INTO @Employee
SELECT 1,'kannu',1 UNION ALL
SELECT 2,'Ram',1 UNION ALL
SELECT 3,'Kumar',2 UNION ALL
SELECT 4,'Murali',3 UNION ALL
SELECT 5,'Ranjith',4 UNION ALL
SELECT 6,'Suresh',4 UNION ALL
SELECT 7,'Selva',5 UNION ALL
SELECT 8,'Muthu',6 

DECLARE @Department TABLE
(
 DeptID  INT,
 DeptName VARCHAR(50)
)

INSERT INTO @Department
SELECT 1,'Account' UNION ALL
SELECT 2,'Testing' UNION ALL
SELECT 3,'Web Develop' UNION ALL
SELECT 5,'PDA Develop' UNION ALL
SELECT 6,'Java' UNION ALL
SELECT 7,'DBA'

What is Join in SQL SERVER?

The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.
Join Types
  1. Inner Join
    • Inner Join
    • Equi-Join
    • Natural Join
  2. Outer join
    • Left Join
      • Left Join Excluding Inner Join
    • Right Join
      • Right Join Excluding Inner Join
    • Full Outer Join
      • Outer Join Excluding Inner Join Or Left & Right Joins Excluding Inner Join
  3. Cross Join / Cartesian product
  4. Self Join / Auto Join

Join
The query compares each row of table(@Employee) with each row of table(@Department) to find all pairs of rows which satisfy the join predicate.

Inner Join
The query produces a new result set by combining the column values of both the table @Employee and @Department.
It will produce the resultset if there is atleast one match.

An inner join is a join with a join condition that may contain both equality and non-equality sign whereas an equijoin is a join with a join condition that only contain only equality sign. So we can say an equijoin is a type of inner join containing (Equal)= operator in the join condition.

It is good to know the difference between join and INNER JOIN keyword. Actually there is no difference. If we write JOIN then by default INNER JOIN is performed.

Equi-join or Inner Join
Join based on equality test. Using other operator disqualifies equijoin.

SELECT A.EmpID  ,
       A.EmpName,
       A.DeptID  ,
       B.DeptID ,
       B.DeptName
FROM   @Employee A
       INNER JOIN @Department B
 ON     A.DeptID=B.DeptID
Complex Join Or Inner Join
If join nested then it is called complex join
Jon based on more then one column from each table.

Natural Join
Select the Particular column in Both TableA and TableB. Both table should have same no of columns and names (i.e. Identical columns in both tables). This is accomplished by using union operator in both the select statement.
SELECT EmpID  ,
       EmpName,
       DeptID
FROM   @Employee
UNION --Eliminates duplicates
--UNION ALL --Get all the records from both the table
SELECT EmpID  ,
       EmpName,
       DeptID
FROM   @Employee
Outer Join
Left Outer Join
Display all columns in left side and only Match values in right side. Remaining values will be NULL.
SELECT A.EmpID  ,
       A.EmpName,
       A.DeptID  ,
       B.DeptID ,
       B.DeptName
FROM   @Employee A
       LEFT OUTER JOIN @Department B
       ON     A.DeptID=B.DeptID
Left Join Excluding Inner Join
SELECT A.EmpID  ,
       A.EmpName,
       A.DeptID  ,
       B.DeptID ,
       B.DeptName
FROM   @Employee A
       LEFT JOIN @Department B
       ON     A.DeptID=B.DeptID
WHERE B.DeptID IS NULL
Difference between On clause and Where clause when used with left join
SELECT E.EmpID  ,
       E.EmpName,
       D.DeptName
FROM   @Employee             AS E
       LEFT JOIN @Department AS D
       ON     D.DeptID = E.DeptID
       AND
              (
                     D.DeptName = 'Account'
              OR     D.DeptName = 'Java'
              )
              
SELECT E.EmpID  ,
       E.EmpName,
       D.DeptName
FROM   @Employee             AS E
       LEFT JOIN @Department AS D
       ON     D.DeptID = E.DeptID
WHERE (
              D.DeptName = 'Account'
       OR     D.DeptName = 'Java'
       )
Now let us understand ON clause it is apply before JOIN that is why it retrieves all the result of Table2 where there are Flag = 1 but it does not affect Table1 so it retrieves all the rows of table1. When WHERE clause is applied it applies to complete result so it removes all the rows from Table1 and Table2 where Flag is not equal to 1, essentially keeping flag = 1 rows from Table1 and Table2.
Right Outer Join
Just Opposite Of Left Outer Join
SELECT A.EmpID  ,
       A.EmpName,
       A.DeptID  ,
       B.DeptID ,
       B.DeptName
FROM   @Employee A
       RIGHT JOIN @Department B
       ON     A.DeptID=B.DeptID
       

Right Join Excluding Inner Join
SELECT A.EmpID  ,
       A.EmpName,
       A.DeptID  ,
       B.DeptID ,
       B.DeptName
FROM   @Employee A
       RIGHT JOIN @Department B
       ON     A.DeptID=B.DeptID
WHERE A.DeptID IS NULL
Full Outer Join
A full outer join combines the results of both left and right outer joins. The joined table will contain all records from both tables, and fill in NULLs for missing matches on either side.
SELECT A.EmpID  ,
       A.EmpName,
       A.DeptID  ,
       B.DeptID ,
       B.DeptName
FROM   @Employee A
       FULL OUTER JOIN @Department B
       ON     A.DeptID=B.DeptID
Outer Join Excluding Inner Join Or Left & Right Joins Excluding Inner Join
SELECT A.EmpID  ,
       A.EmpName,
       A.DeptID ,
       B.DeptID ,
       B.DeptName
FROM   @Employee A
       FULL OUTER JOIN @Department B
       ON     A.DeptID=B.DeptID
WHERE  A.DeptID IS NULL
OR     B.DeptID IS NULL
Cartesian Product Or Cross Join
Known as Join without condition
ResultSet = No of Rows in TableA * No of Rows in TableB
Display all the Possibilities of combinations.
SELECT *
FROM   @Employee
INNER JOIN @Department
ON 1 = 1

--Explicit
SELECT *
FROM   @Employee
CROSS JOIN @Department

--Implicit
SELECT *
FROM   @Employee, @Department

Self-Join
A table joins with itself with one or two aliases to stave off confusion are called self-join.
SELECT A.EmpName ,
       B.EmpName ,
       A.DeptID  ,
       B.DeptID
FROM   @Employee A
       INNER JOIN @Employee B
       ON     A.DeptID = B.DeptID

References:
codeproject
wikipedia
c-sharpcorner.com
techbubbles
marcoullis
Logical Query Processing

Wednesday, August 18, 2010

asp menu

Table structure for creating the Menu

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MainMenu](
 [MenuID] [int] NOT NULL,
 [ParentMenuID] [int] NULL,
 [LabelMenu] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [LinkMenu] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [TargetMenu] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [HighlightMenu] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 CONSTRAINT [PK_MainMenu] PRIMARY KEY CLUSTERED 
(
 [MenuID] ASC
) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
EXEC dbo.sp_addextendedproperty @name=N'MS_Description', @value=N'Identity Column' ,@level0type=N'USER', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'MainMenu', @level2type=N'COLUMN', @level2name=N'MenuID'

GO
EXEC dbo.sp_addextendedproperty @name=N'MS_Description', @value=N'Name of the menu.' ,@level0type=N'USER', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'MainMenu', @level2type=N'COLUMN', @level2name=N'LabelMenu'

GO
EXEC dbo.sp_addextendedproperty @name=N'MS_Description', @value=N'Url for the label' ,@level0type=N'USER', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'MainMenu', @level2type=N'COLUMN', @level2name=N'LinkMenu'

GO
EXEC dbo.sp_addextendedproperty @name=N'MS_Description', @value=N'Main menu' ,@level0type=N'USER', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'MainMenu', @level2type=N'COLUMN', @level2name=N'HighlightMenu'

Query to insert records

INSERT INTO dbo.MainMenu
SELECT 1,NULL,'Home,'#,'_self','1' UNION ALL
SELECT 2,NULL,'Accessories,'#,'_self','2' UNION ALL
SELECT 3,NULL,'Products,'#,'_self','3' UNION ALL
SELECT 4,NULL,'Contact,'#,'_self','4' UNION ALL
SELECT 5,2,'Accessory1,'#,'_self',NULL UNION ALL
SELECT 6,3,'Product1,'#,'_self',NULL UNION ALL
SELECT 7,3,'Product2,'#,'_self',NULL UNION ALL
SELECT 8,5,'Accessory2,'#,'_self',NULL UNION ALL
SELECT 9,5,'Accessory3,'#,'_self',NULL UNION ALL
SELECT 10,8,'Acc,'#,'_self',NULL
Query to generate Insert statements
SELECT 'SELECT ' + CAST(MenuID AS VARCHAR) +',' + COALESCE(CAST(ParentMenuID AS VARCHAR), 'NULL')+ ',''' + LabelMenu + ','''+ LinkMenu + ','''+ TargetMenu + ''','+ (CASE WHEN HighlightMenu IS NULL OR HighlightMenu = '' THEN 'NULL' ELSE +''''+ HighlightMenu +'''' END) + ' UNION ALL' FROM dbo.MainMenu

C# Code
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PopulateMenu();
        }
    }

    private void PopulateMenu()
    {
        //Get the menu structure from the table
        DataSet dsMenu = GetDataSetForMenu();

        foreach (DataRow drDataRow in dsMenu.Tables["Menu"].Rows)
        {
            //If the ParentMenuID is NullOrEmpty then it is the top most menu
            if (string.IsNullOrEmpty(Convert.ToString(drDataRow["ParentMenuID"])))
            {
                MenuItem mainMenuItem = new MenuItem((string)drDataRow["LabelMenu"], Convert.ToString(drDataRow["MenuID"]));
                Menu1.Items.Add(mainMenuItem);
                //CreateSubMenu(dsMenu, drDataRow, mainMenuItem);
            }
            else //Otherwise it is the submenu
            {
                CreateSubMenu(dsMenu, drDataRow, new MenuItem());
            }
        }
    }

    private void CreateSubMenu(DataSet dsSubMenu, DataRow drDataRow, MenuItem mainMenuItem)
    {
        //MenuID is the subMenu of the ParentMenuID
        //string MenuID = Convert.ToString(drDataRow["MenuID"]);
        string ParentMenuID = Convert.ToString(drDataRow["ParentMenuID"]);

        //Which is always true
        if (mainMenuItem.Text == string.Empty)
        {
            //If it is the firstChild of the parent find it here itself
            mainMenuItem = Menu1.FindItem(Convert.ToString(drDataRow["ParentMenuID"]));
            //If we can't able to find it in the main menu we have to look for sub-menu
            if (mainMenuItem == null)
                foreach (MenuItem mi in Menu1.Items)
                {
                    //Find the ParentMenu by ParentMenuID
                    mainMenuItem = GetParentMenuItem(mi, Convert.ToString(drDataRow["ParentMenuID"]));
                    if (mainMenuItem == null)
                        continue;
                    if (!mainMenuItem.Text.Trim().Equals(string.Empty))
                        break;
                }
        }

        if (mainMenuItem == null)
            return;
        //This the child element
        if (!string.IsNullOrEmpty(ParentMenuID))
        {
            MenuItem childrenItem = new MenuItem((string)drDataRow["LabelMenu"], Convert.ToString(drDataRow["MenuID"]));
            childrenItem.Target = (string)drDataRow["LinkMenu"];
            mainMenuItem.ChildItems.Add(childrenItem);
        }
    }

    // Recursive function   
    private MenuItem GetParentMenuItem(MenuItem root, string value)
    {
        MenuItem menuItem;
        //Is MenuItem has ChildItems
        if (root.ChildItems.Count > 0)
        {
            //Check which ChildItems is the Parent
            for (int i = 0; i < root.ChildItems.Count; i++)
            {
                menuItem = GetParentMenuItem(root.ChildItems[i], value);
                if (menuItem != null)
                    return menuItem;
            }
        }
        if (root.Value == value)
        {
            return root;
        }
        else
            return null;
    }

    private DataSet GetDataSetForMenu()
    {
        String constr = "Server=10.16.105.171;Database=test;Uid=test;Pwd=test123;Connect Timeout=0; pooling='true'; Max Pool Size=200";
        String query = @"SELECT MenuID, ParentMenuID, LabelMenu, LinkMenu FROM dbo.MainMenu ORDER BY MenuID ASC";
        DataSet dsMenu = new DataSet();

        using (SqlConnection conn = new SqlConnection(constr))
        {
            SqlDataAdapter da = new SqlDataAdapter(query, conn);
            da.Fill(dsMenu);
            da.Dispose();
        }

        dsMenu.DataSetName = "Menus";
        dsMenu.Tables[0].TableName = "Menu";
        DataRelation relation = new DataRelation("ParentChild",
                                dsMenu.Tables["Menu"].Columns["MenuID"],
                                dsMenu.Tables["Menu"].Columns["ParentMenuID"], true);

        relation.Nested = true;
        dsMenu.Relations.Add(relation);

        //This constraint cannot be enabled as not all values have corresponding parent values.

        return dsMenu;
    }
Reference Exception: This constraint cannot be enabled as not all values have corresponding parent values. We will get this exception if we set 0 for ParentMenuID. Where the LabelMenu is parent. Since there is no MenuID with value 0

Saturday, August 14, 2010

Constraints In SQL Server

Constraints: Rules defined on the table, which cannot be violated by the users. It provides a powerful yet easy way to enforce the data integrity in your database.

A constraint is a property assigned to a column or the set of columns in a table that prevents certain types of inconsistent data values from being placed in the column(s). Constraints are used to enforce the data integrity. This ensures the accuracy and reliability of the data in the database.
Data integrity comes in the following forms:
  1. Entity Integrity
  2. Domain Integrity
  3. Referential integrity
  4. User-Defined Integrity
Entity Integrity ensures that there are no duplicate rows in a table.(i.e. Ensures that a table has a primary key).
Entity Integrity can be defined by defining
  1. Primary Key Constraint
  2. Unique Key Constraint
  3. or by building an Unique Indexes

Domain Integrity ensures that data values meet certain criteria; i.e. by choosing an appropriate data type.
  1. Other approaches include defining CHECK constraints or FOREIGN KEY constraints, or writing a trigger.
  2. Default Constraint, Null Constraint, NOT null Constraint also an aspect of domain integrity.

Referential integrity Enforces relationships between two tables, a referenced table, and a referencing table. It ensures that rows cannot be deleted or updated in the referenced, when used in referencing table.
  1. Foreign Key

User-Defined Integrity enforces some specific business rules that do not fall into entity, domain, or referential integrity categories. Each of these categories of the data integrity can be enforced by the appropriate constraints.

Microsoft SQL Server supports the following constraints:
  1. PRIMARY KEY
    • Composite Key or Compound key or Concatenated Key or Aggregate Key
    • Single-Column Key
    • Natural Key
    • Surrogate Key
    • Super Key
    • Candidate Key
    • Alternate Key or Secondary Key
  2. UNIQUE
  3. FOREIGN KEY
  4. CHECK
  5. NOT NULL

A PRIMARY KEY is a column or a combination of columns that uniquely identify a record. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity. NULL values are not allowed. A table can have only one primary key. A primary key adds a clustered index to the table The key can created for single column or more columns of a table. When two or more columns are used as a primary key, they are called a composite key. Not Null Constraint is automatically enforced. SQLPrimaryKeys

A Single-Column Key defined with an ever-increasing identity column.

Surrogate Key
It’s also Primary Key. If there no suitable natural key exists then we have to create surrogate key. It is a single column primary key that created automatically (example: Identity key column in SQL Server) or system generated values (like generated via a table in the schema).

Candidate Key
A column or a set of columns can be called as candidate key if they identify each row of a table uniquely. A table can have multiple candidate keys. One of them is specified as Primary key and rest of them can be called as alternate key.

Composite Key
A key formed by combining at least two or more columns is called Composite Key. Each single column's data can be duplicated but the combination values of these columns cannot be duplicated.
Rules
  1. At all times it holds in the relation assigned to that variable that there are no
    two distinct tuples (rows) with the same values for these attributes and
  2. There is not a proper subset of this set of attributes for which (1) holds.

Natural Key
It’s also Primary Key. If it is reference by foreign key or by defining an unique index on it.

Super Key
A Super Key is a combination of attributes that can be uniquely used to identify a database record. A table might have many Super Keys. A primary key is therefore a minimum Super Key.

Alternate Key
A candidate key that is not the primary key is called an alternate key.

A UNIQUE constraint enforces the uniqueness of the values in a single column or a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints. Not Null Constraint is not automatically enforced. So it allows only one null value.

A FOREIGN KEY constraint prevents any actions that would destroy link between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.

A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity.

A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints. We can create constraints when the table is created, as part of the table definition by using the CREATE TABLE statement.

Default constraint is used to fill column with default value defined during creation of table if nothing is supplied while inserting data.

Super Key - Any combination of keys that make it unique.
Candidate Key - Minimum SK is called candidate key.
Primary Key - Any CK, which does not take null value.
Foreign Key - Reference to PK of another table with no nulls
Unique Key - Same feature is PK but can take null values. Also, in a table there can be many UK.

Any attribute that is uniquely identifying a row in a table is candidate key for the table. We select one of the candidate keys as Primary key.
All candidate keys, which are not chosen as primary key, are Alternate keys.

The key which uniquely identify the rows of the table and which is made up of more than one attribute is called Composite key. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key one of them will become the primary key and the rest are called alternate keys.

Reference
Natural vs. Surrogate Keys in SQL Server
Different Types of SQL Keys
Surrogate Keys, Natural Keys, Candidate Keys, Composite Keys and Super Keys?

Friday, July 30, 2010

Query to get PrimaryKey, ForeignKey, IdentityKey, UniqueKey column names

DECLARE  @TableName NVARCHAR(50)
SET @TableName = 'PkFkIkTestIdentAsPk'
 
 SELECT
  C.COLUMN_NAME,
  C.DATA_TYPE,
  C.ORDINAL_POSITION 
 FROM
  INFORMATION_SCHEMA.COLUMNS C 
  LEFT JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS COL
  ON col.TABLE_NAME = C.TABLE_NAME 
  AND col.COLUMN_NAME = C.COLUMN_NAME
  INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tblCons 
 ON tblCons.CONSTRAINT_NAME = col.CONSTRAINT_NAME 
 WHERE tblCons.TABLE_NAME = @TableName 
  AND 
  (
   tblCons.CONSTRAINT_TYPE = 'PRIMARY KEY' 
  OR tblCons.CONSTRAINT_TYPE = 'FOREIGN KEY' 
  OR tblCons.CONSTRAINT_TYPE = 'UNIQUE' 
  )
 UNION 
  SELECT C.COLUMN_NAME,
  C.DATA_TYPE,
  C.ORDINAL_POSITION
  FROM
  INFORMATION_SCHEMA.COLUMNS C
  WHERE C.TABLE_NAME = @TableName
  AND COLUMNPROPERTY(OBJECT_ID(C.TABLE_NAME), C.COLUMN_NAME,'IsIdentity') = 1

Saturday, July 10, 2010

SQL SERVER DataTypes

To get the DataType information
SP_HELP DataTypeName
SELECT 'User_type' = name, 
       'Storage_type' = Type_name(xtype), 
       'Length(Size)' = length, 
       'Prec' = Typeproperty(name, 'precision'), 
       'Scale' = Typeproperty(name, 'scale'), 
       'Nullable' = CASE 
                      WHEN Typeproperty(name, 'AllowsNull') = 1 THEN 'Yes' 
                      ELSE 'No' 
                    END, 
       'Default_name' = Isnull(Object_name(tdefault), 'None'), 
       'Rule_name' = Isnull(Object_name(domain), 'None'), 
       'Collation' = collation 
FROM   systypes 
ORDER  BY name  


2008

2005

2000

Exact Numerics

Exact Numerics

Exact Numerics

bigint

bigint

bigint

numeric

numeric

numeric

bit

bit

bit

smallint

smallint

smallint

decimal

decimal

decimal

smallmoney

smallmoney

smallmoney

int

int

int

tinyint

tinyint

tinyint

money

money

money

 

 

 

Approximate Numerics

Approximate Numerics

Approximate Numerics

float

float

float

real

real

real

 

 

 

Date and Time

Date and Time

Date and Time

date

 

 

datetimeoffset

 

 

datetime2

 

 

smalldatetime

smalldatetime

smalldatetime

datetime

datetime

datetime

time

 

 

 

 

 

Character Strings

Character Strings

Character Strings

char

char

char

varchar

varchar

varchar

text

text

text

 

 

 

Unicode Character Strings

Unicode Character Strings

Unicode Character Strings

nchar

nchar

nchar

nvarchar

nvarchar

nvarchar

ntext

ntext

ntext

 

 

 

Binary Strings

Binary Strings

Binary Strings

binary

binary

binary

varbinary

varbinary

varbinary

image

image

image

 

 

 

Other Data Types

Other Data Types

Other Data Types

cursor

cursor

cursor

timestamp

timestamp

timestamp

hierarchyid

 

 

uniqueidentifier

uniqueidentifier

uniqueidentifier

sql_variant

sql_variant

sql_variant

xml

xml

 

table

table

table

2008

2005

2000

Saturday, June 26, 2010

OutOfMemory Exception

The below code is used to merge multipage tiff with single page tiffs.

 private void CreatThumbnail(Image thumbNailImg, int iPagesCount)
        {
            try
            {
                //TRK
                //PictureBox[] picBoxArray = new PictureBox[iPagesCount];
                picBoxArray = new PictureBox[iPagesCount];
                PictureBox picBox = null;

                pnlThumbnail.Controls.Clear();

                
                int iWidth = 300;
                int iHeight = 300;

               
                if (!rbShowPageByPage.Checked && !rbShowBoth.Checked)
                {
                    //TRK - 01 
                    iWidth = 308;
                    iHeight = 550;
                    pnlThumbnail.Size = new Size(966, 560);

                    //iWidth = 500;
                    //iHeight = 550;
                    //pnlThumbnail.Size = new Size(966, 560);
                }
                else
                {
                    pnlThumbnail.Location = new Point(16, 110);
                    pnlThumbnail.Size = new Size(966, 131);
                }

                int iThumbCurrPage = 0;
                
                for (; iThumbCurrPage < iPagesCount; iThumbCurrPage++)
                {
                    //TRK
                    picBox = new PictureBox();
                    thumbNailImg.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, iThumbCurrPage);

                    using (Image myBmp = new Bitmap(thumbNailImg, iWidth, iHeight))
                    {
                        MemoryStream memoryStream = new MemoryStream();
                        myBmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Tiff);
                        picBox.Image = Image.FromStream(memoryStream); // showing the page in the pictureBox1

                        myBmp.Dispose();
                        if (memoryStream != null)
                        {
                            memoryStream.Close();
                            memoryStream.Dispose();
                        }
                        GC.Collect();
                    }

                    picBox.Size = picBox.Image.Size;
                    picBox.Location = new Point(1 + (iThumbCurrPage * (iWidth + 10)), 1);
                    picBoxArray[iThumbCurrPage] = picBox;
                    picBoxArray[iThumbCurrPage].Name = Convert.ToString(iThumbCurrPage);
                    toolTipForControls.SetToolTip(picBoxArray[iThumbCurrPage], MessagesAndToolTips.ThumNailClick);

                    picBoxArray[iThumbCurrPage].Click += new System.EventHandler(this.ThumbNailPictureBox_Click);
                    pnlThumbnail.Controls.Add(picBoxArray[iThumbCurrPage]);

                    if (iThumbCurrPage == 0)
                        objCommonDeclarations.ShowMessage("Loading Page " + Convert.ToString(iThumbCurrPage + 1) + " Of " + Convert.ToString(iPagesCount), "INFO", lblShowMessage);
                    else
                        objCommonDeclarations.ShowMessage("Loading Next Page " + Convert.ToString(iThumbCurrPage + 1) + " Of " + Convert.ToString(iPagesCount), "INFO", lblShowMessage);
                    Application.DoEvents();

                    GC.Collect();
                }

                objCommonDeclarations.ShowMessage("Loading Last " + Convert.ToString(iThumbCurrPage) + " Of " + Convert.ToString(iPagesCount), "INFO", lblShowMessage);
                Application.DoEvents();

                objCommonDeclarations.ShowMessage(string.Empty, "INFO", lblShowMessage);
                Application.DoEvents();

            }
            catch (Exception ex)
            {
                objCommonDeclarations.ShowMessage(ex.Message.ToString(), "ERROR", lblShowMessage);
                objCommonDeclarations.WriteLog(ex.Message.ToString(), false, false);
            }
        }

 private void SwapImages()
        {
            try
            {
                int swapPage = Convert.ToInt32(txtPageNumber.Text.Trim()) - 1;

                //Open file in read only mode 
                using (FileStream fs = new FileStream(@lblFile.Text.Trim(), FileMode.Open, FileAccess.Read))
                {

                    string _sDestinatinPath = Path.Combine(CommonDeclarations.sDestinationPath, Path.GetFileName(@lblFile.Text.Trim()));
                    if (swapPage == 0)
                    {
                        using (Image bmp1 = Image.FromStream(fs))//TRK
                        {
                            bmp1.Save(_sDestinatinPath, ImageFormat.Tiff);

                            fs.Dispose();
                            bmp1.Dispose();
                            GC.Collect();
                        }
                        return;

                        //background
                        //return string.Empty;
                    }

                    ImageCodecInfo imageCodecInfo = GetEncoderInfo("image/tiff");

                    //Image bmp = Image.FromStream(fs);
                    using (Image bmp = Image.FromStream(fs))//TRK
                    {
                        //Bitmap bmp = new Bitmap(fs);

                        int frameCount = bmp.GetFrameCount(FrameDimension.Page);
                        bmp.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, swapPage);

                        //Image newTiff = new Bitmap(bmp, bmp.Width, bmp.Height);
                        //Image newTiff = Converter.ConvertToBitonal(new Bitmap(bmp, bmp.Width, bmp.Height));
                        using (Image newTiff = Converter.ConvertToBitonal(new Bitmap(bmp, bmp.Width, bmp.Height)))
                        {

                            EncoderParameters SaveEncoderParameters = new EncoderParameters(2);
                            System.Drawing.Imaging.Encoder SaveEncoder = System.Drawing.Imaging.Encoder.SaveFlag;
                            EncoderParameter CompressEncodeParam = new EncoderParameter(SaveEncoder, (long)(EncoderValue.MultiFrame));
                            SaveEncoderParameters.Param[0] = CompressEncodeParam;
                            SaveEncoder = System.Drawing.Imaging.Encoder.Compression;
                            CompressEncodeParam = new EncoderParameter(SaveEncoder, (long)(EncoderValue.CompressionCCITT4));
                            SaveEncoderParameters.Param[1] = CompressEncodeParam;


                            System.Drawing.Imaging.Encoder AddEncoder = System.Drawing.Imaging.Encoder.SaveFlag;
                            EncoderParameter AddEncodeParam = new EncoderParameter(AddEncoder, (long)EncoderValue.FrameDimensionPage);
                            System.Drawing.Imaging.Encoder AddCompressionEncoder = System.Drawing.Imaging.Encoder.Compression;
                            EncoderParameter AddCompressionEncodeParam = new EncoderParameter(AddCompressionEncoder, (long)EncoderValue.CompressionCCITT4);
                            EncoderParameters AddEncoderParams = new EncoderParameters(2);

                            AddEncoderParams.Param[0] = AddEncodeParam;
                            AddEncoderParams.Param[1] = AddCompressionEncodeParam;

                            ArrayList swap = new ArrayList();
                            for (int i = 0; i < frameCount; i++)
                            {
                                swap.Add(i);
                            }

                            swap.Insert(0, swap[swapPage]);
                            swap.RemoveAt(swapPage + 1);

                            int pageCount = 0;
                            for (; pageCount < frameCount; pageCount++)
                            {
                                switch (pageCount)
                                {
                                    case 0:

                                        newTiff.Save(_sDestinatinPath, imageCodecInfo, SaveEncoderParameters);
                                        break;
                                    default:

                                        bmp.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, Convert.ToInt32(swap[pageCount]));

                                        try
                                        {
                                            // Convert image to bitonal for saving to file
                                            using (Bitmap newPage = Converter.ConvertToBitonal(new Bitmap(bmp, bmp.Width, bmp.Height)))//TRK
                                            {
                                                newTiff.SaveAdd(newPage, AddEncoderParams);
                                                newPage.Dispose();
                                                GC.Collect();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            throw ex;
                                        }
                                        finally
                                        {

                                            //GC.WaitForPendingFinalizers();
                                        }
                                        break;
                                }

                                ////Background
                                //objCommonDeclarations.ShowMessage("Reordering Images " + Convert.ToString(pageCount + 1) + " of " + Convert.ToString(frameCount), "INFO", lblShowMessage);
                                //Application.DoEvents();

                                GC.Collect();
                                //GC.WaitForPendingFinalizers();
                            }

                            //////Background
                            //objCommonDeclarations.ShowMessage("Reordering Images " + Convert.ToString(pageCount + 1) + " of " + Convert.ToString(frameCount), "INFO", lblShowMessage);
                            //Application.DoEvents();

                            //////Background
                            //objCommonDeclarations.ShowMessage(string.Empty, "INFO", lblShowMessage);
                            //Application.DoEvents();

                            AddEncoderParams.Param[0] = new EncoderParameter(AddEncoder, (long)EncoderValue.Flush);
                            newTiff.SaveAdd(AddEncoderParams);

                            newTiff.Dispose();
                            GC.Collect();
                        }

                        bmp.Dispose();
                        fs.Dispose();
                        GC.Collect();

                    }
                }
            }
            catch (Exception ex)
            {
                objCommonDeclarations.ShowMessage(ex.Message.ToString(), "ERROR", lblShowMessage);
                //Background
                //return ex.Message.ToString();
                objCommonDeclarations.WriteLog(ex.Message.ToString(), false, false);
            }

            //Background
            //return string.Empty;
        }


/// 
/// To Merge the Single Page Tifs in folder to a Multipage Tiff Image
/// 
/// This denotes Multipage Image Full Path/// This denotes Single Page Tif Image List/// After Merge where need to store the New Merged Tif Filesprivate bool MergeTifImages(String sMultiPageTif, List lstSingleTifs, String sDestinationPath)
        {
            String SinglePageTif = String.Empty;
            bool sflg = true;
            try
            {
                // To Check Destination Path is Exist or Not, if not create the path and folder structure
                if (!Directory.Exists(@sDestinationPath)) Directory.CreateDirectory(@sDestinationPath);
                //Open file in read only mode 
                using (FileStream fs = new FileStream(@sMultiPageTif, FileMode.Open, FileAccess.Read))
                {
                    //To Form the Destination Tiff File Name
                    String _sDestinatinPath = Path.Combine(@sDestinationPath, Path.GetFileName(@sMultiPageTif));
                    //To Create the Image Codec Info                   
                    ImageCodecInfo imageCodecInfo = GetEncoderInfo("image/tiff");

                    //To Create the New bmp Image from the existing Multipage Tif
                    //Image bmp = Image.FromStream(fs);
                    Image newTiff = null;
                    //To Select the Encoder and Compresstion formates for the Tif Images
                    EncoderParameters SaveEncoderParameters = new EncoderParameters(2);
                    System.Drawing.Imaging.Encoder SaveEncoder = System.Drawing.Imaging.Encoder.SaveFlag;
                    EncoderParameter CompressEncodeParam = new EncoderParameter(SaveEncoder, (long)(EncoderValue.MultiFrame));
                    SaveEncoderParameters.Param[0] = CompressEncodeParam;
                    SaveEncoder = System.Drawing.Imaging.Encoder.Compression;
                    CompressEncodeParam = new EncoderParameter(SaveEncoder, (long)(EncoderValue.CompressionCCITT4));
                    SaveEncoderParameters.Param[1] = CompressEncodeParam;

                    System.Drawing.Imaging.Encoder AddEncoder = System.Drawing.Imaging.Encoder.SaveFlag;
                    EncoderParameter AddEncodeParam = new EncoderParameter(AddEncoder, (long)EncoderValue.FrameDimensionPage);
                    System.Drawing.Imaging.Encoder AddCompressionEncoder = System.Drawing.Imaging.Encoder.Compression;
                    EncoderParameter AddCompressionEncodeParam = new EncoderParameter(AddCompressionEncoder, (long)EncoderValue.CompressionCCITT4);
                    EncoderParameters AddEncoderParams = new EncoderParameters(2);

                    AddEncoderParams.Param[0] = AddEncodeParam;
                    AddEncoderParams.Param[1] = AddCompressionEncodeParam;

                    using (Image bmp = Image.FromStream(fs))
                    {
                        //Get the Page Count, i.e Frame Count
                        int frameCount = bmp.GetFrameCount(FrameDimension.Page);

                        //To Create Temp New Tiff                 
                        newTiff = Converter.ConvertToBitonal(new Bitmap(bmp, bmp.Width, bmp.Height));

                        // To Save the Multipage Tiff
                        newTiff.Save(_sDestinatinPath, imageCodecInfo, SaveEncoderParameters);
                        Application.DoEvents();
                        //To Update frame by frame to the multipage
                        int pageCount = 0;
                        for (; pageCount < frameCount; pageCount++)
                        {
                            switch (pageCount)
                            {
                                case 0:

                                    newTiff.Save(_sDestinatinPath, imageCodecInfo, SaveEncoderParameters);
                                    break;
                                default:
                                    bmp.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, pageCount);
                                    // Convert image to bitonal for saving to file

                                    using (Bitmap newPage = Converter.ConvertToBitonal(new Bitmap(bmp, bmp.Width, bmp.Height)))
                                    {
                                        //Bitmap newPage = Converter.ConvertToBitonal(new Bitmap(bmp, bmp.Width, bmp.Height));
                                        newTiff.SaveAdd(newPage, AddEncoderParams);
                                    }

                                    break;
                            }
                            Application.DoEvents();
                        }
                    }

                    // To Merage the Single Page Tif Image to Multipage Tif Image form Single Tifs List
                    foreach (String SingleTif in lstSingleTifs)
                    {
                        try
                        {
                            CommonDeclarations.WriteLog("Single Page TIF: " + Path.GetFileName(SingleTif), false, false);
                            using (FileStream fs1 = new FileStream(@SingleTif, FileMode.Open, FileAccess.Read))
                            {
                                //To over come Out of memory.
                                //Image Singlebmp = Image.FromStream(fs1);
                                using (Image Singlebmp = Image.FromStream(fs1))
                                {
                                    Application.DoEvents();
                                    int frameCount = Singlebmp.GetFrameCount(FrameDimension.Page);
                                    //To Check the Given Single Page tif is having More than One Frame
                                    if (frameCount > 1)
                                    {
                                        CommonDeclarations.WriteLog("The Selected Single Page TIF Having More Then One Page. Page Count: " + frameCount, false, false);
                                        //This works if Multipage exist 
                                        int pageCount = 0;
                                        for (; pageCount < frameCount; pageCount++)
                                        {
                                            Singlebmp.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, pageCount);
                                            // Convert image to bitonal for saving to file
                                            Bitmap SinglePageTiff = Converter.ConvertToBitonal(new Bitmap(Singlebmp, Singlebmp.Width, Singlebmp.Height));
                                            newTiff.SaveAdd(SinglePageTiff, AddEncoderParams);
                                            //  break;
                                        }
                                    }
                                    else
                                    {
                                        //This will works while Single Frame of Single Tiff Image
                                        using (Bitmap tempBmp = new Bitmap(Singlebmp, Singlebmp.Width, Singlebmp.Height))
                                        {
                                            using (Bitmap SinglePageTifs = Converter.ConvertToBitonal(tempBmp))
                                            {
                                                //Bitmap SinglePageTifs = Converter.ConvertToBitonal(new Bitmap(Singlebmp, Singlebmp.Width, Singlebmp.Height));
                                                Application.DoEvents();
                                                newTiff.SaveAdd(SinglePageTifs, AddEncoderParams);

                                                SinglePageTifs.Dispose();
                                                GC.Collect();
                                            }
                                            tempBmp.Dispose();
                                            GC.Collect();
                                        }
                                    }

                                    Singlebmp.Dispose();
                                    GC.Collect();
                                }

                                fs1.Close();
                                fs1.Dispose();
                                GC.Collect();
                            }
                        }
                        catch (Exception ex)
                        {
                            CommonDeclarations.WriteLog(ex.Message.ToString(), false, false);
                            sflg = false;
                        }

                    }
                    //Save the New Tiff and Encode the Tiff  Images
                    AddEncoderParams.Param[0] = new EncoderParameter(AddEncoder, (long)EncoderValue.Flush);
                    newTiff.SaveAdd(AddEncoderParams);
                    newTiff.Dispose();
                    GC.Collect();

                }
            }
            catch (Exception ex)
            {
                //CommonDeclarations.ShowMessage(ex.Message.ToString(), "ERROR", lblShowMessage);
                CommonDeclarations.WriteLog("Some Error in MergeTifImages, Error: " + ex.Message.ToString(), false, false);
                sflg = false;
            }
            return sflg;
        }

        /// 
        /// To Get the ImageCodecInfo. For Example *.TIF,*.TIFF or *.JPG,*.BMP,*.GIF
        /// 
        /// This denotes MimeType. Kind of Imgage to Get the Image Files Type/// 
        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            try
            {
                ImageCodecInfo[] encoders;
                encoders = ImageCodecInfo.GetImageEncoders();
                for (j = 0; j < encoders.Length; ++j)
                {
                    if (encoders[j].MimeType == mimeType)
                        return encoders[j];
                }
                return null;
            }
            catch (Exception ex)
            {
                CommonDeclarations.WriteLog("Some Error in ImageCodecInfo,Error:"+ ex.Message.ToString(), false, false);
                return null;
            }
        }

After running the application I looked how much memory the Proces use. Object.Dispose(); doesn't release the memory occuped by the object immediately. It shows constant memory increase when seeing. After using GC.Collect(); if frees the memory. Afterwares no OutOfMemory Exception thrown. Here we added each image to a panel(pnlThumbnail) pnlThumbnail.Controls.Add(picBoxArray[iThumbCurrPage]); This occupies more memory. We have to clear that in the following way.
//Clear the picture box stored in thumbnailArray
                if (picBoxArray != null)
                {
                    foreach (PictureBox tempPb in picBoxArray)
                    {
                        if (tempPb.Image != null)
                        {
                            tempPb.Image.Dispose();
                            tempPb.Image = null;

                            GC.Collect();
                        }
                    }
                    picBoxArray = null;
                }

                for (int clearPictureBox = 0; clearPictureBox < pnlThumbnail.Controls.Count; clearPictureBox++)
                {

                    PictureBox pb = pnlThumbnail.Controls[clearPictureBox] as PictureBox;

                    pnlThumbnail.Controls.Remove(pb);

                    if (pb.Image != null)
                    {
                        pb.Image.Dispose();
                        pb.Image = null;
                    }
                }
                
                if (pbShowTiffImage.Image != null)
                {
                    pbShowTiffImage.Image = null;
                    pbShowTiffImage.Invalidate();
                    GC.Collect();
                }
                                
                //The above one is better than this
                //foreach (IDisposable control in pnlThumbnail.Controls)
                //    control.Dispose(); 

                pnlThumbnail.Controls.Clear();
                GC.Collect();
REferences Tracking down managed memory leaks (how to find a GC leak) IDisposable.Dispose Method Detecting .NET application memory leaks memory leak with delegates and workflow foundation http://msdn.microsoft.com/en-us/magazine/cc163491.aspx Memory Leak Detection in .NET

Wednesday, June 16, 2010

Stored Procedure Generator for SQL SERVER

Download the tool


1. Get Sql Server Name.
2. Get Sql Server IP Address.
3. Load Server from local machine.
4. Load Server from your network.
5. Press the button load to load the Server Name or IP Address.
6. Press the button load to load the DataBase name for the the Selected Server Name or IP Address..
7. Save to File save the Procudure as .sql file.
8. Append The Scripts In SQLFile puts all the Procedure in a single .sql file.
9. Create New File For Each SP creates new .sql file with the name of the procedure.
10. Execute Script To Server, executes your procedure directly to your SQL server.
11. Overwrite the SP If Already Exists. If any procedure already exists it drops the procedure and creates a new one.
12. The left list box contails all the tables in your selected database.
13. >> button to move from left listbox to right for creating procedure for the table.
14. << botton to move from the right listbox to left if you don't want to create procedure for the table.
15. Select All To Move Right to select all tables in the left listbox for moving right.
16. Select All To Move Left to select all tables in the right listbox for moving left.
17. Click Create Scripts button to generate procedure according to the conditions.


Happy Coding.

Friday, April 30, 2010

SQL SERVER Parameter Directions

There are 4 types of parameter direction in SQL SERVER.
  1. Input
  2. Output or Out
  3. InputOutput
  4. Return

But we can specify only OUT or OUTPUT as parameter direction for the Procedure or Function.

RETURN at the last statement of the Procedure or Function and not in the parameter declaration of the Procedure or Function.

IN
DECLARE @ParentID int
SET @ParentID =6
exec [dbo].[GetTestTable] @ParentID


ALTER PROCEDURE [dbo].[GetTestTable](
@ParentID INT)
AS
BEGIN
SET @ParentID =10
SELECT @ParentID
END


We can’t able to specify in any where during the execution or in the SP parameter direction.
DECLARE @ParentID int
SET @ParentID =6
exec [dbo].[GetTestTable] @ParentID IN –Not allowed

ALTER PROCEDURE [dbo].[GetTestTable](
@ParentID INT IN) -–Not allowed AS
BEGIN
SELECT @ParentID
END

We will get this error.
Incorrect syntax near the keyword 'in'.

OUTPUT
Output is not only for sending value back to the caller, it also accepts input from the caller. Since by default OUT implies both IN and OUT.

E.g. 1
ALTER PROCEDURE [dbo].[GetTestTable](
@ParentID INT OUTPUT)
AS
BEGIN
SET @ParentID = @ParentID + 5
END


DECLARE @ParentID int
SET @ParentID =6
exec [dbo].[GetTestTable] @ParentID OUT
PRINT @ParentID 

Result: 11

There is no need of RETURN or SELECT statement for the OUT direction parameter. Just assing the value, we will get the result.

If we didn’t assing a new value, we will get only the value we sent during execution of the Procedure or Function.(i.e. 6 for the above condion.)

If we didn’t sent any value during execution of the Procedure or Function we will get only nothing for the below condion.

DECLARE @ParentID int
exec [dbo].[GetTestTable] @ParentID OUT
PRINT @ParentID



E.g. 2
ALTER PROCEDURE [dbo].[GetTestTable](
@ParentID INT OUTPUT)
AS
BEGIN
SET @ParentID =10
SELECT @ParentID
END
No need to pass value. Just specify the keyword OUT near the parameter.
DECLARE @ParentID INT
EXEC [dbo].[GetTestTable] @ParentID OUT
PRINT @ParentID

Result: 10

For the above Procedure or Function we are assigning value to the parameter and also we are using SELECT statement. Here we will get a result-set and aslo the value assigned to our argument.

RETURN

There should be a RETURN statement at the end of the Procedure or Function.
ALTER PROCEDURE [dbo].[GetTestTable](
@ParentID INT OUTPUT)
AS
BEGIN
SET @ParentID =10
RETURN @ParentID
END

DECLARE @ParentID    INT
DECLARE @ReturnValue INT
SET @ParentID     =6
EXEC @ReturnValue = [dbo].[GetTestTable] @ParentID
PRINT @ReturnValue

If there is no RETURN statemnt at the end of the Procedure or Function, we will get only the default value of the RETURN argument datatype.

For example there is no RETURN statemnt for the above Procedure the result will be 0.

We can’t able to return a table variable from a RETURN statement.


Note:
  1. By default OUT implies both IN and OUT.
  2. Since our parameter is OUT we can pass value, since OUT implies both IN and OUT.
  3. The default parameter direction is IN.
  4. If the last statement is just RETURN without any value or a variable we will get
    nothing (if we didn’t pass value to the parameter of assign) or default value (if
    we assign value when passing). This is default for all the parameter direction.


These all are wrong.
@ReturnValue EXEC [dbo].[GetTestTable] @ParentID

Line 4: Incorrect syntax near '@ReturnValue'.

@ReturnValue = EXEC [dbo].[GetTestTable] @ParentID

Line 4: Incorrect syntax near '@ReturnValue'.

EXEC [dbo].[GetTestTable] @ParentID, @ReturnValue RETURN

Procedure or Function GetTestTable has too many arguments specified.

Wednesday, April 28, 2010

Three tire code Generator for C#.NET

Download the toolOr


  1. Select Table Tab to get the tables for your ConnectionString.
  2. Enter your connection string.
  3. Press to get the tables for your ConnectionString.
  4. After pressing the button Load Tables the tables are loaded. When selecting a table it focus on the Conditions tab and all the column and DataType are loaded automatically in 9, 10, 10.1.
  5. Conditon tab to specify the property and field prefix.
  6. Namespace for your class.
  7. Name of your property class.
  8. Name of your data access layer class.
  9. Enter your table name. This helps to produce the sp name. For Select method it creates spname as GetTableName.
  10. Table column name along with DataType.
  11. 10.1. Get distinct of DataType from 10.
  12. Clear all the controls.
  13. For each datatype in 10.1 we are generating a textbox to enter the prefix for the DataType.
  14. For each data-type you want to specify a separate prefix check it. For exampele for string specify str. Your field will be created like strUserID. The panel will be enabled and enter it.
  15. By default the field names are generated with underscore (_). If you want to change give a new one.
  16. Enter the prefix for the fields. This will be enabled by checking Is prefix required for fields.
  17. For properties some of us specify pUserID. If you want to specify enter it by check the checkbox of is prefix required for properties.
  18. To genereate the Data Tire Classes.
  19. If your get procedure contains any parameter check the select.
  20. If your Delete procedure contains any parameter check the select.
  21. Select the column names. These are the parameters for procedure Insert and Update.
  22. This is single select. This column will be your direction. For all the four procedures.
  23. Select your ParameterDirection
  24. Select your ParameterDirection.
  25. Select your ParameterDirection.
  26. Select your ParameterDirection.
  27. If you are using SQLHelper class check it. The code generated accordingly.
  28. If you want to save the calsses as file check it. It opens a folder dialogue to select a path where to store the class files.
  29. After select you can view the selected path.
  30. The tab Properties contains a class with properties.
  31. The tab DAL contains a class with functions for calling Select, Insert, Delete Update procecures.
  32. The tab SQLHelper contains a class with functions for calling Select, Insert, Delete Update procecures. This class uses SQLHelper.cs

Happy Coding.

Tuesday, April 27, 2010

ADO.NET Parameter Direction





Input

InputOutput

Output

ReturnValue

Passing
value to procedure

  or function.

Pass
value to the procedure or function and get back the assigned value from the procedure
or function.

Get
value from the procedure or function.

Get
the value of the return statement.

ParameterDirection

.Input;

ParameterDirection

.InputOutput

ParameterDirection

.Output

ParameterDirection

.ReturnValue

(@Columndatetime

 
datetime)




 
 

By default it is IN. So

 
it is not possible

to use the keyword IN.

(@Columndatetime
datetime OUT)




 
 

Since OUT implies both IN and OUT and there is no INOUT.

(@Columndatetime
datetime OUT)

We
are not passing the parameter in Procedure or function.

         


DECLARE
@Columnnumeric numeric,
@ReturnValue NUMERIC

SET
@Columnnumeric = 10

EXEC

@ReturnValue

= [dbo].

[GetTestTable] @Columnnumeric,
'BABU'


PRINT

@ReturnValue

We
can assign the value any where in the procedure or function.

        

We
can assign value at declaration itself.

        

(@Columndatetime
datetime = 10
OUT)




 
 

If we didn’t assign value in the procedure
or function it took the sent value.




 
 

If we didn’t pass value and we didn’t assing
value in the procedure or function but we assign default value it took the default
value.

We
can assign the value any where in the procedure or function.

        

We
can assign value at declaration itself.

        

(@Columndatetime
datetime = 10
OUT)




 
 




 
 

If we didn’t assign value in the procedure
or function it took the sent value.




 
 

If we didn’t pass value and we didn’t assing
value in the procedure or function but we assign default value it took the default
value.




 
 




 
 

DECLARE
@Columnnumeric numeric,
@ReturnValue NUMERIC

SET
@Columnnumeric = 10

EXEC
[dbo].[GetTestTable] @Columnnumeric OUT,
'BABU'

PRINT
@Columnnumeric

This
should be the last statement of the procedure or function.

        

return
10




 
 

     or like this.




 
 

DECLARE
@ReturnValue numeric

SET
@ReturnValue = 10

RETURN
10




 
 




 
 

Get value from the procedure or function.




 
 

DECLARE
@Columnnumeric numeric,
@ReturnValue NUMERIC

SET
@Columnnumeric = 10

EXEC
@ReturnValue = [dbo].[GetTestTable]
@Columnnumeric

PRINT
@ReturnValue

         


         


         


         


objCmd.
Parameters

.Add("

@Columnnumeric"

,
SqlDbType

.Decimal)

.Value =
10.0d;

objCmd.Parameters

.Add("@

Columnnumeric"
, SqlDbType.
Decimal)

.Value = 10.0d;

objCmd.
Parameters["@


Columnnumeric"
]

.Direction =
Parameter

Direction

. InputOutput;

objCmd.
Parameters

.Add("@


Columnnumeric"
, SqlDbType.
Decimal).

Value = 10.0d;

objCmd.
Parameters["@


Columnnumeric"
]

.Direction =
Parameter

Direction

. Output;

objCmd.
Parameters

.Add("

@Columnnumeric"
, SqlDbType

.Decimal).

Value = 10.0d;

objCmd.
Parameters

["

@Columnnumeric"
]

.Direction =
Parameter

Direction

.ReturnValue;

         


Decimal

Columnnumeric = (Decimal)objCmd.

Parameters

["@ColumnnTest"]

.Value;

Decimal Columnnumeric


 
= (Decimal)objCmd.

Parameters

["@ColumnnTest"]

.Value;

Decimal

Columnnumeric = (Decimal)objCmd.

Parameters

["@ColumnnTest"]

.Value;

         


         


         


If the ParameterDirection
is ParameterDirection

.ReturnValue we should not use the parameter
in prarameter declaration of the procedure or function.

!supportEmptyParas]> <![endif]>

http://weblogs.asp.net/andrewrea/archive/2008/02/19/examples-of-using-system-data-parameterdirection-with-sql-server.aspx

Rules to follow

Rule 1

If our ParameterDirection is
ParameterDirection
.ReturnValue and we are using in the parameter of the
Procedure or Function it expects the parameter. And we throw this error.

Procedure 'GetTestTable'
expects parameter '@Columnnumeric', which was not supplied.


We should not use the parameter in the procedure if we set
ParameterDirection as ParameterDirection.ReturnValue
in ADO.net.


E.g.
 
CREATE PROCEDURE [dbo].[GetTestTable] (@Columndatetime DATETIME,
                                       @Columnnumeric  NUMERIC
)

AS
BEGIN

      RETURN 15


END


objCmd.Parameters.Add("@Columndatetime",
SqlDbType
.DateTime).Value = objPropertiesClassName.Columndatetime;

objCmd.Parameters.Add("@Columnnumeric",
SqlDbType
.Decimal).Value = objPropertiesClassName.Columnnumeric;

objCmd.Parameters["@Columnnumeric"].Direction =
ParameterDirection
.ReturnValue;

objCmd.ExecuteNonQuery();

int i = (int)objCmd.Parameters["@Columnnumeric"].Value;


Rule 2

Consider that we have given the parameter order as given below.
The parameter @ColumnnTest will contain the return value. We will think that we have specified
the direction ReturnValue to
@Columnnumeric before @ColumnnTest and @Columnnumeric will contain the value. But it is
not like that. Since we added the parameter @ColumnnTest before @Columnnumeric.
It took according to the order of parameter that we are adding to the command.


objCmd.Parameters.Add("@ColumnnTest",
SqlDbType
.Decimal).Value = objPropertiesClassName.Columnnumeric;

objCmd.Parameters.Add("@Columnnumeric",
SqlDbType
.Decimal).Value = objPropertiesClassName.Columnnumeric;

objCmd.Parameters["@Columnnumeric"].Direction =
ParameterDirection
.ReturnValue;

objCmd.Parameters["@ColumnnTest"].Direction =
ParameterDirection
.ReturnValue;

int j = (int)objCmd.Parameters["@ColumnnTest"].Value;

object i = (object)objCmd.Parameters["@Columnnumeric"].Value;


Rule 3

objCmd.Parameters.Add("@ColumnnTest",
SqlDbType
.Decimal).Value = 20.0d;

objCmd.Parameters.Add("@Columnnumeric",
SqlDbType
.Decimal).Value = 10.0d;

objCmd.Parameters["@Columnnumeric"].Direction =
ParameterDirection
.ReturnValue;

objCmd.Parameters["@ColumnnTest"].Direction =
ParameterDirection
.ReturnValue;
 
If the procedure or function
doesn’t return any value, the first added parameter tooks the default value.
 
But the next parameter took
the value that we asigned.
 
Here
@ColumnnTest returns 0.0d, while
("@Columnnumeric
returns the assigned value 10.0d.
 
We can ask instead of ReturnValue can we use ExecuteScalar(), since it also returns
single value.

The ExecuteScalar returns a single value that is in the form of a result set.  That
means the value must be "SELECTed" in the SQL.
I.e. if the result-set contains 3 columns and 2 rows, it took only the 1st
row and 0th column value. The remaining are discarded.

 Using the RETURN keyword is possible through the use of a ReturnValue parameter.
References
Configuring Parameters and Parameter Data Types (ADO.NET)

Examples of using System.Data.ParameterDirection with Sql Server