Hello All, We are going to start new batch from next week. message/call or mail us for more details.

28 August 2012

Understanding Structures in C#


A structure in C# is simply a composite data type consisting of a number elements of other types. A C# structure is a value type and the instances or objects of a structure are created in stack. The structure in C# can contain fields, methods, constants, constructors, properties, indexers, operators and even other structure types. 
Structure Declaration & Object Creation
The keyword struct can be used to declare a structure. The general form of a structure declaration in C# is as follows.         

<modifiers> struct <struct_name>
{
//Structure members}

Where the modifier can be private, public, internal or public. The struct is the required keyword.

For example  

struct
 MyStruct
{
public int
 x;public int y;
}

The objects of a strcut can be created by using the new operator as follows.    

MyStruct ms = new MyStruct(); The individual members of a struct can be accessed by using the dot (.) operator as showing below.

ms.x = 10;
ms.y = 20;

Remember that unlike classes, the strcut object can also be created without using the new operator.    

MyStruct ms;

But in this case all fields of the struct will remain unassigned and the object can't be used until all of the fields are initialized. 

Structs & Fields 
A struct in C# can contain fields. These fields can be declared as private, public, internal. Remember that inside a struct, we can only declare a field. We can't initialize a field inside a struct. However we can use constructor to initialize the structure fields. 
The following is not a valid C# struct and the code will not compile, since the fields inside the structure are trying to initialize.           

struct MyStruct
{
int x = 20; 
// Error its not possible to initializeint y = 20; // Error its not possible to initialize}

A valid C# structure is showing below. 

// Author: rajeshvs@msn.comusing System;struct MyStruct
{
public int
 x;public int y;
}
class
 MyClient
{
public static void
 Main()
{
MyStruct ms = 
new
 MyStruct();
ms.x = 10;
ms.y = 20;
int
 sum = ms.x + ms.y;
Console.WriteLine("The sum is {0}",sum);
}
}

However a struct can contain static fields, which can be initialized inside the struct. The following example shows the use of static fields inside a struct. 

// Author: rajeshvs@msn.com using System;struct MyStruct
{
public static int
 x = 25;public static int y = 50;
}
class
 MyClient
{
public static void
 Main()
{
int
 sum = MyStruct.x + MyStruct.y;
Console.WriteLine("The sum is {0}",sum);
}
 
Remember that static fields can't be accessed by an instance of a struct. We can access them only by using the struct names. 

Struct & Methods 
A C# struct can also contain methods. The methods can be either static or non-static. But static methods can access only other static members and they can't invoke by using an object of the structure. They can invoke only by using the struct name.
An example is shown below. 

// Author: rajeshvs@msn.com using System;struct MyStruct
{
static int
 x = 25;static int y = 50;public void SetXY(int i, int j)
{
x = i;
y = j;
public static void
 ShowSum()
{
int
 sum = x + y;
Console.WriteLine("The sum is {0}",sum);
}
}
class
 MyClient
{
public static void
 Main()
{
MyStruct ms = 
new
 MyStruct();
ms.SetXY(100,200);
MyStruct.ShowSum();
}
}
  
The methods inside a struct can also be overloaded as like inside a class. For example 

// Author:rajeshvs@msn.com  using System;struct MyStruct
{
static int
 x = 25;static int y = 50;public void SetXY(int i, int j)
{
x = i;
y = j;
public void SetXY(int
 i)
{
x = i;
y = i;

}
class
 MyClient
{
public static void
 Main()
{
MyStruct ms1 = 
new
 MyStruct();
MyStruct ms2 = 
new
 MyStruct();
ms1.SetXY(100,200);
ms2.SetXY(500);
}
}
Structs & Constructors
A C# struct can declare constrcutor, but they must take parameters. A default constructor (constructor without any parameters) are always provided to initialize the struct fields to their default values. The parameterized constructors inside a struct can also be overloaded.          

// Author: rajeshvs@msn.com using System;struct MyStruct
{
int
 x ;int y ; 
{ x = i; y = j;}
public MyStruct(int
 i)
{ x = y = i; }
public void
 ShowXY()
{ Console.WriteLine("The field values are {0} & {1}",x,y); }
}
class
 MyClient
{
public static void
 Main()
{
MyStruct ms1 = 
new
 MyStruct(10,20);
MyStruct ms2 = 
new
 MyStruct(30);
ms1.ShowXY();
ms2.ShowXY();
}
}
 
The 'this' operator can also be used in constructors and parameterized constructors can be chained inside a C# constructor. An example is given below. 

// Author: rajeshvs@msn.comusing System;struct MyStruct
{
int
 x ;int y ;public MyStruct(int i, int j):this(i+j){ }public MyStruct(int i)
{ x = y = i; }
public void
 ShowXY()
{ Console.WriteLine("The field values are {0} & {1}",x,y); }
}
class
 MyClient
{
public static void
 Main()
{
MyStruct ms1 = 
new
 MyStruct(10,20);
ms1.ShowXY();
}
}
Finally remember that C# struct do not support destructors. 

Structs & Properties 
The properties can be declared inside a struct as shown below.         

//C#: Property
// Author: rajeshvs@msn.com
using  System;class MyStructprivate int x; public int X 
get
 
return
 x; 
set
 

x = 
value


}
}
class
 MyClientpublic static void Main() 

MyStruct ms = 
new
 MyStruct(); 
ms.X = 10; 
int
 xVal = ms.X; 
Console.WriteLine(xVal);
//Displays 10 }
}
Structs & Indexers 

The indexers can also be used with a C# struct. An example is shown below.         

// Author: rajeshvs@msn.com using System;using System.Collections;struct MyStruct
{
public string
 []data ;public string this [int index]
{
get{return data[index];
}
set{
data[index] = 
value
;
}
}
}
class
 MyClient
{
public static void
 Main()
{
MyStruct ms = 
new
 MyStruct();
ms.data = 
new string
[5];
ms[0] = "Rajesh";
ms[1] = "A3-126";
ms[2] = "Snehadara";
ms[3] = "Irla";
ms[4] = "Mumbai";
Console.WriteLine("{0},{1},{2},{3},{4}",ms[0],ms[1],ms[2],ms[3],ms[4]);
}
}
Structs & Operator Overloading 

The operators can be overloaded inside a C# structure also. The same rules applicable with respect to a C# class is also applicable here. Both unary and binary operators can be overloaded.         

// Author: rajeshvs@msn.com 
using
 System;struct Complex
{
private int
 x;private int y;public Complex(int i, int j)
{
x = i;
y = j;
}
public void
 ShowXY()
{
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator
 -(Complex c)
{
Complex temp = 
new
 Complex();
temp.x = -c.x;
temp.y = -c.y;
return
 temp;
}
}
class
 MyClient
{
public static void
 Main()
{
Complex c1 = 
new
 Complex(10,20);
c1.ShowXY(); 
// displays 10 & 20Complex c2 = new Complex();
c2.ShowXY(); 
// displays 0 & 0c2 = -c1;
c2.ShowXY(); 
// diapls -10 & -20}
}
Structs & Inheritance 

There is no inheritance for structs as there is for classes. A struct can't inherit from another struct or class and it can't be the base class for a class. But remember that in C# all types are directly or indirectly inheriting from the super base class object and hence the structure also. Since structs doesn't support inheritance, we can't use the keywords virtual, override, new, abstract etc with a struct methods. C# struct types are never abstract and are always implicitly sealed. The abstract or sealed modifiers are not permitted in a struct declaration. 
Since inheritance is not supported for structs, the declared accessibility of a struct member can't be protected or protected internal. Since all struct types are implicitly inherit from object class, it is possible to override the methods of the object class inside a struct by using the keyword override. Remember that this is special case in C# structs. 
Structs & Interfaces 
Just like classes, a C# struct can also implement from an interface. For example         

// Author:rajeshvs@msn.com  using System;interface IInterface
{
void
 Method();
}
struct
 Complex : IInterface
{
public void
 Method()
{
Console.WriteLine("Struct Method");

class
 MyClient
{
public static void
 Main()
{
Complex c1 = 
new
 Complex();
c1.Method();
}
}
Structs & Classes 

The structs in C# seems to similar to classes. But they are two entirely different aspects of the language. The classes are reference types while a struct is a value type in C#. The objects of class types are always created on heal while the objects of struct types are always created on the stack. But C# structs are useful for small data structures that have value semantics. Complex numbers, points in a co-ordinate systems etc are good examples for struct types.

19 August 2012

Backing Up a SQL Server Database Directly Onto a Remote Server


Recently I encountered a situation where the backup drive was short of space on the production server. The policy on the production server was that as soon as soon as the Full Backup is complete, a copy of the production backup is transferred to the staging server using RoboCopy and then on the staging server there is a job scheduled which transfers the backup to tape.
I needed to increase the size of my backup drive but this could take several weeks to procure and order the drive. Thus, I needed a method to backup the database while the new drive was being procured. I then decided to try and verify whether my Production DB Backups could be directly taken to my staging servers using T-SQL.
I am taking backups of the database hosted on my Production server (which is named A.A.A.A) directly onto the staging server named P.Q.R.S. My Production and Staging servers are located in different locations but are both in the same domain.

Approach

I decided to write a Dynamic SQL Query to implement the backup. The table named sysdatabases in the master database contains all the information related to the databases hosted on the server.I decided to write a Cursor to implement the required looping. The full code is available for download here, the explanation of the code is as follows:
DECLARE DATABASE_BACKUP Cursor
FOR
The DECLARE CURSOR statement defines the SELECT statement that forms the basis of the cursor. Using this you can perform almost anything you would do in a SELECT statement.
select [name] from master.sysdatabases
where [name] not in(
'tempdb',
'distribution'
)
I decided to backup all the databases on the server excluding tempdb and distribution. As you most likely know, tempdb is never backed up and in our environment the distribution database is not required to be backed up since we were using Transactional Replication for Reporting, and if there are any issues we would have to directly set up the Replication again.
Once have the names of the databases which need to be backed up, the next step is to define a cursor to do the looping:
Open DATABASE_BACKUP
The OPEN statement statement executes the SELECT statement and populates the result set.
DECLARE @Name varchar(100)
Fetch NEXT FROM DATABASE_BACKUP INTO @Name
The FETCH statement returns a row from the result set into the variable. You can select multiple columns and return them into multiple variables.
While (@@FETCH_STATUS <> -1)
The variable @@FETCH_STATUS is used to determine if there are any more rows. It will be 0 as long as there are more rows. We use a WHILE loop to move through each row of the result set.
WHILE(@@FETCH_STATUS<>-1) will ensure that the conditional looping proceeds until we reach the last row of the SELECT statement.
BEGIN
DECLARE @month varchar(2)
DECLARE @date varchar(2)
DECLARE @year varchar(4)
DECLARE @SQL varchar(max)
SELECT @month = DATEPART(MM,GETDATE())
SELECT @date = DATEPART(DD,GETDATE())
SELECT @year = DATEPART(YYYY,GETDATE())
SELECT @SQL ='BACKUP DATABASE '+CONVERT(VARCHAR(100),@Name)+'
To DISK='+''''+'\\P.Q.R.S\DBBACKUPS\'+CONVERT(VARCHAR(100),@Name)+''+CONVERT(VARCHAR(1),'_')+CONVERT(VARCHAR(2),@month)+CONVERT(VARCHAR(1),'_')+
CONVERT(VARCHAR(2),@date)+CONVERT(VARCHAR(1),'_')+CONVERT(VARCHAR(4),@YEAR)+'.BAK'''
EXEC(@SQL)
The variable @SQL contains the Dynamic SQL Query which contains the backup statement. EXEC(@SQL) tells the SQL Server to execute the backup statement individually for each database. Please note that DBBackups is the name of the folder which is present on the staging server P.Q.R.S to hold the DB Backup.Please do not forget to share this folder and give full rights to the Domain Account on this folder.

The below statement tells the SQL Server that once the backup of first database is complete proceed with the second and so on. This procedure continues until we have reached the last database present in the sysdatabases table in the master database.
FETCH NEXT FROM DATABASE_BACKUP INTO @Name
END
The next statement tells the SQL Server to release the row set.
CLOSE DATABASE_BACKUP
The below statement releases the resources asociated with the cursor.
DEALLOCATE DATABASE_BACKUP

Find Stored Procedure Related to Table in Database


SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'

18 August 2012

Recovering a SQL Server Database from Suspect Mode


A couple of days back at I got a call from my support team informing me that one of our database located on the Production Server went into Suspect Mode. The version used was SQL Server 2005 Service Pack 3. Being a Production Database server, it was a Priority 1 incident and the expected time of resolution was 4 hours..
Solution:
The first step was to identify why this incident occured and after investigation it was found that it was due to the corruption of the transactional log file of the database.
I connected to SSMS using the sa login credentials and located the SUSPECT database:
I then reset the status of the SUSPECT Database by executing the below T-SQL query against the master database.
EXEC sp_resetstatus 'test_dr';
sp_resetstatus turns off the suspect flag on a database. This procedure updates the mode and status columns of the named database in sys.databases. Also note that only logins having sysadmin priveleges can perform this :
As you can see in the above screen capture, the T-SQL query gave the warning message upon execution:
You must recover this database prior to access
The next step was to set the SUSPECT database into an EMERGENCY mode. This was done by executing the below SQL query against the master database.
ALTER DATABASE test_dr SET EMERGENCY
Once the database is set to EMERGENCY mode it becomes a READ_ONLY copy and only members ofsysadmin fixed server roles have privileges to access it. The basic purpose for this is to facilitate troubleshooting. I did not want other users updating the database while it was being worked on.
As you can see from the above screen capture, once the T-SQL query got executed successfully the state of the database changed from SUSPECT to EMERGENCY.
Once the database state was changed to EMERGENCY. I then performrf a consistency check by executing the below T-SQL query against the master database.
DBCC checkdb('test_dr')
Which resulted in the below output:
As seen from the above screen capture there is no issue with respect to consistency of the test_dr database. Also, this confirmed that the logical and physical integrity of the database was intact.
The next step was to set the database to SINGLE USER mode with ROLLBACK IMMEDIATE. To do this the below SQL query was executed against the master database.
ALTER DATABASE
test_dr SET SINGLE_USER
WITH ROLLBACK IMMEDIATE
The above query will rollback any transactions if any are present in the test_dr database and will bring the database named test_dr into Single User mode.
Please refer to the screen capture below:



The next step was to perform a DBCC Checkdb along with Repair with Data Loss by executing the below T-SQL query against the master database.
DBCC CheckDB ('test_dr', REPAIR_ALLOW_DATA_LOSS)
This query will attempt to repair all reported errors. These repairs can cause some data loss.
Once the DBCC CheckDB with the Repair with Data Loss option were executed, the Database went into Single User mode as shown below:
After performing the above step the database was brought ONLINE and Multiple Users access was enabled by executing the below T-SQL query against the master database.
ALTER DATABASE test_dr SET MULTI_USER
Please refer the screen capture below.
As you can see from the above screen capture the database named test_dr is back ONLINE. I am even able to view its objects as shown below:
As final step for safety, I again checked the consistency of the database which was just repaired and brought ONLINE (i.e. the test_dr database) by executing the below T-SQL query against the master database.
 DBCC CheckDB ('test_dr')
After performing the above steps I ensured that all the required logins had access to the database with proper privileges. The application started working fine and the business was back on track. It took just 38 minutes to bring the SUSPECT database back ONLINE.
Please let me know if you have any comments on this approach or alternative approaches you have used in the past.

Find out who modified an object in SQL Server


SELECT I.*
FROM
sys.traces T
CROSS Apply ::fn_trace_gettable(T.path, T.max_files) I
Join sys.trace_events E On I.eventclass = E.trace_event_id
Where T.id = 1 And
E.name = 'Object:Altered' and ObjectName like '%UAC_AdminAccess%'