Feeds:
Posts
Comments

In one of our project modules I am currently working on there is a requirement to backup and restore the databases as and when required. They are doing it programmatically from the application side. Everything went well with the backup. But when they are restoring we need to validate whether the .BAK file that they are passing is a valid one or not. How to validate this? In SQL Server we have an option while restoring the database RESTORE VERIFY ONLY. It will not restore the backup but it will check whether the backup is complete and readable. I used the following script to do the same.

declare @verifystatement nvarchar(250)

declare @backupdevice nvarchar(250)

declare @err int

set @backupdevice =‘C:\Temp\TestDB.bak’ –Select the .bak file path here

set @verifystatement =‘RESTORE VERIFYONLY FROM DISK = ”’+ @backupdevice + ””

exec sp_executesql @verifystatement

SELECT @err = @@error

if @err <> 0

 begin

   PRINT ‘Database backup is corrupt’

 end

else

begin

  PRINT ‘Database backup is valid’

End

From the application side they can put this in a function and call this to identify whether the database backup file is corrupt or not. Based on the result from this function they can take whether to backup or throw an exception.

For more details please refer to http://msdn.microsoft.com/en-us/library/aa238412(SQL.80).aspx

Here I find a good link that contains a list of good ASP.NET interview questions. These are ideal for people whi want brush up their topics in the free time and who are planning to switch jobs.

One of the new features of SQL Server 2008 is the MERGE statement. Basically MERGE will insert data  to a target table from a source if the data is not there other wise it will update/delete from the target table. Using the MERGE statement will actually improves the performance a lot.

1. To further illustrate I have created a table called Mobiles as follows.

 

   CREATE TABLE Mobiles (
   ProductID   INT PRIMARY KEY,

   ManufacturerName     NVARCHAR(200), 

    Price             INT

)

 

2. I inserted the following sample data into the table 

 

INSERT
INTO Mobiles VALUES (1,‘Nokia’,10000),

                    (2,‘Samsung’,2000),

                    (3,‘Motorola’,3000)    

3. Next I created a table type which will be used as a table valued input parameter for the stored procedures that I create.

 

CREATE TYPE MobileType AS  TABLE

(

    MobileID         INT PRIMARY KEY,

    MobileName     NVARCHAR(200),

    MobilePrice     INT

)

 GO

4. Next I created a stored procedure which will insert/update the details of the Mobiles. This procedure accepts the MobileType table valued parameter that I created in the previous step as input.

CREATE
PROCEDURE UpdateMobileDetails

@Mobiles MobileType READONLY

AS

 UPDATE M
SET
M.ManufacturerName=LM.MobileName,
M.Price=LM.MobilePrice
FROM Mobiles M
INNER
JOIN @Mobiles LM
ON M.ProductID=LM.MobileID
 

INSERT
INTO Mobiles
(
    ProductID,
    ManufacturerName,
    Price
)

SELECT

   LM.MobileID,

    LM.MobileName,
    LM.MobilePrice
FROM Mobiles M
LEFT OUTER JOIN @Mobiles LM
    ON M.ProductID=LM.MobileID
WHERE M.ProductID IS NULL    

This procedure will update the records if they are already existing in the table otherwise it will insert them

5. You can achieve the same functionality using the MERGE statement of the SQL Server 2008.

CREATE
PROCEDURE UpdateMobileDetails_Merge

@Mobiles MobileType READONLY

AS

 MERGE Mobiles M
USING @Mobiles LM ON M.ProductID = LM.MobileId
WHEN MATCHED THEN
UPDATE
SET
M.ManufacturerName=LM.MobileName,
M.Price=LM.MobilePrice    
 WHEN NOT MATCHED THEN
INSERT

(

    ProductID,

    ManufacturerName,

    Price

)

VALUES(

    LM.MobileID,

    LM.MobileName,

    LM.MobilePrice    );    

If the record matches it updates, if it is not matched it will insert into the table.

6. Next I opened two separate query windows to test these two procedures and analyze the performances. I created the following test scripts in these two windows.

–To test the normal procedure

    –Test script

DECLARE @ltblMobiles MobileType

INSERT
INTO @ltblMobiles VALUES (1,‘Nokia N Series’,20000),

                        (4,‘Sony Ericssion’,5000)                                

EXEC UpdateMobileDetails    

@Mobiles=@ltblMobiles    

 

SELECT
*
FROM Mobiles

 

To test the MERGE procedure

DECLARE @ltblMobiles MobileType

INSERT
INTO @ltblMobiles VALUES (6,‘BENQ’,12000),

                        (7,‘iPhone’,5000)

                                

EXEC UpdateMobileDetails_Merge    

@Mobiles=@ltblMobiles    

 

SELECT
*
FROM Mobiles

7. Now go to the Object Explorer. Right Click the database where you have created the table in Step 1.

Right Click database->Reports->Standard Reports ->Object Execution Statistics.

Object Execution statics window will open in a new tab. In that you can see the one which uses MERGE has less Logical I/O.

 


 

 

 

In this article I will demonstrate how we can ultilise the new feature called table valued parameters in SQL Server 2008. These are great addition to the SQL sever 2008 that allows us to pass multiple rows of data to the stored procedure. In earlier versions we acheived this functionality by  converting the data into XML or calling the stored procedure mulitple times or by many different means. Lets see how this new feature works in SQL server 2008.

 

tvp

Basically what we have done here is as follows:

1.Created a table called Mobiles

2.Created a new type called MobileTable

3. Created a new stored procedure which accepts a parameter of type MobileTable and inserts records into the Mobiles table.

4.Executed the stored procedure

This  new feature will be a great benefit for the SQL server developers and client side developers working on ASP.NET or any other client interface where they can send the whole bunch of tables as parameters to the stored procedures without converting them into XML or any other client side modifications.  I hope this article helps you…

I recently came across an article written by Thomas L. Friedman, a Newyork Times Editor and the author of books like “The World is Flat“ , “The Lexus and the Olive Tree” and “From Beirut to Jerusalem“.

You can read the article here. This article tells about the authors experiences while travelling to a small country called CostaRice. It fulfils it 95% of its energy requirements from renewable energy sources.It discovered its oil reserves five years ago and still it banned drilling citing pollution to the environment. Can anyone think of a country which discovered its own natural treasure and forbid it because it may cause damage to the environment?  It started the process of investing in renewable energy sources like Hydro-electric power, Geo-Thermal power and wind energy in the 1990s and now it enjoys the benefits of having a long term vision for the sustainable development of the country. Can you imagine the same thing happening in India? Do our policy makers think on those lines? Food for thought…..

The new version of SQL server Code named “Kilimanjaro” is going to release in FY2010. Before that microsoft wants to give a brief introduction of the same. So they have created this webcast. You can download the webcast by registering here. This session will provide you with an sneak preview into the next release of SQL Server codenamed ‘Kilimanjaro’ as well as project ‘Madison’.

On a high level the new features that are coming with this release are as follows

  • Self Service Analysis (Project “Gemini”) and Reporting
  • BI sharing,Colloboration and Resource Management
  • Application and multi server management

Project “Gemini” has 4 components in it

  • Excel  Reporting tool
  • In memory BI engine
  • Sharepoint  Integration
  • Analysis service as the backend

Also SQL server wants to have a major release for every 24-36 months from the release of SQL server 2008. That means we can expect this “Kilimanjaro” major release to be in the near future(Aug 10).

So keep your fingers crossed and be prepared for the steep learning curve.

When you write any .NET application it will always add some of the assemblies by default. How will this happen? When I think about the probable answer I thought it might be GAC. But when I googled it I found the answer is completely different. The answer is a response file.

 What is a response file (.rsp) file:  A response file is a text file that tells the compiler what are the command line switches to be added. When you execute CSC.exe, the compiler opens response files and uses any switches that are specified in them as though the switches were passed to CSC.exe on the command line.

When you install the .NET Framework, it installs a default global CSC.rsp file in the %System-Root%\Microsoft.NET\Framework\vX.X.X directory (where X.X.X is the version of the .NETFramework you have installed). The 2.0 version of this file contains the following switches: 

# This file contains command-line options that the c#

# command line compiler (CSC) will process as part

# of every compilation, unless the “/noconfig” option

# is specified.

# Reference the common Framework libraries

/r:Accessibility.dll

/r:Microsoft.Vsa.dll

/r:System.Configuration.dll

/r:System.Configuration.Install.dll

/r:System.Data.dll

/r:System.Data.OracleClient.dll

/r:System.Data.SqlXml.dll

/r:System.Deployment.dll

/r:System.Design.dll

/r:System.DirectoryServices.dll

/r:System.dll

/r:System.Drawing.Design.dll

/r:System.Drawing.dll

/r:System.EnterpriseServices.dll

/r:System.Management.dll

/r:System.Messaging.dll

/r:System.Runtime.Remoting.dll

/r:System.Runtime.Serialization.Formatters.Soap.dll

/r:System.Security.dll

/r:System.ServiceProcess.dll

/r:System.Transactions.dll

/r:System.Web.dll

/r:System.Web.Mobile.dll

/r:System.Web.RegularExpressions.dll

/r:System.Web.Services.dll

/r:System.Windows.Forms.Dll

/r:System.Xml.dll

You can add more dlls to the above file if you want. But it is not advisable as it requires to update the same file in each build machine of your respective build environment.

I hope this article helps you….

Today in  my current project we are supposed to build an image from  Binary data stored in a SQL Server column. AS we know SQL Server allows us to store BLOB (Binary Large Objects) data. Here in our case the situation is as below.

 In Source System data (read as Images,Videos or documents(.xls,.ppt,.pptx,.xlsx,.doc,.docx) )is stored in a column defined as VARBINARY(MAX). To the destination System which is on a seperate SQL Server instace , the source data is passed on a daily basis. The destination system is connected to a .NET application which is used as a front end. Our task is to reconstruct the same file through this binary data using this .NET application. We have used the following code snippet to achieve this functionality.

 Byte[] bytImage=null

string 

constring = @”Specify your data source here;”  
SqlCommand command = new SqlCommand(@”Get the column where the binary data is stored in the table”);
command.CommandType =CommandType.Text; 

SqlConnection myconn = new SqlConnection(constring);

command.Connection = myconn;

myconn.Open();

 SqlDataReader dr = command.ExecuteReader(); 

 while (dr.Read()){
//To save a bit map file 

 

bytImage = (byte[])dr["BlobData" ];
} 
 
FileStream fs = new FileStream(“C:\\Temp\\Test1.doc”, FileMode.OpenOrCreate, FileAccess.Write);  
BinaryWriter br = new BinaryWriter(fs);
br.Write(bytImage);
fs.Dispose();
} 
If the content type is an image file we can write the code as follows.

MemoryStream ms = new MemoryStream(bytImage);

System.Drawing.Bitmap BMP = new System.Drawing.Bitmap(ms);

BMP.Save(“C:\\Temp\\Test.bmp”);

//To save a file in JPEG format

System.Drawing.Image img = new System.Drawing.Bitmap(ms);

img.Save(“C:\\Temp\\Test1.jpeg”, ImageFormat.Jpeg);

I hope this article will help you to retrieve the binarydata from SQL server and create the corresponding documents from the same.

As we were discussing concurrency options in my previous articles here , we noted that updating the database with SubmitChanges could update a single record or any number of records (even across multiple tables). If we run into conflicts, we can decide how to handle the conflict. However, we didn’t point out previously that if some effort is not made to roll back changes, any records that were successfully saved prior to the exception will be committed to the database. This could leave the database in an invalid state if some records are saved and others are not.

LINQ to SQL offers three main mechanisms to manage transactions. In the first option, used by default, the DataContext will create and put that in a transaction when SubmitChanges is called. This will roll back changes automatically depending on the selected ConflictMode option. If we wish to manually maintain the transaction, the DataContext also offers the ability to use the transaction on the connection already maintained by the DataContext. In this case, we call BeginTransaction on DataContext.Connection before we try to submit the changes. After we submit the changes, we can either commit them or roll them back. The below code demonstrates this.

7

 The downside of managing the transactions directly through the DataContext is that it cannot span multiple connections or multiple DataContext objects. As a third option, the System.Transactions.TransactionScope object that was introduced with the .NET 2.0 Framework was specifically designed to seamlessly span connections. To use it, add a reference to the System. Transactions library. This object will automatically scale the transaction based on the objects that it covers. If the scope only covers a single database call, it will use a simple database transaction. If it spans multiple classes with multiple connections, it will automatically scale up to an enterprise transaction. Additionally, the TransactionScope doesn’t require us to explicitly begin the transaction or roll it back. The only thing you need to do is complete it as shown below. 8

 Unlike the other transaction mechanisms, we don’t need to wrap the code in a try catch block solely to roll the transaction back. With the TransactionScope, the transaction will automatically get rolled back unless we call the Complete method. If an exception is thrown in SubmitChanges, the exception will bypass the Complete method. We don’t need to explicitly roll the transaction back. It still needs to be wrapped in an exception-handling block, but the exception handling can be done closer to the user interface.The true advantage of the TransactionScope object is that it automatically scales based on the given context. It works equally well with local transactions an with heterogeneous sources. Because of the flexibility and scalability, using the TransactionScope object is the preferred method of handling transactions with LINQ to SQL.

In my earlier articles I showed how we can handle the concurrency using UpdateCheck. In this articles I will show how to deal with Concurrency Exceptions.

In using the Always or WhenChanged options for UpdateCheck, it is inevitable that two users will modify the same values and cause conflicts. In those cases, the DataContext will raise a ChangeConflictException when the second user issues   an SubmitChanges request. Because of the likelihood of running into an exception, we need to make sure we wrap the updates inside a structured exception handling block.

Once an exception is thrown, several options to resolve the exception exist. The DataContext helps discover not only the objects that are in conflict, but also which properties are different between the original value, the changed value, and the current value in the database. In order to provide this level of information, we can specify the “RefreshMode” to determine whether the conflicting record is first refreshed from the database to determine the current values. Once we have the refreshed values, we can determine whether we want to retain the original values, the current database values, or our new values. If we want to take the last option and make sure our values are the ones that are retained, we resolve the change conflicts of the context object specifying that we want to keep the changes as shown in the code below.

5

 If we use the RefreshMode.KeepChanges option, we don’t need to inspect the changed values. We are assuming that our values are correct and go ahead and force them into the appropriate row. This can be potentially dangerous. Columns that we didn’t update will be refreshed from the current value in the database. If the business needs demand it, we could merge the changes with the new values from the database; simply set the RefreshMode as  RefreshMode.KeepCurrentValues. This way, we’ll incorporate the other user’s changes into our record and add our changes. However, if both users changed the same column, the new value will overwrite the value that the first user updated. To be safe, we can overwrite the values that the second user tried to change with the current values from the database. In that case, use  RefreshMode.OverwriteCurrentValues  At this point, it would not be beneficial to submit the changes back to the database again, as there would be no difference between the current object and the values in the database. We would present the refreshed record to the user and have them make the appropriate changes again.Depending on the number of changes that the user made, they may not appreciate having to reenter their data. Since SubmitChanges can update multiple records in a batch, the number of changes could be significant. To assist with this, the SubmitChanges method takes an overloaded value to indicate how we wish to proceed when a record is in conflict. We can either stop evaluating further records or collect a listing of objects that were conflicted.  

The ConflictMode enumeration specifies the two options: FailOnFirstConflict and ContinueOnConflict. 

With the ContinueOnConflict option, we’ll need to iterate over the conflicting options and resolve them using the appropriate RefreshMode. With this method, we can at least submit some of the values and then prompt the user to reenter his information in the conflicting items. This could still cause some user resentment, as he would need to review all of the changes to see what records need to be changed.A better solution would be to present the user with the records and fields that were changed. LINQ to SQL not only allows access to this information, but also supports the ability to view the current value, original value, and database value for the conflicting object. The below code demonstrates using the ChangeConflicts collection of the DataContext to collect the details of each conflict. 6

Each item in the ChangeConflicts collection contains the object that conflicted as well as a MemberConflicts collection. This collection contains information about the Member, CurrentValue, DatabaseValue, and OriginalValue. Once we have this information, we can display it to the user in whatever method we choose. Using this code, we can display details of the concurrency errors that the user creates.In designing systems that allow for multiple concurrent users, we need to consider how to handle concurrency concerns.  By catching the exception, we can either handle it using one of the resolution modes or roll the entire transaction back.

Older Posts »