Saturday, June 21, 2008

File Handling using SQL Server

To write contents to a file through SQL Server, you can use an extended stored procedure called master..xp_cmdshell. However, you can rest assured that good database administrators would definitely have disabled the execution of this stored procedure. So the trick works only if the execution permissions for this stored procedures are granted for the application.

This stored procedure actually executes anything you provide to it as an argument on the command prompt of the machine on which the SQL Server is installed. The execution is the same as if you had a Command Prompt window opened and typed a command.

Now as we know that if we redirect a string(call it st1) to any other arbitrary name string (call st2) , then st2 is created as a file on the machine and st1 is written in that, its syntax will be like this.

echo "your string" >> filename.txt,

This command on the command prompt will write(actually append) your string in filename.txt, If you use '>' in place of '>>' the file contents will be overwritten. In either case a new file will be created if it doesn't already exist.

Now with this info, all you've to do is to execute something like this on the SQL server

exec master..xp_cmdshell 'echo ''your string'' >> filename.txt'

and your file will be written with your message

Trust me, its performance is awesome as you need not create any File object and then call its functions to get the work done. This work is done through IO redirection, which is the fastest way to write a file.

The only disadvantage, and it is a serious one, here is that this stored procedure is infamous for being used as an SQL injection attack. Granting permission for its execution might require that you be extra careful while writing your queries as a small mistake can ensue havoc on the database server. This is because any executable can be run on the machine hosting the SQL server with xp_cmdshell .

SQL Server Constraint Issues

Adding constraints such as check constraints or foreign keys to a table are best practices to keep your data as clean as possible with minimal data enforcement rules performed at the database level. Unfortunately sometimes issues may occur where the data becomes out of synch and one of these constraints has been violated. This may be due to disabled constraints or constraints that are later added with the NOCHECK option. Finding these issues can be done by running queries to check each of the constraints, but is there any easier way to determine if the data the constraints support has been violated?

Solution
As mentioned already, one approach would be to write queries for each of the constraints and check the data to see if the constraints are being enforced. This is probably not all that difficult, but it could be time consuming. Another approach to tackle this issue is to use the DBCC CHECKCONSTRAINTS command. This command allows you to check the constraints to ensure that no data is violating the constraints that have been setup.

This command can be run as follows:

* DBCC CHECKCONSTRAINTS (TableName) - checks an individual table
* DBCC CHECKCONSTRAINTS (ConstraintName) - checks an individual constraint
* DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS - checks all constraints in the database
* DBCC CHECKCONSTRAINTS WITH ALL_ERRORMSGS - returns all rows that violate constraints
* DBCC CHECKCONSTRAINTS WITH NO_INFOMSGS - suppress messages when query runs

Here are some examples of how you can use this command.

Example 1
Here is an example where a foreign key constraint has been disabled to allow you to possibly do some bulk loading of data without checking the FK constraint for each record. This example disables the FK constraint, inserts new records and then tries to enable the FK constraint. When the FK is enabled it will fail, because the new row violates the FK constraint.

-- disable FK constraint

ALTER TABLE HumanResources.EmployeeAddress
NOCHECK CONSTRAINT FK_EmployeeAddress_Employee_EmployeeID;

-- insert new row

-- find current max EmployeeID

DECLARE @maxEmployeeID int
SELECT @maxEmployeeID = MAX(EmployeeID)
FROM HumanResources.Employee

-- add 1 to value

SET @maxEmployeeID = @maxEmployeeID + 1

-- insert new row

INSERT INTO HumanResources.EmployeeAddress
(employeeID, AddressID)
VALUES (@maxEmployeeID, 36)

-- try to enable constraint

ALTER TABLE HumanResources.EmployeeAddress
WITH CHECK CHECK CONSTRAINT FK_EmployeeAddress_Employee_EmployeeID;

When the constraint is enabled with the CHECK option, we get this error.

To find and fix this error we can run the DBCC CHECKCONSTRAINTS command.

--find constraint error

DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS

Now we can fix the record in question, check the constraints again and then enable the constraint.

-- delete row in question

DELETE FROM HumanResources.EmployeeAddress
WHERE employeeID = 291

-- check constraints again

DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS

-- try to enable constraint

ALTER TABLE HumanResources.EmployeeAddress
WITH CHECK CHECK CONSTRAINT FK_EmployeeAddress_Employee_EmployeeID;

Example 2
Another example would be a check constraint on certain values that a column should store. This data could have been pre-populated and you add a new constraint with the NOCHECK option when you create the constraint or again this constraint could have been disabled for some reason.

In this example we create two check constraints that enforce the values for col1 and col2 to be greater than 100. The three rows that are created all violate the constraints for at least one of the columns.
-- create a new table

CREATE TABLE dbo.TestConstraint (col1 int, col2 int, col3 char (30));

-- insert some records

INSERT INTO dbo.TestConstraint VALUES (100, 100, 'Monday')
INSERT INTO dbo.TestConstraint VALUES (100, 99, 'Tuesday')
INSERT INTO dbo.TestConstraint VALUES (101, 98, 'Wednesday')

-- create check constraints with NOCHECK option

ALTER TABLE dbo.TestConstraint WITH NOCHECK
ADD CONSTRAINT chkConstraint_1 CHECK (col1 > 100);

ALTER TABLE dbo.TestConstraint WITH NOCHECK
ADD CONSTRAINT chkConstraint_2 CHECK (col2 > 100);

-- find the problems

DBCC CHECKCONSTRAINTS('dbo.TestConstraint') WITH ALL_CONSTRAINTS

When the DBCC CHECKCONSTRAINTS command is run, this is the output. From the data that we entered there should be three rows of data that should be returned. As you can see this command does not show you the actual records that are in violation, just the values and the columns that are in violation. Also, for the second insert values (100, 99) the 99 also violates the constraint, but this does not show up in the result set.

To get information about each constraint so we can see all of the values in violation we can run the following:
DBCC CHECKCONSTRAINTS('chkConstraint_1')
DBCC CHECKCONSTRAINTS('chkConstraint_2')

At this point you would then need to write queries to find the exact records that are in violation and fix these records. The DBCC CHECKCONSTRAINTS command only shows the constraint that has been violated and the value, but not the primary key value for the record, so there is an additional step to find these records. To find these records you would do something like the following:

SELECT * FROM dbo.TestConstraint WHERE col1 = 100

SELECT * FROM dbo.TestConstraint WHERE col2 IN (98,99,100)

Other Info
By default the DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS option should list all of the constraints that are in violation. As seen in Example 2 it only shows one issue per record and does not list all of them. So this could be a good place to start, but it may be helpful to do each constraint individually. To get a list of all of the constraints in your database you can issue the following command and then run the DBCC CHECKCONSTRAINTS command for each constraint.

SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS

Find Foreign Key

SQL Server Enterprise Manager and Management Studio are pretty good tools for giving you information about a particular object, but when you want to get information across your entire database or server this becomes a bit of a challenge. There are several system stored procedures and now dynamic management views in SQL 2005 to provide some of the information, but there is still a bit of missing functionality if you want to get data across the database or server. One of these recent challenges was getting foreign key information across the entire database. Management Studio has some nice additions where you can see the FK constraints on a table by table basis, but getting all of the foreign keys is a bit more a challenge. There is a stored procedure called sp_fkeys, but this procedure requires you to include at least the primary key table name. So how can you get a complete list?

Solution
There is a wealth of information in the system stored procedures and this is another good way of learning how things work behind the scenes. By taking a look at the stored procedure sp_fkeys for SQL Server 2005 I noticed that it is not very complicated at all. When you pass in the parameters it basically uses the parameters to filter your selection. By making a minor tweak to the SELECT statement we are able to get a list of all FKs in the entire database. Here is the modified query for SQL Server 2005.

SQL Server 2005 Version


SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.SCHEMA_ID)),
PKTABLE_NAME = CONVERT(SYSNAME,O1.NAME),
PKCOLUMN_NAME = CONVERT(SYSNAME,C1.NAME),
FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.SCHEMA_ID)),
FKTABLE_NAME = CONVERT(SYSNAME,O2.NAME),
FKCOLUMN_NAME = CONVERT(SYSNAME,C2.NAME),
-- Force the column to be non-nullable (see SQL BU 325751)
--KEY_SEQ = isnull(convert(smallint,k.constraint_column_id), sysconv(smallint,0)),
UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsUpdateCascade')
WHEN 1 THEN 0
ELSE 1
END),
DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsDeleteCascade')
WHEN 1 THEN 0
ELSE 1
END),
FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.OBJECT_ID)),
PK_NAME = CONVERT(SYSNAME,I.NAME),
DEFERRABILITY = CONVERT(SMALLINT,7) -- SQL_NOT_DEFERRABLE
FROM SYS.ALL_OBJECTS O1,
SYS.ALL_OBJECTS O2,
SYS.ALL_COLUMNS C1,
SYS.ALL_COLUMNS C2,
SYS.FOREIGN_KEYS F
INNER JOIN SYS.FOREIGN_KEY_COLUMNS K
ON (K.CONSTRAINT_OBJECT_ID = F.OBJECT_ID)
INNER JOIN SYS.INDEXES I
ON (F.REFERENCED_OBJECT_ID = I.OBJECT_ID
AND F.KEY_INDEX_ID = I.INDEX_ID)
WHERE O1.OBJECT_ID = F.REFERENCED_OBJECT_ID
AND O2.OBJECT_ID = F.PARENT_OBJECT_ID
AND C1.OBJECT_ID = F.REFERENCED_OBJECT_ID
AND C2.OBJECT_ID = F.PARENT_OBJECT_ID
AND C1.COLUMN_ID = K.REFERENCED_COLUMN_ID
AND C2.COLUMN_ID = K.PARENT_COLUMN_ID


SQL Server 2005 - Version 2

This is another version that was contributed by one of our readers Troy Ketsdever. This uses the INFORMATION_SCHEMA views.

SELECT C.TABLE_CATALOG [PKTABLE_QUALIFIER],
C.TABLE_SCHEMA [PKTABLE_OWNER],
C.TABLE_NAME [PKTABLE_NAME],
KCU.COLUMN_NAME [PKCOLUMN_NAME],
C2.TABLE_CATALOG [FKTABLE_QUALIFIER],
C2.TABLE_SCHEMA [FKTABLE_OWNER],
C2.TABLE_NAME [FKTABLE_NAME],
KCU2.COLUMN_NAME [FKCOLUMN_NAME],
RC.UPDATE_RULE,
RC.DELETE_RULE,
C.CONSTRAINT_NAME [FK_NAME],
C2.CONSTRAINT_NAME [PK_NAME],
CAST(7 AS SMALLINT) [DEFERRABILITY]
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
ON C.CONSTRAINT_SCHEMA = KCU.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
ON C.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C2
ON RC.UNIQUE_CONSTRAINT_SCHEMA = C2.CONSTRAINT_SCHEMA
AND RC.UNIQUE_CONSTRAINT_NAME = C2.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2
ON C2.CONSTRAINT_SCHEMA = KCU2.CONSTRAINT_SCHEMA
AND C2.CONSTRAINT_NAME = KCU2.CONSTRAINT_NAME
AND KCU.ORDINAL_POSITION = KCU2.ORDINAL_POSITION
WHERE C.CONSTRAINT_TYPE = 'FOREIGN KEY'


SQL Server 2000 Version

With SQL Server 2000 it is not as straight forward as using a simple SQL statement as shown above. In order to get this to work for SQL Server 2000 an adjustment was made to the sp_fkeys SP to cursor through all of the user tables. It is not the prettiest method, but it does seem to do the job.

Find Primary Keys

One design aspect that all tables should have is a primary key. The primary key is the main entry way into your dataset, so that when you access your data you are guaranteed to only affect one row of data. Having primary keys are not only a good design feature they also play an important role in replication and data updates especially when there may be duplicate rows of data. So how can you determine what tables have primary keys and what tables do not have primary keys?

Primary keys guarantee a unique row of data in your table. Some of the design aspects of a primary key are as follows:

* can be one or more columns
* column values can not be null
* the column or combination of columns must be unique
* there can only be one primary key on a table



Query 1 - Tables with primary keys

SQL 2005

SELECT c.name, b.name, a.name
FROM sys.key_constraints a
INNER JOIN sys.tables b ON a.parent_object_id = b.OBJECT_ID
INNER JOIN sys.schemas c ON a.schema_id = c.schema_id
WHERE a.type = 'PK'

SQL 2000

SELECT c.name, a.name, b.name
FROM sysobjects a
INNER JOIN sysindexes b ON a.id = b.id
INNER JOIN sysusers c ON a.uid = c.uid
WHERE (b.status & 2048)<>0


Query 2 - Tables without primary keys

SQL 2005

SELECT c.name, b.name
FROM sys.tables b
INNER JOIN sys.schemas c ON b.schema_id = c.schema_id
WHERE b.type = 'U'
AND NOT EXISTS
(SELECT a.name
FROM sys.key_constraints a
WHERE a.parent_object_id = b.OBJECT_ID
AND a.schema_id = c.schema_id
AND a.type = 'PK' )

SQL 2000

SELECT c.name, a.name
FROM sysobjects a
INNER JOIN sysusers c ON a.uid = c.uid
WHERE xtype = 'U'
AND NOT EXISTS
(SELECT b.name
FROM sysindexes b
WHERE a.id = b.id
AND (b.status & 2048)<>0)

Wednesday, June 18, 2008

File Handling throuth SQL

To write contents to a file through SQL Server, you can use an extended stored procedure called master..xp_cmdshell. However, you can rest assured that good database administrators would definitely have disabled the execution of this stored procedure. So the trick works only if the execution permissions for this stored procedures are granted for the application.
This stored procedure actually executes anything you provide to it as an argument on the command prompt of the machine on which the SQL Server is installed. The execution is the same as if you had a Command Prompt window opened and typed a command.
Now as we know that if we redirect a string(call it st1) to any other arbitrary name string (call st2) , then st2 is created as a file on the machine and st1 is written in that, its syntax will be like this.
echo "your string" >> filename.txt,
This command on the command prompt will write(actually append) your string in filename.txt, If you use '>' in place of '>>' the file contents will be overwritten. In either case a new file will be created if it doesn't already exist.
Now with this info, all you've to do is to execute something like this on the SQL serverexec master..xp_cmdshell 'echo ''your string'' >> filename.txt'
and your file will be written with your message
Trust me, its performance is awesome as you need not create any File object and then call its functions to get the work done. This work is done through IO redirection, which is the fastest way to write a file.
The only disadvantage, and it is a serious one, here is that this stored procedure is infamous for being used as an SQL injection attack. Granting permission for its execution might require that you be extra careful while writing your queries as a small mistake can ensue havoc on the database server. This is because any executable can be run on the machine hosting the SQL server with xp_cmdshell .

Foreign Key

Foreign keys are part of the family of constraints that SQL Server provides to ensure database integrity. You may be familiar with other constraint types that help maintain data integrity such as Primary Key constraints, Unique constraints, Default constraints, and Check constraints. Each of these constraint types serves a specific purpose. The foreign key’s purpose is to ensure the relationship integrity between a parent table and its child tables.
You can define a foreign key as follows

ALTER TABLE DBO.ADD CONSTRAINT FOREIGN KEY REFERENCES DBO.(){ON [DELETEUPDATE] CASCADE}


The following example declares that a line item row cannot exist without an associated order header row. The ON DELETE CASCADE option tells the database engine that if the parent ORDER HEADER row’s ORDERNUMBER is deleted, then any LINE ITEM tied to the ORDER HEADER by the deleted ORDERNUMBER should be automatically deleted as well.

ALTER TABLE DBO.LINEITEMADD CONSTRAINT FK_LINEITEM_ORDERNUMBER FOREIGN KEY (ORDERNUMBER)REFERENCES DBO.ORDERHEADER(ORDERNUMBER)ON DELETE CASCADE


There are obvious reasons for defining foreign key constraints in your data model

* They physically define the business by preventing data integrity issues in your database. (e.g. The database prevents line items from being created without an existing order header)

* They logically document the business by showing how all data relates to each other. To someone new to your organization, this allows him/her to get a good understanding of how the business works. (e.g. Every order taken must have a valid customer assigned)

* Foreign Keys are native to SQL Server and are designed to prevent data integrity issues. Business logic developers should not be in the business of verifying table relationships.
The not so obvious

* If defined and indexed correctly, they can be leveraged by the SQL Server query engine to generate extremely efficient query plans.


Unlike primary key constraints and unique constraints, foreign key constraints are not automatically indexed by SQL Server. However, indexing the column used in your foreign key is a good idea for a few reasons.

* Without an index, user deletion of a parent row from the database would force the SQL Server query engine to scan the child table referenced in the foreign key to ensure that data integrity is not compromised. Consider a child table with hundreds of thousands of rows; an index can speed this lookup considerably.

* The performance of the foreign key CASCADE options (ON DELETE CASCADE, ON UPDATE CASCADE) can be improved dramatically with the use of an index since the engine performs a query to search for the rows that should be automatically deleted or updated

* The performance of JOINs between the parent and child tables on the foreign key column is greatly improved. It’s a natural assumption that tables that are related may be queried together to produce result sets. Consider the earlier ORDERHEADER/LINEITEM example. It would be natural for queries to be executed that would require not only elements of the LINE ITEMs but also of the ORDERHEADER (e.g. order date, the CSR who entered the order)

Saturday, June 14, 2008

STORE XML DATA IN SQL TABLE

OPENXML provides a rowset view over an XML document. Because OPENXML is a rowset provider, OPENXML can be used in T-SQL statements in which rowset providers such as a table, view, or the OPENROWSET function can appear.

Syntax:
OPENXML (idoc int [in], rowpattern nvarchar[in], [flags byte[in]])[WITH (SchemaDeclatation TableName)]
Arguments:

idoc:

Is the document handle of the internal representation of an XML document. The internal representation of an XML document is created by calling sp_xml_preparedocument.

rowpattern:
Is the XPath pattern used to identify the nodes (in the XML document whse handle is passed in the idoc parameter) to be processed as rows.

flags:
Indicates the mapping that should be used between the XML data and the relational rowset, and how the spill-over column should be filled. flags is an optional input parameter, and can be on of these values:

0 : Defaults to attribute centric mapping.

1 : Use the attribute-centric mapping.

Can be combined with XML_element: in which case, attribute-centric mapping is applied first, and then element-centric mapping is applied for all columns not yet dealt with.


2 : Use the element-centric mapping.

Can be combined with XML_ATTRIBUTES; in which case, attribute-centric mapping is applied first, and then element-centric mapping is applied for all columns not yet dealt with.

3 : Can be combined (logical OR) with XML_ATTRIBUTES or XML_ELEMENTS.

In context of retrieval, this flag indicates that the consumed data should not be copied to the overflow property @mp:xmltext

SchemaDeclaration:
Is the schema definition of the form:

ColName ColType [ColPattern MetaProperty][, ColName ColType [ColPattern MetaProperty]...]

ColName:

Is the column name in the rowset.

ColType:

Is the SQL data type of the column in the rowset. If the column types differ from the undrelying XML data type of the attribute, type coercion occurs. If the column is of type timestamp, the present values int eh XML documnet is disregarded when selecting from an OPENXML rowset, and the autofill values are returned.


ColPattern:
Is an optional, general XPath pattern that describes how the XML nodes should be mapped to the columns. If the ColPattern is not specified, the default mapping (attribute-centric or element-centric mapping as specified by flags) takes place. The XPath pattern specified as ColPattern is used to specify the special nature of the mapping (in case of attribute-centric and element-centric mapping) that overwrites or enhances the default mapping indicated by flags.


The general XPath pattern specified as ColPattern also supports the metaproperties.

MetaProperty:

Is one of the metaproperties provided by OPENXML. If the metaproperty is specified, the column contains information provided by the metaproperty. The metaproperties allow you to extract information (such as relative position, , namespace information) about XML nodes, which provides more information than is visible in the textual representation.


TableName:

Is the table name that can be given (instead of SchemaDeclaration) if a table with the desired schema already exists and no column patterns are required.


The WITH clause provides a rowset format (and additional mapping information as necessary) using either SchemaDeclaration or specifying an existing TableName. If the optional WITH clause is not specified, the results are returned in an edge table format. Edge tables represent the fine-grained XML document structure (e.g. element/attribute names, the document hierarchy, the namespaces, PIs etc.) in a single table.


This table describes the structure of the edge table.


id : bigint

Is the unique ID of the document node.

The root element has an ID value 0. The negative ID values are reserved.


parentid :

Identifies the parent of the node.

The parent identified by this ID is not necessarily the parent element, but it depends on the NodeType of the node whose parent is identified by this ID. For example, if the node is a text node, the parent of it may be an attribute node. If the node is at the top level in the XML document, its ParentID is NULL.


nodetype :

Identifies the node type.

Is an integer that corresponds to the XML DOM node type numbering (see DOM for node information).

The node types are:
1 = Element node

2 = Attribute node

3 = Text node


localname :

Gives the local name of the element or attribute. Is NULL if the DOM object does not have a name.


prefix :

Is the namespace prefix of the node name.
namespaceuri : nvarchar -- Is the namespace URI of the node.

If the value is NULL, no namespace is present.


datatype :

Is the actual data type of the element or attribute row and is NULL otherwise.

The data type is inferred from the inline DTD or from the inline schema.

prev :

Is the XML ID of the previous sibling element.

Is NULL if there is no direct previous sibling.

text :

Contains the attribute value or the element content in text form (or is NULL if the edge table entry does not need a value).




--STORE XML DATA IN SQL TABLE

DECLARE @idoc INT

DECLARE @doc VARCHAR(8000)

SET @doc ='

<SearchCountryResponse ISO="true">

<CountryDetails>

<Country Code="TT">

<![CDATA[Trinidad & Tobago]]></Country>

<Country Code="TW"><![CDATA[Taiwan]]></Country>

<Country Code="TZ"><![CDATA[Tanzania]]></Country>

<Country Code="UA"><![CDATA[Ukraine]]></Country>

<Country Code="UG"><![CDATA[Uganda]]></Country>

<Country Code="US"><![CDATA[United States]]>

</Country>

<Country Code="UY"><![CDATA[Uruguay]]></Country>

<Country Code="UZ"><![CDATA[Uzbekistan]]>

</Country>

</CountryDetails>

</SearchCountryResponse>'


-- Create an internal representation of the XML document.

EXEC sp_xml_preparedocument @idoc OUTPUT, @doc



-- SELECT statement using OPENXML rowset provider

SELECT *FROM

OPENXML (@idoc, '/SearchCountryResponse/CountryDetails/Country',3)

WITH (

Code varchar(10),

CountryName varchar(20) 'text()'

)

EXEC sp_xml_removedocument @idoc

Wednesday, June 11, 2008

Mutable & Immutable Classes

Create your own pair of mutable and immutable classes similar to String and StringBuilder

Immutability in a "weak" sense (for lack of a better term) means creating a temporary read-only view of otherwise modifiable data. A typical case is implementing an accessor method: one must avoid giving out writable handles to internals of the class implementation. Note that an accessor is not necessarily expected to return the same data every time it is called. The key is not letting the caller subvert the read-only access protocol in place of supported mutator methods.
Immutability in a "strong" sense means locking down a piece of data in perpetuity, such as creating an immutable object instance that cannot be changed by any code. Knowing that such an instance will never change opens doors for a host of other useful patterns. For example, when cloning an object with String fields, it is not necessary to clone them since Strings are immutable.
I illustrate a couple of patterns for separating a class API into mutable and immutable parts here.
Immutable class extended by a companion nonpublic mutable classConsider these three classes:

using System;
using System.Collections;

namespace MyItem
{
public class Item
{
protected int ma, mb;
public Item(int a, int b)
{
ma = a;
mb = b;
}
// ACCESSOR PROPERTIES: [all properties are sealed]
public int A

{
get { return ma; }
}
public int B

{
get { return mb; }
}
}

public sealed class MutableItem : Item
{
public MutableItem(int a, int b) : base(a, b) { }
// MUTATOR PROPERTIES:


public int A
{
set { ma = value; }
}
public int B
{
set { mb = value; }
}
}

public class ItemArray : ICollection
{
private ArrayList _MutableItem;
public ItemArray()
{
this._MutableItem = new ArrayList();
}
public ItemArray(int size)
{
_MutableItem = new ArrayList(size);
for (int i = 0; i < size; i++)
_MutableItem.Add(new MutableItem(0, 0));
}

// ICollection Members
public bool IsSynchronized
{
get { return false; }
}
public int Count
{
get { return this._MutableItem.Count; }
}
public void CopyTo(Array array, int index)
{
_MutableItem.CopyTo(array, index);
}

public object SyncRoot
{
get { return this; }
}

// IEnumerable Member
public IEnumerator GetEnumerator()
{
return _MutableItem.GetEnumerator();
}
// Indexer
public Item this [int index]
{
get { return (Item)this._MutableItem[index]; }
set { this._MutableItem[index] = value; }
}

// Public Method
public void setItem(int index, int a, int b)
{
((MutableItem)_MutableItem[index]).A = a;
((MutableItem)_MutableItem[index]).B = b;
}
}
}


Item is immutable: it has no mutator methods. It is further specialized into MutableItem that adds mutators. Conceptually, this inheritance relationship makes sense: being able to read and write is of course more than just being able to read.
Anything that has a MutableItem instance fully controls its state. However, this access can be restricted to read-only by upcasting such an instance to Item, as demonstrated in the ItemArray Class.
Once you have created an array, you can set its value by calling setItem() method and you can get the value through indexer as well, but once you have fetched the value in an Item object, you cannot change the values of A and B explicitly as shown in the following example:

using System;
using MyItem;

namespace Items

{
class Program
{
static void Main(string[] args)
{
ItemArray arr;
arr = new ItemArray(3);
for (int i = 0; i < 3; i++)
{
Console.WriteLine("i = " + i + ", value = " + arr[i].A.ToString());
Console.WriteLine("i = " + i + ", value = " + arr[i].B.ToString());
}
Console.WriteLine();
arr.setItem(1, 5, 6);

for (int i = 0; i < 3; i++)
{
Console.WriteLine("i = " + i + ", value = " + arr[i].A.ToString());
Console.WriteLine("i = " + i + ", value = " + arr[i].B.ToString());
}
Console.ReadLine();
Console.WriteLine();
Item item = (Item) arr[1];
item.A = 15; // Error: Cannot change item.A
Console.WriteLine(item.A);
Console.WriteLine(item.B);
Console.ReadLine();
}
}
}

Indexer's get property of ItemArray exposes a mutable object in an immutable way. Note that this method has no data copying and no new object allocation, and the overall implementation is very efficient and safe.
Happy Codeing !!!

System.Text.StringBuilder

Represents a mutable string of characters.

This class represents string-like objects that are mutable. After a StringBuilder object has been created, it can be directly modified by removing, replacing, or inserting characters. This contrasts the String class, which represents an immutable string of characters.The System.Text.StringBuilder.Capacity of an instance of the StringBuilder class is the maximum number of characters it can hold in the currently allocated space. The StringBuilder will dynamically allocate more space when it is required.

Unlike most types in the Base Class Library, the arguments to StringBuilder members are assumed to be passed as in / out arguments (passed by reference). [Note: Normally arguments are in arguments (passed by value) unless explicitly declared as out or in / out .]

[Note: An instance of String is said to be "immutable" because its value cannot be modified once it has been created. Methods on String that appear to modify a String instance actually return a new instance containing the modification. The StringBuilder class provides methods that actually modify the contents of a string-like object.

Relational operators only perform reference comparisons (unless overloaded by a particular language compiler). Despite this restriction, relational operators can be used to compare String objects that are assigned literal values. Their values are immutable and can't change, so a reference comparison is sufficient. Because StringBuilder instances are mutable, they should not be compared with relational operators.

System.String

An index is the position of a character within a string. The first character in the string is at index 0. The length of a string is the number of characters it is made up of. The last accessible index of a string instance is System.String.Length - 1.

Strings are immutable; once created, the contents of a String do not change. Combining operations, such as System.String.Replace(System.Char,System.Char), cannot alter existing strings. Instead, such operations return a new string that contains the results of the operation, an unchanged string, or the null value. To perform modifications to a String use the StringBuilder .

The following characters are considered white space when present in a String instance: 0x9, 0xA, 0xB, 0xC, 0xD, 0x20, 0xA0, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x200B, 0x3000, and 0xFEFF. The null character is defined as hexadecimal 0x00.

The String(String) constructor is omitted for performance reasons. If you need a copy of a String, consider using System.String.Copy(System.String) or the StringBuilder class.

To insert a formatted string representation of an object into a string, use the System.String.Format(System.String,System.Object) methods. These methods take one or more arguments to be formatted, and a format string.

To insert a formatted string representation of an object into a string, use the System.String.Format(System.String,System.Object) methods. These methods take one or more arguments to be formatted, and a format string.

String vs StringBuilder

Mutable Objects: The objects whose values can be changed are called mutable objects.

Immutable Objects : An object qualifies as being called immutable if its value cannot be modified once it has been created.

Strings are Immutable. Methods that appear to modify a String actually return a new String containing the modification. We modify strings all the time in our code. This may appear as mutable - but it is not. What actually happens is the string variable/object has been changed to reference a new string value containing the results of your new string value.

For this very reason .NET has the System.Text.StringBuilder class. If you find it necessary to modify the actual contents of a string-like object heavily, such as in a for or foreach loop, use the System.Text.StringBuilder class. It is a mutable version of String.

But never confuse that System.Text.StringBuilder is inheriting the System.String Class. There are two causes:

1) If this would have happened, we would have got all or most of the methods (Or we may not as we have, get the methods at all being all the methods sealed)

2) The comment of the point (1) is right. System.String is a SEALED class.

Tuesday, June 10, 2008

Constraints

The primary job of a constraint is to enforce a rule in the database. The constraints in a database maintain the integrity of the database. For instance, we have foreign key constraints to ensure all orders reference existing products. You cannot enter an order for a product the database does not know about. Maintaining integrity is of utmost importance for a database,
so much so that we cannot trust users and applications to enforce these rules by themselves. Once integrity is lost, you may find customers are double billed, payments to the supplier are missing, and everyone loses faith in your application.


Data integrity rules fall into one of three categories: entity, referential, and domain. We want to briefly describe these terms to provide a complete discussion.


Entity IntegrityEntity integrity ensures each row in a table is a uniquely identifiable entity. You can apply entity integrity to a table by specifying a PRIMARY KEY constraint. For example, the ProductID column of the Products table is a primary key for the table.


Referential Integrity
Referential integrity ensures the relationships between tables remain preserved as data is inserted, deleted, and modified. You can apply referential integrity using a FOREIGN KEY constraint. The ProductID column of the Order Details table has a foreign key constraint applied referencing the Orders table. The constraint prevents an Order Detail record from using a
ProductID that does not exist in the database. Also, you cannot remove a row from the Products table if an order detail references the ProductID of the row.


Entity and referential integrity together form key integrity.

Domain Integrity
Domain integrity ensures the data values inside a database follow defined rules for values, range, and format. A database can enforce these rules using a variety of techniques, including CHECK constraints, UNIQUE constraints, and DEFAULT constraints.

These are the constraints we will cover in this article, but be aware there are other options available to enforce domain integrity. Even the selection of the data type for a column enforces domain integrity to some extent. For instance, the selection of datetime for a column data type is more restrictive than a free format varchar field.

The following list gives a sampling of domain integrity constraints.


A product name cannot be NULL. A product name must be unique. The date of an order must not be in the future. The product quantity in an order must be greater than zero.


Unique Constraints
As we have already discussed, a unique constraint uses an index to ensure a column (or set of columns) contains no duplicate values. By creating a unique constraint, instead of just a unique index, you are telling the database you really want to enforce a rule, and are not just providing an index for query optimization. The database will not allow someone to drop the
index without first dropping the constraint.

From a SQL point of view, there are three methods available to add a unique constraint to a table. The first method is to create the constraint inside of CREATE TABLE as a column constraint. A column constraint applies to only a single column. The following SQL will create a unique constraint on a new table: Products_2.

CREATE TABLE Products_2 ( ProductID int PRIMARY KEY, ProductName nvarchar (40) Constraint IX_ProductName UNIQUE)

This command will actually create two unique indexes. One is the unique, clustered index given by default to the primary key of a table. The second is the unique index using the ProductName column as a key and enforcing our constraint.


A different syntax allows you to create a table constraint. Unlike a column constraint, a table constraint is able to enforce a rule across multiple columns. A table constraint is a separate element in the CREATE TABLE command. We will see an example of using multiple columns when we build a special CHECK constraint later in the article. Notice there is now a comma after
the ProductName column definition.

CREATE TABLE Products_2 ( ProductID int PRIMARY KEY, ProductName nvarchar (40), CONSTRAINT IX_ProductName UNIQUE(ProductName) )

The final way to create a constraint via SQL is to add a constraint to an existing table using the ALTER TABLE command, as shown in the following command:

CREATE TABLE Products_2( ProductID int PRIMARY KEY, ProductName nvarchar (40))
ALTER TABLE Products_2 ADD CONSTRAINT IX_ProductName UNIQUE (ProductName)



If duplicate data values exist in the table when the ALTER TABLE command runs, you can expect an error message similr to the following:

Server: Msg 1505, Level 16, State 1, Line 1CREATE UNIQUE INDEX terminated because a duplicate key was found for index ID 2. Most significant primary key is 'Hamburger'.Server: Msg 1750, Level 16, State 1, Line 1Could not create constraint. See previous errors.The statement has been terminated.


Check Constraints
Check constraints contain an expression the database will evaluate when you modify or insert a row. If the expression evaluates to false, the database will not save the row. Building a check constraint is similar to building a WHERE clause.

You can use many of the same operators (>, <, <=, >=, <>, =) in additional to BETWEEN, IN, LIKE, and NULL. You can also build expressions around AND and OR operators. You can use check constraints to implement business rules, and tighten down the allowed values and formats allowed for a particular column.

We can use the same three techniques we learned earlier to create a check constraint using SQL. The first technique places the constraint after the column definition, as shown below. Note the constraint name is optional for unique and check constraints.

CREATE TABLE Products_2( ProductID int PRIMARY KEY, UnitPrice money CHECK(UnitPrice > 0 AND UnitPrice <100)

In the above example we are restricting values in the UnitPrice column between 0 and 100. Let’s try to insert a value outside of this range with the following SQL.

INSERT INTO Products_2 VALUES(1, 101)

The database will not save the values and should respond with the following error.

Server: Msg 547, Level 16, State 1, Line 1INSERT statement conflicted with COLUMN CHECK constraint 'CK__Products___UnitP__2739D489'.The conflict occurred in database 'Northwind', table 'Products_2', column 'UnitPrice'.The statement has been terminated.


The following sample creates the constraint as a table constraint, separate from the column definitions.

CREATE TABLE Products_2( ProductID int PRIMARY KEY, UnitPrice money, CONSTRAINT CK_UnitPrice2 CHECK(UnitPrice > 0 AND UnitPrice < 100)

Remember, with a table constraint you can reference multiple columns. The constraint in the following example will ensure we have either a telephone number or a fax number for every customer.

CREATE TABLE Customers_2 ( CustomerID int, Phone varchar(24), Fax varchar(24), CONSTRAINT CK_PhoneOrFax CHECK(Fax IS NOT NULL OR PHONE IS NOT NULL))


You can also add check constraints to a table after a table exists using the ALTER TABLE syntax. The following constraint will ensure an employee date of hire is always in the past by using the system function GETTIME.

CREATE TABLE Employees_2( EmployeeID int, HireDate datetime)
ALTER TABLE Employees_2 ADD CONSTRAINT CK_HireDate CHECK(hiredate < getdate())<>


Check Constraints and Existing Values
As with UNIQUE constraints, adding a CHECK constraint after a table is populated runs a chance of failure, because the database will check existing data for conformance. This is not optional behavior with a unique constraint, but it is possible to avoid the conformance test when adding a CHECK constraint using WITH NOCHECK syntax in SQL.

CREATE TABLE Employees_2( EmployeeID int, Salary money)
INSERT INTO Employees_2 VALUES(1, -1)
ALTER TABLE Employees_2 WITH NOCHECK ADD CONSTRAINT CK_Salary CHECK(Salary > 0)



Check Constraints and NULL Values

Earlier in this section we mentioned how the database will only stop a data modification when a check restraint returns false. We did not mention, however, how the database allows the modification to take place if the result is logically unknown. A logically unknown expression happens when a NULL value is present in an expression. For example, let’s use the following insert statement on the last table created above.

INSERT INTO Employees_2 (EmployeeID, Salary) VALUES(2, NULL)

Even with the constraint on salary (Salary > 0) in place, the INSERT is successful. A NULL value makes the expression logically unknown. A CHECK constraint will only fail an INSERT or UPDATE if the expression in the constraint explicitly returns false. An expression returning true, or a logically unknown expression will let the command succeed.

Restrictions On Check ConstraintsAlthough check constraints are by far the easiest way to enforce domain integrity in a database, they do have some limitations, namely:

1) A check constraint cannot reference a different row in a table.
2) A check constraint cannot reference a column in a different table.

NULL ConstraintsAlthough not a constraint in the strictest definition, the decision to allow NULL values in a column or not is a type of rule enforcement for domain integrity.

Using SQL you can use NULL or NOT NULL on a column definition to explicitly set the nullability of a column. In the following example table, the FirstName column will accept NULL values while LastName always requires a non NULL value. Primary key columns require a NOT NULL setting, and default to this setting if not specified.

CREATE TABLE Employees_2 ( EmployeeID int PRIMARY KEY, FirstName varchar(50) NULL, LastName varchar(50) NOT NULL,)

If you do not explicitly set a column to allow or disallow NULL values, the database uses a number of rules to determine the "nullability" of the column, including current configuration settings on the server. I recommended you always define a column explicitly as NULL or NOT NULL in your scripts to avoid problems when moving between different server environments.
Given the above table definition, the following two INSERT statements can succeed.

INSERT INTO Employees_2 VALUES(1, 'Jitendra', 'Gupta')INSERT INTO Employees_2 VALUES(2, NULL, 'Sharma')

However, the following INSERT statement should fail with the error shown below.

INSERT INTO Employees_2 VALUES(3, 'Shashi', NULL)

Server: Msg 515, Level 16, State 2, Line 1Cannot insert the value NULL into column 'LastName', table 'Northwind.dbo.Employees_2'; column does not allow nulls. INSERT fails.The statement has been terminated.


You can declare columns in a unique constraint to allow NULL values. However, the constraint checking considers NULL values as equal, so on a single column unique constraint, the database allows only one row to have a NULL value.

Default ConstraintsDefault constraints apply a value to a column when an INSERT statement does not specify the value for the column. Although default constraints do not enforce a rule like the other constraints we have seen, they do provide the proper values to keep domain integrity in tact. A default can assign a constant value, the value of a system function, or NULL to a column. You can use a default on any column except IDENTITY columns and columns of type timestamp.

The following example demonstrates how to place the default value inline with the column definition. We also mix in some of the other constraints we have seen in this article to show you how you can put everything together.

CREATE TABLE Orders_2( OrderID int IDENTITY NOT NULL , EmployeeID int NOT NULL , OrderDate datetime NULL DEFAULT(GETDATE()), Freight money NULL DEFAULT (0) CHECK(Freight >= 0), ShipAddress nvarchar (60) NULL DEFAULT('NO SHIPPING ADDRESS'), EnteredBy nvarchar (60) NOT NULL DEFAULT(SUSER_SNAME()))

We can examine the behavior of the defaults with the following INSERT statement, placing values only in the EmployeeID and Frieght fields.

INSERT INTO Orders_2 (EmployeeID, Freight) VALUES(1, NULL)

If we then query the table to see the row we just inserted, we should see the following results.

OrderID:1

EmployeeID:1

OrderDate:2003-01-02

Freight: NULL

ShipAddress: NO

SHIPPING ADDRESS

EnteredBy: sa


Notice the Freight column did not receive the default value of 0. Specifying a NULL value is not the equivalent of leaving the column value unspecified, the database does not use the default and NULL is placed in the column instead.

Maintaining ConstraintsIn this section we will examine how to delete an existing constraint. We will also take a look at a special capability to temporarily disable constraints for special processing scenarios.



Dropping Constraints
First, let’s remove the check on UnitPrice in Product table.
ALTER TABLE Products DROP CONSTRAINT CK_Products_UnitPrice
If all you need to do is drop a constraint to allow a one time circumvention of the rules enforcement, a better solution is to temporarily disable the constraint, as we explain in the next section.


Disabling Constraints
Special situations often arise in database development where it is convenient to temporarily relax the rules. For example, it is often easier to load initial values into a database one table at a time, without worrying with foreign key constraints and checks until all of the tables have finished loading. After the import is complete, you can turn constraint checking back on and know the database is once again protecting the integrity of the data.

Note: The only constraints you can disable are the FOREIGN KEY constraint, and the CHECK constraint. PRIMARY KEY, UNIQUE, and DEFAULT constraints are always active.

Disabling a constraint using SQL is done through the ALTER TABLE command. The following statements disable the CHECK constraint on the UnitsOnOrder column, and the FOREIGN KEY constraint on the CategoryID column.

ALTER TABLE Products NOCHECK CONSTRAINT CK_UnitsOnOrder ALTER TABLE Products NOCHECK CONSTRAINT FK_Products_Categories

If you need to disable all of the constraints on a table, manually navigating through the interface or writing a SQL command for each constraint may prove to be a laborious process. There is an easy alternative using the ALL keyword, as shown below:


ALTER TABLE Products NOCHECK CONSTRAINT ALL


You can re-enable just the CK_UnitsOnOrder constraint again with the following statement:

ALTER TABLE Products CHECK CONSTRAINT CK_UnitsOnOrder



When a disabled constraint is re-enabled, the database does not check to ensure any of the existing data meets the constraints. We will touch on this subject shortly. To turn on all constraints for the Products table, use the following command:

ALTER TABLE Products CHECK CONSTRAINT ALL

Manually Checking ConstaintsWith the ability to disable and re-enable constraints, and the ability to add constraints to a table using the WITH NOCHECK option, you can certainly run into a condition where the referential or domain integrity of your database is compromised. For
example, let’s imagine we ran the following INSERT statement after disabling the CK_UnitsOnOrder constraint:

INSERT INTO Products (ProductName, UnitsOnOrder) VALUES('Scott''s Stuffed Shells', -1)


The above insert statement inserts a -1 into the UnitsOnOrder column, a clear violation of the CHECK constraint in place on the column. When we re-enable the constraint, SQL Server will not complain as the data is not checked. Fortunately, SQL Server provides a Database Console Command you can run from any query tool to check all enabled constraints in a database or
table. With CK_UnitsOnOrder re-enabled, we can use the following command to check for constraint violations in the Products table.


dbcc checkconstraints(Products)

To check an entire database, omit the parentheses and parameter from the DBCC command. The above command will give the following output and find the violated constraint in the Products table.

Table Constraint Where
--------- ---------------- --------------------
Products CK_UnitsOnOrder UnitsOnOrder = '-1'

You can use the information in the DBCC output to track down the offending row.




Monday, June 9, 2008

PATINDEX

PatIndex is one of most powerful functions of t-SQL but often developers ignore it firstly because of the availability of CharIndex and secondly, the difficulty of creating patterns for PatIndex to search. Developers try to solve some typical problems faced by today’s web application by developing their own workarounds instead of using PatIndex. Today, I will share some very useful tricks which can help you to make sure that your input string is according to the pattern you want like all numeric, all letters, starts with letter and end with number etc.
Following are the TSQL scripts which you can use to solve these type of problems. You can convert them to user defined functions as per your requirements:



Checks that input only contains numbers

if PatIndex(‘%[^0-9]%’,‘11′) > 0
Begin
Print ‘Not all numbers’
End
Else
Begin
Print ‘All numbers’
End


Checks that input only contains letters

if PatIndex(‘%[^a-z]%’,‘aaaaa’) > 0
Begin
Print ‘Not all letters’
End
Else
Begin
Print ‘All letters’
End


Checking for mixed input

If PatIndex(‘%[^0-9][0-9]%’,‘abc’) > 0
Begin
Print ‘Alpha numeric data’
End
Else
Begin
Print ‘Either all numbers or all letters’
End



Checks that value must start with a letter and a number

If PatIndex(‘[^0-9][0-9]%’,‘A1anamwar11′) > 0
Begin
Print ‘Starts with a letter and a number’
End
Else
Begin
Print ‘Does not start with a letter and a number’
End


Checks that value must End with a letter and a number

If PatIndex(‘%[^0-9][0-9]‘,‘A1anamwar11a1′) > 0
Begin
Print ‘Ends with a letter and a number’
End
Else
Begin
Print ‘Does not End with a letter and a number’
End


Checks that value must Start with a letter and Ends with a number

If PatIndex(‘[^0-9]%[0-9]‘,‘namwar1′) > 0
Begin
Print ‘Starts with a letter and ends with a number’
End
Else
Begin
Print ‘Does not start with a letter and ends with a number’
End

SQL Rules

I am working on a database building for a huge XML engine. This will store data of many service providers and Hotel suppliers. I came with a need to validate fields at three levels : Client side, Server side and Validation in database; for the purpose of security.
As right now I am designing and developing database, I came with a thought to impose rules to maximum columns. This will provide a validation at database level.
May this post help you in some regard.

1) First create rule.
2) bind rule to table's column.
Create Rule:

Let us create rule for Email validation
CREATE RULE Email_Rule
AS CHARINDEX(' ',LTRIM(RTRIM(@Email))) = 0

-- No embedded spaces

AND LEFT(LTRIM(@Email),1) <> '@'

-- '@' can't be the first character of an email address

AND RIGHT(RTRIM(@Email),1) <> '.'

-- '.' can't be the last character of an email address

AND CHARINDEX('.',@Email,CHARINDEX('@',@Email)) - CHARINDEX('@',@Email) > 1

-- There must be a '.' after '@'

AND LEN(LTRIM(RTRIM(@Email))) - LEN(REPLACE(LTRIM(RTRIM(@Email)),'@','')) = 1

-- Only one '@' sign is allowed

AND CHARINDEX('.',REVERSE(LTRIM(RTRIM(@Email)))) >= 3

-- Domain name should end with at least 2 character extension

AND (CHARINDEX('.@',@Email) = 0 AND CHARINDEX('..',@Email) = 0)

-- can't have patterns like '.@' and '..'


Bind this rule to Email field of Address table:

EXEC sp_bindrule 'Email_Rule', 'Address.Email'


You can also drop rules:
drop rule Email_Rule
But before droping rule you MUST unbind rule from any column which it is attatched to:

EXEC sp_unbindrule 'Address.Email'
It is a tough task in a large database to find which table's which column the rule is bound. There is a very easy query to find this:
SELECT name FROM sysobjects WHERE name = 'phone_rule' AND type = 'R'

targetNamespace

Namespaces in XML schema have a lot of significance. As we always (generally) see XMLSchema namespace associated to each schema we come across. This is the schema which defines the basic-building-block-components like simpleType, complexType, sequence, choice, element, attribute, attributeGroup, minOccurs, maxOccurs etc.


The second type of namespace need to be associated is targetNamespace. This namespace is used just to refer to the component in your document. Every component, if qualified, must be in some namespace. If you want to reuse a qualified element in your document, you need to provide a targetNamespace. And if you refer to a global element in you schema within your same schema, or any other schema where you have included this schema, you need to put like this

This statement tells the compiler to put the referred element here.

Friday, June 6, 2008

Patterns in XML Schema

If you want to have <, > " & \ and other special character in a section, and want to restrict the user to enter some character and you have used restriction on simple type and have used pattern, then you will find dificult to define the pattern. Cause :
1. <> is not an ordinary character but is the closing angle bracket for tag.
3. " is used to define a string and your value for the pattern is also a string to be set for pattern and has " enclosing the pattern.
4. & is a special character (discussed later)
5. \ is used as escape sequence.

You can not use escape character for escaping <, >, ", or &.
Instead use
&lt;for < &gt; for >
& for & (& cannot be used solely because the compiler considers that it is being used to define a name as in < or > or & and looks for a semicolon (;) further and when it does not find one reports an error)
\\ for \
For " (double quote) use single quote(') as the bounding boundries of the value part of the pattern and use " (double quote) in the pattern-value like

<xsd:simpletype name="text">
<xsd:restriction base="xsd:string">
<xsd:pattern value='([&lt;&gt;%"&amp;\\])'/>
</xsd:restriction>
</xsd:simpleType>

Server.Transfer() Vs Response.Redirect()

The majority use Response.Redirect to send the user to another page, some seem to prefer the rather mysterious-sounding Server.Transfer. So, what's the difference?


Well, Response.Redirect simply sends a message down to the browser, telling it to move to another page. So, you may run code like:
Response.Redirect("WebForm2.aspx") or
Response.Redirect("http://www.forevacations.com/") to send the user to another page.
Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer("WebForm2.aspx"). However, the statement has a number of distinct advantages and disadvantages.


Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.
But watch out: because the "transfer" process can work on only those sites running on the server, you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.


Secondly, Server.Transfer maintains the original URL in the browser. It may make for confusion when debugging.


That's not all: The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.


For example, if your WebForm1.aspx has a TextBox control called TextBox1 and you transferred to WebForm2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").


This technique is great for wizard-style input forms split over multiple pages. But there's another thing you'll want to watch out for when using the preserveForm parameter. ASP.NET has a bug whereby, in certain situations, an error will occur when attempting to transfer the form and query string values.


The unofficial solution is to set the enableViewStateMac property to True on the page you'll be transferring to, then set it back to False. This records that you want a definitive False value for this property and resolves the bug.


So, in brief: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.

Restrictions in XML Schema

enumeration
Defines a list of acceptable values

fractionDigits
Specifies the maximum number of decimal places allowed. Must be equal to or greater than zero.totalDigitsSpecifies the exact number of digits allowed. Must be greater than zero.

length
Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero. The number of characters should be EQUAL to the LENGTH specified.

maxLength
Specifies the maximum number of characters or list items allowed. The number of characters CAN NOT EXCEED the maxLength specified. maxLength Must be equal to or greater than zero.

minLength
Specifies the minimum number of characters or list items allowed.The number of characters CAN NOT BE LESS THAN the minLength specified. minLength Must be equal to or greater than zero.

maxExclusive
Specifies the upper bounds for numeric values EXCLUSIVE THE maxExclusive. The numeric value CAN NOT EXCEED ONE LESS THAN the maxLength specified. The value must be less than maxExclusive.

minExclusive
Specifies the lower bounds for numeric values EXCLUSIVE THE minExclusive. The numeric value CAN NOT BE LESS THAN the (maxLength + 1). The value must be greater than minExclusive.

maxInclusive
Specifies the upper bounds for numeric values. The numeric value CAN NOT EXCEED the maxLength specified. The value must be less than or equal to maxInclusive.

minInclusive
Specifies the lower bounds for numeric values. The numeric value CAN NOT BE LESS THAN the maxLength. The value must be greater than or equal to this value.

pattern
Defines the exact sequence of characters that are acceptable .

whiteSpace
Specifies how white space (line feeds, tabs, spaces, and carriage returns) is handled.

Thursday, June 5, 2008

About My Experience

First Project : Web-based Billing software of Limco Sales Corporation
I feel satisfactory to say that I am working on my 5th project. And I have worked solely on each project. I learnt lots of thing in course of these projects. But could have learnt much more if there would be any Team Leader / Project Leader guiding me.

My first project was a Billing web based software for Limco Sales Corporation. This company deals with SIM services. It is SIM vender to the foreigner and other mainly in ambassy. They used to generate their own Bills for call minute usage, messages and other services used. They used to have their own call charges which generally differ from that of Service Providers.

As this was my first project, I had to work hard. I got real time knowledge of Database. I used very complex features of SQL Server. They used to provide us with their bills in soft form. I had to save all those bills in database. I created my own customed parser for reading billing information. It enjoyed advanced Regular expression and string manipulations. They used to provide us with excel and text files of huge weight (30 to 50 MB) with billing information. This led me to explore other way of moving data into SQL Database which I have discussed under the label SQL and Post SQL Questions.

I worked also on Crystal Report for generation of Physical Bill. This is a great tool for bill or voucher generation. It takes a datasourse for data access from and displays data on bill/voucher.

The hardest job with this project was data-transfer from existing database to new database. It was really very complicated. It took great effort to transfer data from one old table on existing server to new server's new table. Basically Tables were not identical and data were scattered. Transfer of relevent data from old table to new ONE table took many steps to be transfered. I used to rename column and change datatype of column several time for data to be transferred. It was a great experience. Sometimes it took 15 - 20 min to transfer data from one table to other.

Over all it was a great experience, and gave me a lot of confidence in myself.

Wednesday, June 4, 2008

SQL Questions

How to copy structure only from a table?

select * Into NEWTABLE from OLDTABLE where 1=2

Without Data :
select * into temp2 from temp where 1=2

With Data :
select * into temp2 from temp

SELECT TOP 0 * INTO Test1 FROM Test


How to insert rows in a table from Excel worksheet?

INSERT INTO dbo.TableName
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\LIMCO.xls', [Sheet2$])


Moving data into SQL Server
Moving data into SQL Server is something that most DBAs or Developers are faced with probably on a daily basis. One simple way of doing this is by using the Import / Export wizard, but along with this option there are several other ways of loading data into SQL Server tables. Another common technique would be to use either DTS (SQL 2000) or SSIS (SQL 2005). In this tip we take a look at some of these other options for importing data into SQL Server.
In addition to using the Import / Export wizards and/or DTS or SSIS to move data into SQL Server there are also a few other options for doing this that are built into SQL Server. Some these other options include bcp, BULK INSERT, OPENROWSET as well as others. The following examples show you some of these different options for importing data and how you can use some of these inline with your T-SQL code as well as others that can be run from the command line.

BCP
This is one of the options that is mostly widely used. One reason for this is that it has been around for awhile, so DBAs have come quite familiar with this command. This command allows you to both import and export data, but is primarily used for text data formats. In addition, this command is generally run from a Windows command prompt, but could also be called from a stored procedure by using xp_cmdshell or called from a DTS or SSIS package.
Here is a simple command for importing data from file C:\ImportData.txt into table dbo.ImportTest.

bcp dbo.ImportTest in 'C:\ImportData.txt' -T -SserverName\instanceName

BULK INSERT
This command is a T-SQL command that allows you to import data directly from within SQL Server by using T-SQL. This command imports data from file C:\ImportData.txt into table dbo.ImportTest.

BULK INSERT dbo.ImportTest FROM 'C:\ImportData.txt' WITH ( FIELDTERMINATOR =',', FIRSTROW = 2 )

OPENROWSET
This command is a T-SQL command that allows you to query data from other data sources directly from within SQL Server. By using this command along with an INSERT INTO command we can load data from the specified data source into a SQL Server table.
This command will pull in all data from worksheet [Sheet1$]. By using the INSERT INTO command you can insert the query results into table dbo.ImportTest.

INSERT INTO dbo.ImportTest SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\ImportData.xls', [Sheet1$])


Here is another example where data is pulled from worksheet [Sheet1$] by using a SELECT * FROM command. Again, by using the INSERT INTO command you can insert the query results into table dbo.ImportTest. The query can be any valid SQL query, so you can filter the columns and rows by using this option.

INSERT INTO dbo.ImportTest SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\ImportData.xls', 'SELECT * FROM [Sheet1$]')

OPENDATASOURCE
This command is a T-SQL command that allows you to query data from other data sources directly from within SQL Server. This is similar to the OPENROWSET command.

INSERT INTO dbo.ImportTest SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', 'Data Source=C:\ImportData.xls;Extended Properties=Excel 8.0')...[Sheet1$]

OPENQUERY
Another option is OPENQUERY. This is another command that allows you to issue a T-SQL command to select data and again with the INSERT INTO option we can load data into our table. There are two steps with this process, first a linked server is setup and then second the query is issued using the OPENQUERY command. This option allow you to filter the columns and rows by the query that is issued against your linked data source.

EXEC sp_addlinkedserver 'ImportData', 'Jet 4.0', 'Microsoft.Jet.OLEDB.4.0', 'C:\ImportData.xls', NULL, 'Excel 8.0' GO INSERT INTO dbo.ImportTest SELECT * FROM OPENQUERY(ImportData, 'SELECT * FROM [Sheet1$]')

Linked Servers
Here is yet another option with setting up a linked server and then issuing a straight SQL statement against the linked server. This again has two steps, first the linked server is setup and secondly a SQL command is issued against the linked data source.

EXEC sp_addlinkedserver 'ImportData', 'Jet 4.0', 'Microsoft.Jet.OLEDB.4.0', 'C:\ImportData.xls', NULL, 'Excel 8.0' GO INSERT INTO dbo.ImportTest SELECT * FROM ImportData...Sheet1$

As you can see SQL Server offers many ways of importing data into SQL Server. Take a look at these different options to see what satisfies your database requirements.

Happy SQLing...