Naveen's Weblog

Bridge to future

Posts Tagged ‘Tips and Tricks’

Clone fields and properties in a abstract class

Posted by codingsense on March 15, 2009

Hi Friends,

In this post we shall see how we can clone the properties of a abstract class.

If there is a normal class and we need to clone it, then we will use the simple method of cloning
1) Create a new object
2) Copy all the properties of this object to the newly created object
3) Return the object

But assume a condition when we have a abstract class in which lot of properties are been defined and it has lot of derived classes. Now if we want all the derived classes to implement clone and clone all the properties of the base class then we need to write clone method in each derived classes. Since we know that we cannot create a instance method in abstract class becuase its instance cannot be created.

What would you do in the following case, here is the solution for it, Its simple and a generic method that can be used in any class that needs to implement clone. Here it goes.

Clone Properties:

abstract class CloneProperties: ICloneable    
{
public int fldi = 0;

int propi = 0;
public int Propi
{
get { return propi; }
set { propi = value; }
}

int propj = 0;
public int Propj
{
get { return propj; }
set { propj = value; }
}

        #region ICloneable Members

public object Clone()
{
//we create a new instance of this specific type.            
object newInstance = Activator.CreateInstance(this.GetType());

//We get the array of properties for the new type instance.            
PropertyInfo[] properties = newInstance.GetType().GetProperties();

int i = 0;

foreach (PropertyInfo pi in this.GetType().GetProperties())
{
properties[i].SetValue(newInstance, pi.GetValue(this, null), null);
i++;
}

return newInstance;
}
        #endregion    
}

To check the output we shall create a dummy class and inherit it from cloneProperties class

class Prop : CloneProperties    
{
}

And in the Main function we shall call the clone and check

class Program    
{
static void Main(string[] args)
{
CloneProperties cloneProp1 = new Prop();
cloneProp1.fldi = 1;
cloneProp1.Propi = 2;
cloneProp1.Propj = 3;
CloneProperties cloneProp2 = (CloneProperties)cloneProp1.Clone();

Console.WriteLine("Cloning Properties");
Console.WriteLine("fldi = {0} , Propi = {1}, Propj = {2}", cloneProp2.fldi, cloneProp2.Propi,cloneProp2.Propj);

Console.Read();
}
}

Output:

Output after cloning Properties

Output after cloning Properties


Well it has worked fine, we can see that only the properties are succesfully cloned so they have got the values 2 and 3 and for fields it dint clone and it has value 0.

Clone Fields:

If you need to clone only the fields then you can replace the above clone function with the below one

public object Clone()
{
//we create a new instance of this specific type.            
object newInstance = Activator.CreateInstance(this.GetType());

//We get the array of properties for the new type instance.            
FieldInfo[] fields = newInstance.GetType().GetFields();

int i = 0;

foreach (FieldInfo fi in this.GetType().GetFields())
{
fields[i].SetValue(newInstance, fi.GetValue(this));
i++;
}

return newInstance;
}

Output:
cloneflieds

Here you can see that only fields are cloned and properties are set to the default vaule.

Happy Learning :)

Posted in C# | Tagged: , | Leave a Comment »

Search metadata

Posted by codingsense on December 23, 2008


Many times we may want to see the information of our MSSQL objects. Here are some list of searches i have come across and found useful to share with you all.

  • SYSOBJECTS:

    The below query gives the list of keys associated with a table

    
    select name, xtype from sysobjects where parent_obj = object_id(N'[dbo].TableName')

    You can further filter it out by adding where clause to get only Primary Key( Xtype = ‘PK’) and foreign key (Xtype = ‘F’) and so on

    XType List :
    C: Check constraint
    D: Default constraint
    F: Foreign Key constraint
    L: Log
    P: Stored procedure
    PK: Primary Key constraint
    RF: Replication Filter stored procedure
    S: System table
    TR: Trigger
    U: User table
    UQ: Unique constraint
    V: View
    X: Extended stored procedure

  • INFORMATION_SCHEMA:

    To List the Tables in the database with thier properites use

    
    select * from INFORMATION_SCHEMA.TABLES

    To see the list of stored procedures in the database with thier properites use

    
    SELECT * FROM INFORMATION_SCHEMA.ROUTINES

    Information schema to find foreign keys associated with a table
    More Information_Schema

  • SYSINDEXES:

    Many people use count(*) to get the number of rows in a table, for this operation the MSSQL server recounts the rows thus leading to slower process. The table properties will have its rowcount at any point of time. The best way is to access from sysindexes as follows

    
    select rows from SYSINDEXES WHERE ID = OBJECT_ID('TableName') and indid < 2

Happy Learning :)

Posted in MSSQL | Tagged: , , , | Leave a Comment »

Guidelines, Tips and Tricks MSSQL

Posted by codingsense on December 23, 2008

Here are some of the Tips and Tricks to imporve the performance of MSSQL.

  • Minimize the use of nulls.Because they incur more complexity in queries and updates. ISNULL and COALESCE functions are helpful in dealing with NULL values.
  • Use TRUNCATE TABLE statement instead of DELETE clause if you want to delete all rows from a table
  • Do not use reserved words for naming database objects, as that can lead to some unpredictable situations
  • Avoid using the new bigint data type unless you really need its additional storage capacity. The bigint data type uses 8 bytes of memory verses 4 bytes for the int data type
  • Don’t use “sp_“ as your prefix for stored procedures – it is a reserved prefix in MS SQL server!
  • The Union All statement is much faster than Union, because Union All statement does not look for duplicate rows, and Union statement does look for duplicate rows, whether or not they exist.
  • Always put the Declare statements at the starting of the code in the stored procedure. This will make the query optimizer to reuse query plans.
  • Do not call functions repeatedly in stored procedures, triggers, functions and batches, instead call the function once and store the result in a variable, for later use.
  • To avoid trips from application to SQL server, we should retrieve multiple resultset from single Stored procedure instead of using output param.
  • If stored procedure always returns single row result set, then consider returning the result set using OUTPUT parameters instead of SELECT statement, as ADO handles OUTPUT parameters faster than result set returned by SELECT statements.
  • Avoid (*), Try to restrict the queries result set by returning only the particular columns from the table, not all table’s columns.
  • Use SET NOCOUNT ON statement in your stored procedures to reduce network traffic.
  • Call stored procedure using its fully qualified name.The complete name of an object consists of four identifiers: the server name, database name, owner name, and object name. An object name that specifies all four parts is known as a fully qualified name. Using fully qualified names eliminates any confusion about which stored procedure you want to run and can boost performance because SQL Server has a better chance to reuse the stored procedures execution plans if they were executed using fully qualified names.
  • Do not query/manipulate the data directly in your front end application, instead create stored procedures, and let your applications to access stored procedure
  • Except or Not Exist clause can be used in place of Left Join or Not In for better performance.

If any more additional tips or guidelines then please post a comment.

Happy Learning :)

Posted in MSSQL | Tagged: , , , | Leave a Comment »