Wednesday, April 18, 2007
Tuesday, March 20, 2007
Return IDENTITY value
SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are similar functions in that they return values inserted into IDENTITY columns.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope.
SCOPE_IDENTITY and @@IDENTITY will return last identity values generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.
For example, you have two tables, T1 and T2, and an INSERT trigger defined on T1. When a row is inserted to T1, the trigger fires and inserts a row in T2. This scenario illustrates two scopes: the insert on T1, and the insert on T2 as a result of the trigger.
Assuming that both T1 and T2 have IDENTITY columns, @@IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on T1.
@@IDENTITY will return the last IDENTITY column value inserted across any scope in the current session, which is the value inserted in T2.
SCOPE_IDENTITY() will return the IDENTITY value inserted in T1, which was the last INSERT that occurred in the same scope. The SCOPE_IDENTITY() function will return the NULL value if the function is invoked before any insert statements into an identity column occur in the scope.
Failed statements and transactions can alter the current identity for a table and create gaps in the identity column values. The identity value is never rolled back even though the transaction that attempted to insert the value into the table is not committed. For example, if an INSERT statement fails because of an IGNORE_DUP_KEY violation, the current identity value for the table is still incremented.
Examples:
The following example creates two tables, TZ and TY, and an INSERT trigger on TZ. When a row is inserted to table TZ, the trigger (Ztrig) fires and inserts a row in TY.
USE tempdb
GO
CREATE TABLE TZ (
Z_id int IDENTITY(1,1)PRIMARY KEY,
Z_name varchar(20) NOT NULL)
INSERT TZ
VALUES ('Lisa')
INSERT TZ
VALUES ('Mike')
INSERT TZ
VALUES ('Carla')
SELECT * FROM TZ
--Result set: This is how table TZ looks
Z_id Z_name
-------------
1 Lisa
2 Mike
3 Carla
CREATE TABLE TY (
Y_id int IDENTITY(100,5)PRIMARY KEY,
Y_name varchar(20) NULL)
INSERT TY (Y_name)
VALUES ('boathouse')
INSERT TY (Y_name)
VALUES ('rocks')
INSERT TY (Y_name)
VALUES ('elevator')
SELECT * FROM TY
--Result set: This is how TY looks:
Y_id Y_name
---------------
100 boathouse
105 rocks
110 elevator
/*Create the trigger that inserts a row in table TY
when a row is inserted in table TZ*/
CREATE TRIGGER Ztrig
ON TZ
FOR INSERT AS
BEGIN
INSERT TY VALUES ('')
END
/*FIRE the trigger and find out what identity values you get
with the @@IDENTITY and SCOPE_IDENTITY functions*/
INSERT TZ VALUES ('Rosalie')
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
GO
SELECT @@IDENTITY AS [@@IDENTITY]
GO
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope.
SCOPE_IDENTITY and @@IDENTITY will return last identity values generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.
For example, you have two tables, T1 and T2, and an INSERT trigger defined on T1. When a row is inserted to T1, the trigger fires and inserts a row in T2. This scenario illustrates two scopes: the insert on T1, and the insert on T2 as a result of the trigger.
Assuming that both T1 and T2 have IDENTITY columns, @@IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on T1.
@@IDENTITY will return the last IDENTITY column value inserted across any scope in the current session, which is the value inserted in T2.
SCOPE_IDENTITY() will return the IDENTITY value inserted in T1, which was the last INSERT that occurred in the same scope. The SCOPE_IDENTITY() function will return the NULL value if the function is invoked before any insert statements into an identity column occur in the scope.
Failed statements and transactions can alter the current identity for a table and create gaps in the identity column values. The identity value is never rolled back even though the transaction that attempted to insert the value into the table is not committed. For example, if an INSERT statement fails because of an IGNORE_DUP_KEY violation, the current identity value for the table is still incremented.
Examples:
The following example creates two tables, TZ and TY, and an INSERT trigger on TZ. When a row is inserted to table TZ, the trigger (Ztrig) fires and inserts a row in TY.
USE tempdb
GO
CREATE TABLE TZ (
Z_id int IDENTITY(1,1)PRIMARY KEY,
Z_name varchar(20) NOT NULL)
INSERT TZ
VALUES ('Lisa')
INSERT TZ
VALUES ('Mike')
INSERT TZ
VALUES ('Carla')
SELECT * FROM TZ
--Result set: This is how table TZ looks
Z_id Z_name
-------------
1 Lisa
2 Mike
3 Carla
CREATE TABLE TY (
Y_id int IDENTITY(100,5)PRIMARY KEY,
Y_name varchar(20) NULL)
INSERT TY (Y_name)
VALUES ('boathouse')
INSERT TY (Y_name)
VALUES ('rocks')
INSERT TY (Y_name)
VALUES ('elevator')
SELECT * FROM TY
--Result set: This is how TY looks:
Y_id Y_name
---------------
100 boathouse
105 rocks
110 elevator
/*Create the trigger that inserts a row in table TY
when a row is inserted in table TZ*/
CREATE TRIGGER Ztrig
ON TZ
FOR INSERT AS
BEGIN
INSERT TY VALUES ('')
END
/*FIRE the trigger and find out what identity values you get
with the @@IDENTITY and SCOPE_IDENTITY functions*/
INSERT TZ VALUES ('Rosalie')
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
GO
SELECT @@IDENTITY AS [@@IDENTITY]
GO
Setting wallpaper programmatically
private const int SPI_SETDESKWALLPAPER = 0X14;
private const int SPIF_UPDATEINIFILE = 0X1;
private const int SPIF_SENDWININICHANGE = 0X2;
[DllImport("USER32.DLL",EntryPoint="SystemParametersInfo", SetLastError = true)]
private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
private const string WallpaperFile = "Saibaba.bmp";
//Place this picture in MyPictures folder.
internal void SetWallpaper(Image img)
{
string imageLocation;
imageLocation = System.IO.Path.GetFullPath (System.Environment.SpecialFolder.MyPictures.ToString() + WallpaperFile);
try
{
img.Save(imageLocation, System.Drawing.Imaging.ImageFormat.Bmp);
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imageLocation, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
catch (Exception Ex)
{
MessageBox.Show("There was an error setting the wallpaper: " + Ex.Message);
}
}
private const int SPIF_UPDATEINIFILE = 0X1;
private const int SPIF_SENDWININICHANGE = 0X2;
[DllImport("USER32.DLL",EntryPoint="SystemParametersInfo", SetLastError = true)]
private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
private const string WallpaperFile = "Saibaba.bmp";
//Place this picture in MyPictures folder.
internal void SetWallpaper(Image img)
{
string imageLocation;
imageLocation = System.IO.Path.GetFullPath (System.Environment.SpecialFolder.MyPictures.ToString() + WallpaperFile);
try
{
img.Save(imageLocation, System.Drawing.Imaging.ImageFormat.Bmp);
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imageLocation, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
catch (Exception Ex)
{
MessageBox.Show("There was an error setting the wallpaper: " + Ex.Message);
}
}
Select Rows in a datagridview
List selectedItems = new List(); //holds your
selected DataRowViews
private void button1_Click(object sender, EventArgs e)
{
CurrencyManager cm =
this.dataGridView1.BindingContext[dataGridView1.DataSource,
dataGridView1.DataMember] as CurrencyManager;
DataView dv = cm.List as DataView;
int i = 0;
foreach (DataRowView drv in dv)
{
if ((selectedItems.IndexOf(drv)) > -1)
{
this.dataGridView1.Rows[i].Selected = true;
}
i++;
}
}
selected DataRowViews
private void button1_Click(object sender, EventArgs e)
{
CurrencyManager cm =
this.dataGridView1.BindingContext[dataGridView1.DataSource,
dataGridView1.DataMember] as CurrencyManager;
DataView dv = cm.List as DataView;
int i = 0;
foreach (DataRowView drv in dv)
{
if ((selectedItems.IndexOf(drv)) > -1)
{
this.dataGridView1.Rows[i].Selected = true;
}
i++;
}
}
Tuesday, March 13, 2007
Update Connection String after Deployment
Code in VB.NET:
To update the ConnectionString in "App.Config" file after deploying a windows application and code to restore database.
Imports System.Configuration
Imports System.Configuration.Install
Imports System.ComponentModel
Imports System.XML
Imports System.Data.SqlClient
Public Class UpdateConnectionString
Inherits Installer
Public Sub New()
End Sub
Public Overrides Sub install(ByVal stateSaver As System.Collections.IDictionary)
MyBase.Install(stateSaver)
Try
Dim ServerName As String = Context.Parameters("PathValue")
'This comes from Set up page (Custom Actions)
Dim ConnectionString As String
If ServerName <> "" Then
Dim AuthenticationMode, UID, PWD As String
AuthenticationMode = Context.Parameters("AuthVal")
If AuthenticationMode = "2" Then
UID = Context.Parameters("UID")
PWD = Context.Parameters("PWD")
End If
Dim AssemblyPath As String = Context.Parameters("assemblypath")
Dim appConfigPath As String = AssemblyPath + ".config"
Dim doc As XmlDocument = New XmlDocument
doc.Load(appConfigPath)
Dim configuration As XmlNode = Nothing
For Each Node As XmlNode In doc.ChildNodes
If Node.Name = "configuration" Then
configuration = Node
Exit For
End If
Next
If Not configuration Is Nothing Then
Dim settingNode As XmlNode = Nothing
For Each ASNode As XmlNode In configuration.ChildNodes
If ASNode.Name = "appSettings" Then
settingNode = ASNode
Exit For
End If
Next
If Not settingNode Is Nothing Then
Dim NumNode As XmlNode = Nothing
For Each NNode As XmlNode In settingNode.ChildNodes
If Not NNode.Attributes("key") Is Nothing Then
If NNode.Attributes("key").Value "ConnectionString" Then
NumNode = NNode
Exit For
End If
End If
Next
If Not NumNode Is Nothing Then
Dim CnAttr As XmlAttribute = NumNode.Attributes("value")
If AuthenticationMode = "2" Then
ConnectionString = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=SCSAdv1;User ID=" + UID + ";pwd=" + PWD
Else
ConnectionString = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=SCSAdv1;Integrated Security=True"
End If
CnAttr.Value = ConnectionString
doc.Save(appConfigPath)
End If
End If
End If
Dim cnToRestore As String
If AuthenticationMode = "2" Then
cnToRestore = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=master;User ID=" + UID + ";pwd=" + PWD
Else
cnToRestore = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"
End If
Dim Sqlcn As New SqlConnection(cnToRestore)
Dim sqlcmd As New SqlCommand()
sqlcmd.CommandType = CommandType.Text
sqlcmd.CommandText = "RESTORE DATABASE [SCSAdv1] FROM DISK = N'" + AssemblyPath.Substring(0, AssemblyPath.IndexOf("SCSAdv1.exe")) + "\SCSAdv1.bak' WITH FILE = 1, MOVE N'SCS_Data' TO N'" + AssemblyPath.Substring(0, AssemblyPath.IndexOf("SCSAdv1.exe")) + "\SCSAdv1.mdf', MOVE N'SCS_Log' TO N'" + AssemblyPath.Substring(0, AssemblyPath.IndexOf("SCSAdv1.exe")) + "\SCSAdv1_log.ldf', NOUNLOAD, STATS = 10"
sqlcmd.Connection = Sqlcn
Try
Sqlcn.Open()
Catch sqlex As SqlException
MsgBox("We are unable to locate the SQL Server instance you have specified." + vbCrLf + "Inorder to run the 'Simulator' you need to manually restore the database after the completion of setup.", MsgBoxStyle.Critical, "")
End Try
sqlcmd.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "")
End Try
End Sub
Public Overrides Sub Uninstall(
ByVal stateSaver As System.Collections.IDictionary)
MyBase.Uninstall(stateSaver)
End Sub
End Class
To update the ConnectionString in "App.Config" file after deploying a windows application and code to restore database.
Imports System.Configuration
Imports System.Configuration.Install
Imports System.ComponentModel
Imports System.XML
Imports System.Data.SqlClient
Inherits Installer
Public Sub New()
End Sub
Public Overrides Sub install(ByVal stateSaver As System.Collections.IDictionary)
MyBase.Install(stateSaver)
Try
Dim ServerName As String = Context.Parameters("PathValue")
'This comes from Set up page (Custom Actions)
Dim ConnectionString As String
If ServerName <> "" Then
Dim AuthenticationMode, UID, PWD As String
AuthenticationMode = Context.Parameters("AuthVal")
If AuthenticationMode = "2" Then
UID = Context.Parameters("UID")
PWD = Context.Parameters("PWD")
End If
Dim AssemblyPath As String = Context.Parameters("assemblypath")
Dim appConfigPath As String = AssemblyPath + ".config"
Dim doc As XmlDocument = New XmlDocument
doc.Load(appConfigPath)
Dim configuration As XmlNode = Nothing
For Each Node As XmlNode In doc.ChildNodes
If Node.Name = "configuration" Then
configuration = Node
Exit For
End If
Next
If Not configuration Is Nothing Then
Dim settingNode As XmlNode = Nothing
For Each ASNode As XmlNode In configuration.ChildNodes
If ASNode.Name = "appSettings" Then
settingNode = ASNode
Exit For
End If
Next
If Not settingNode Is Nothing Then
Dim NumNode As XmlNode = Nothing
For Each NNode As XmlNode In settingNode.ChildNodes
If Not NNode.Attributes("key") Is Nothing Then
If NNode.Attributes("key").Value "ConnectionString" Then
NumNode = NNode
Exit For
End If
End If
Next
If Not NumNode Is Nothing Then
Dim CnAttr As XmlAttribute = NumNode.Attributes("value")
If AuthenticationMode = "2" Then
ConnectionString = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=SCSAdv1;User ID=" + UID + ";pwd=" + PWD
Else
ConnectionString = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=SCSAdv1;Integrated Security=True"
End If
CnAttr.Value = ConnectionString
doc.Save(appConfigPath)
End If
End If
End If
Dim cnToRestore As String
If AuthenticationMode = "2" Then
cnToRestore = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=master;User ID=" + UID + ";pwd=" + PWD
Else
cnToRestore = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"
End If
Dim Sqlcn As New SqlConnection(cnToRestore)
Dim sqlcmd As New SqlCommand()
sqlcmd.CommandType = CommandType.Text
sqlcmd.CommandText = "RESTORE DATABASE [SCSAdv1] FROM DISK = N'" + AssemblyPath.Substring(0, AssemblyPath.IndexOf("SCSAdv1.exe")) + "\SCSAdv1.bak' WITH FILE = 1, MOVE N'SCS_Data' TO N'" + AssemblyPath.Substring(0, AssemblyPath.IndexOf("SCSAdv1.exe")) + "\SCSAdv1.mdf', MOVE N'SCS_Log' TO N'" + AssemblyPath.Substring(0, AssemblyPath.IndexOf("SCSAdv1.exe")) + "\SCSAdv1_log.ldf', NOUNLOAD, STATS = 10"
sqlcmd.Connection = Sqlcn
Try
Sqlcn.Open()
Catch sqlex As SqlException
MsgBox("We are unable to locate the SQL Server instance you have specified." + vbCrLf + "Inorder to run the 'Simulator' you need to manually restore the database after the completion of setup.", MsgBoxStyle.Critical, "")
End Try
sqlcmd.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "")
End Try
End Sub
Public Overrides Sub Uninstall(
ByVal stateSaver As System.Collections.IDictionary)
MyBase.Uninstall(stateSaver)
End Sub
End Class
Thursday, March 8, 2007
Microsoft Tool to uninstall programs
Have you ever wondered how to uninstall a program without using
Control Panel-> Add or Remove Programs.
There is a tool called 'Windows Installer clean up' from Microsoft .
Download the exe from Microsoft web site & uninstall the ones which are not required.
;-)
Enjoy!
Control Panel-> Add or Remove Programs.
There is a tool called 'Windows Installer clean up' from Microsoft .
Download the exe from Microsoft web site & uninstall the ones which are not required.
;-)
Enjoy!
Subscribe to:
Posts (Atom)