Friday, July 11, 2014

How to open Visual studio 2012 solution in Visual studio 2010?

As we know that if we have lower version solution  then we can open it in upper version but in case of reverse it doesn't allow us to open. In this case we get incompatibility problem. We can make it position by doing some changes in solution file, config file and project file.

In this article, I will explain - How to open Visual studio 2012 solution in Visual studio 2010?

To make it position, Just follow the below steps-

Step 1 -

Open your solution file (.sln) and replace "Format Version 12.00" with "Format Version 11.00"

Step 2 -

Open App.config and replace sku=".NETFramework,Version=v4.5" with sku=".NETFramework,Version=v4.0"

Step 3 -

Open your project file and replace

<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> with
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>

Finally save all the changes and close the files. Now just try to open your solution in Visual studio 2010. It will be opened.

Thanks

Thursday, March 6, 2014

How to know SQL Server Version using backup file?

Backup and restore these are common tasks while working with the database. But before restoring the database it is necessary that we should know about some information about backup file because it may be possible that we have created backup file in upper version of SQL Server and we are trying to restore it in lower version of SQL Server. In this is case database can not be restored.

So before facing this problem it is better to know about backup file means in which version it was created.

To get this information we can simply use RESTORE command with HEADERONLY. Check the bellow command -


RESTORE HEADERONLY 
         FROM DISK = N'd:\filename.bak' 

By passing the path of backup file you can run this command, you will get result like this-


SqlServerBackupFileInforation1


SqlServerBackupFileInforation2


SqlServerBackupFileInforation3


SqlServerBackupFileInforation4


SqlServerBackupFileInforation5


SqlServerBackupFileInforation6

  SqlServerBackupFileInforation7


SqlServerBackupFileInforation8


By seeing SoftwareVersionMajor and SoftwareVersionMinor you can identify the version of the software.

To know about each column help follow this link-

http://technet.microsoft.com/en-us/library/ms178536.aspx

Here you will get description for each column.


Wednesday, March 5, 2014

How to avoid ContextSwitchDeadlock exception?

In some of the cases we face the problem regarding ContextSwitchDeadlock. Actually there are some causes for this exception.

You can check these causes by following this link-

http://msdn.microsoft.com/en-us/library/ms172233%28v=vs.110%29.aspx

In this article, I am explaining - "How can we avoid ContextSwitchDeadlock exception?"

To void the this exception, we need to set some setting in Visual Studio IDE, Check the below steps-

1. Click on "Debug" Menu.
2. After that Click on "Exceptions".
3. It will open one Exception window. Here expand the node- "Manage Debugging Assistants".
4. Here you will find "ContextSwitchDeadlock" CheckBox, just uncheck it.

Follow-

Debug-> Exceptions-> Manage Debugging Assistants -> ContextSwitchDeadlock

Check the below screen shot-


ContextSwitchDeadlock


Just uncheck it and again run the application, This exception will be skipped while run-time.


Friday, February 28, 2014

How to Compare the Objects in .Net (Real story of Equals() method)

Comparing objects is really a big story because we don’t have any direct method to compare the object (Except reference comparison).  If we want to compare the object reference then we can use Object .Equals () but it is not useful when we want to compare the object properties.

Equals () method compares the references not the properties or values of the object. So it will not any help when we have requirement to compare the object properties or values.

Let me take the small example for this. Check the below code-

private void btnEquals_Click(object sender, EventArgs e)
        {
            try
            {
                ClsEmployee objEmp1 = new ClsEmployee();
                ClsEmployee objEmp2 = new ClsEmployee();
                ClsEmployee objEmp3 = new ClsEmployee();

                //Assigning value to objEmp1
                objEmp1.intEmpId = 1;
                objEmp1.intEmpName = "Jitendra";

                //Assigning value to objEmp2
                objEmp2.intEmpId = 1;
                objEmp2.intEmpName = "Jitendra";

                //Assigning objEmp3 with objEmp1 (Reference)
                objEmp3 = objEmp1;

                //Comparing objEmp1 and objEmp2
                if (objEmp1.Equals(objEmp2))
                {
                    MessageBox.Show("Object objEmp1 and objEmp2 are same");
                }
                else
                {
                    MessageBox.Show("Object objEmp1 and objEmp2 are not same");
                }

                //Comparing objEmp1 and objEmp3
                if (objEmp1.Equals(objEmp3))
                {
                    MessageBox.Show("Object objEmp1 and objEmp3 are same");
                }
                else
                {
                    MessageBox.Show("Object objEmp1 and objEmp3 not are not same");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

In above code, I have assigned the same value to objEmp1 and objEmp2 but
objEmp1.Equals(objEmp2) will return False because objEmp1 and objEmp2 represents different references.

objEmp1.Equals(objEmp3) will return True because before comparing the object I have assigned objEmp3 = objEmp1, so here both will represent the same reference.

So here is the question- What if we want to compare the object properties?

Solution-

Here we have solution for this- We can make use of Reflection. Using reflection we can compare thee the properties of object with the help of PropertyInfo class. This class provides the information about the property.

You can find the difference based on following points-

1.    If the type of objects are not same
2.    If number of properties in objects are not same
3.    If any property is missing in second object
4.    If value of properties are not same
5.    If any object is null

For this add the below namespace-

using System.Reflection;

Check the below example-

    //Employee Class
    public class ClsEmployee
    {
        public Int32 intEmpId { get; set; }
        public string intEmpName { get; set; }
        public ClsDept objClsDept { get; set; }
    }

    //Dept Class
    public class ClsDept
    {
        public Int32 intDeptId { get; set; }
        public string intDeptName { get; set; }
    }

//Code to compare object using PropertyInfo Class
        private void btnCompareProInfo_Click(object sender, EventArgs e)
        {
            try
            {
                ClsEmployee objEmp1 = new ClsEmployee();
                ClsEmployee objEmp2 = new ClsEmployee();
                ClsEmployee objEmp3 = new ClsEmployee();

                //Assigning value to objEmp1
                objEmp1.intEmpId = 1;
                objEmp1.intEmpName = "Jitendra";
                objEmp1.objClsDept = new ClsDept();
                objEmp1.objClsDept.intDeptId = 1;
                objEmp1.objClsDept.intDeptName = "AC";
              
                //Assigning value to objEmp2
                objEmp2.intEmpId = 1;
                objEmp2.intEmpName = "Jitendra";
                objEmp2.objClsDept = new ClsDept();
                objEmp2.objClsDept.intDeptId = 1;
                objEmp2.objClsDept.intDeptName = "AC";

                //Assigning value to objEmp3
                objEmp3.intEmpId = 1;
                objEmp3.intEmpName = "Jitendra";
              
                //Comparing objEmp1 and objEmp2
                if (CompareObjects(objEmp1, objEmp2))
                {
                    MessageBox.Show("Object objEmp1 and objEmp2 are same");
                }
                else
                {
                    MessageBox.Show("Object objEmp1 and objEmp2 are not same");
                }

                //Comparing objEmp1 and objEmp3
                if (CompareObjects(objEmp1, objEmp3))
                {
                    MessageBox.Show("Object objEmp1 and objEmp3 are same");
                }
                else
                {
                    MessageBox.Show("Object objEmp1 and objEmp3 are not same");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //Method to compare Object
        private Boolean CompareObjects(object obj1, object obj2)
        {
            Boolean isEqual = true;
            try
            {
                //If any object is null then returning  false
                if (obj1 == null || obj2 == null)
                {
                    return false;
                }
                //If object types are different then returning false
                if (obj1.GetType() != obj2.GetType())
                {
                    return false;
                }

                //Getting list of properties
                PropertyInfo[] obj1PInfo = obj1.GetType().GetProperties();
                PropertyInfo[] obj2PInfo = obj2.GetType().GetProperties();

                //If number of properties are not same then return false
                if (obj1PInfo.Count() != obj2PInfo.Count())
                {
                    return false;
                }

                //Looping each child property
                for (int index = 0; index < obj1PInfo.Count(); index++)
                {
                    //Getting child property
                    PropertyInfo objChild1PInfo = obj1PInfo[index];
                    Object propValue1 = objChild1PInfo.GetValue(obj1, null);

                    Object propValue2 = null;

                    //Checking same property is not present in second object then return false
                    if (obj2PInfo.Contains(objChild1PInfo) == false)
                    {
                        return false;
                    }
                    else
                    {
                        PropertyInfo objChild2PInfo = obj2PInfo[index];
                        propValue2 = objChild2PInfo.GetValue(obj2, null);
                    }

                    //If object contains any child property (as class type) then compare child properties also
                    if (Enum.IsDefined(typeof(System.TypeCode), objChild1PInfo.PropertyType.Name) == false)
                    {
                        isEqual = CompareObjects(propValue1, propValue2);
                    }
                    else
                    {
                        if (Convert.ToString(propValue1) != Convert.ToString(propValue2))
                        {
                            return false;
                        }
                    }
                }
                return isEqual;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

In above code, I have written one method (CompareObjects()) to compare the object s.
Boolean CompareObjects(object obj1, object obj2)-  In this method I have used PropertyInfo class get the information about each property in objects. This method will compare the object based on points as I have given above.

So the result of (CompareObjects(objEmp1, objEmp2)) will be True because both object have same values And result of (CompareObjects(objEmp1, objEmp3)) will be False because both object have different values.

Note- This code will also work if you have any child  classes.

Monday, February 24, 2014

How to generate alphabet sequence A, B, C, ....., Z, AAA, AAB,....., ZZZ in C#

In some of the cases we use alphabet for sequence. If we have options less then 27 then   we can direct use A-Z alphabet but if the options are more then we have to generate sequence.

Check the below logic to generate the alphabet sequence like -     A, B, C, ....., Z, AAA, AAB,....., ZZZ  

 private void btnGenerate_Click(object sender, EventArgs e)
        {
            List<string> lstSquence = new List<string>();
           
            int i = 0;
            //Generating 1000 alphabet sequence
            while (i < 1000)
            {
                lstSquence.Add(GenerateSequence(i));
                i++;
            }
        }


        //Method to generate alphabet sequence
        static string GenerateSequence(int index)
        {
            string result = string.Empty;
            while (index > 0)
            {
                index = index - 1;
                result = char.ConvertFromUtf32(65+ index % 26) + result;
                index = index / 26;
            }
            return result;
        }

       

This logic will generate the alphabet sequence like -     A, B, C, ....., Z, AAA, AAB,....., ZZZ

Monday, February 3, 2014

How to disable or enable all the validation of the page?

To disable or enable the validation of the page we can simply use this JQuery code-

Check this below code-

        //Function to Enable/ Disable all validation
        function EnableValidation(boolFlag) {
            //Turn on/off all validation
            $.each(Page_Validators, function (index, validator) {
                ValidatorEnable(validator, boolFlag);
            });
        }

Now you can call this function. Just pass boolean value to enable or disable the validations.

To disable the validations-

EnableValidation(false);

To enable the validations-
       
EnableValidation(true);

Thursday, January 30, 2014

Considerations for SQL Server Replication



There are some points to consider while implementing replication. These points include some technical and environment requirements for the replication, means in this article, I will explain about configuration setting for SQL Server replication. 

Check the below points, here you will get clear idea about configuration for replication-

1.  Select the proper version of SQL Server

As we know that there are different versions of SQL Server present in the market, so it must that first we have to select proper SQL Server version for replication.

Below table will make you understand to select proper version of SQL Server for Replication.

Reference from- SQL Server Versions

SQL Server Versions



By seeing above table, we can easily identify suitable version of SQL Server for our requirement.

2. Name of the Server (Use actual name of server)

While implementing replication, we should use name of the server (Actual Name of the Server) not IP address, If the user logins to server using IP (without actual SQL Server Name) then the replication wizard for creating publication will not work and it will generate error like this-

 SQL Server Name


So, we should use Server Name not IP Address of server.

3.  Start SQL Server Agent Service

This service should be started before going for replication, to start this we can get list of services using the Control Panel and then we can start.

Follow this -  Control Panel\All Control Panel Items\Administrative Tools\Services

 SQL Server Agent Service

By default, the SQL Server Agent service is disabled when SQL Server is installed unless you explicitly choose to auto start the service during installation.

4.  Enable the TCP IP Ports of SQL Server Instance

TCP IP Ports of SQL Server should be enabled because data transfer is done using TCP Protocol.
To enable this just open the SQL Server Configuration manager and Check for SQL Server Network Configuration, Here we will find Protocols for SQL Server Instance.   Just right click on TCP/IP protocol and enable it.

5. Enable the Named Pipes of SQL Server Instance

As we have enabled the TCP IP Ports, the same way we have to enable Named pipes using the SQL Server Configuration manager.
You can see below image, Here TCP/IP port and Names Pipes are enabled.


 SQL Server Configuration


6. Turn off the Firewall settings

In replication web synchronization requires additional ports to be opened on the firewall because of that firewall should be turned off.

7. Sufficient Disk Space

It may be possible that numbers of Subscribers are more, so in this case we should be more careful about disk space because after synchronization all the database will be sync and this require more space. Synchronization generates high values of data so it is must that we should have sufficient disk space to save the data.

8.  High Bandwidth

It is must that Bandwidth should be good because In case of large amount of data, it uses large amount of bandwidth. Database synchronization will be fast in case of high bandwidth.

9. Proper Database design

It is must that database should be designed properly to reduce possibility of conflict. It may be possible, conflict may occur but if our database design is proper then conflict can be resolved very easily.

We can consider these points while designing database structure-

(i) For Update Conflict-   Each record should have one column to track update time of the record so that while resolving the conflict, we can decide that which record should be reflected (Publisher or Subscriber record). By this way update conflict can be solved very easily.

(ii) For Insert Conflict- Each record should have primary key, it should not repeat at other subscriber also because after synchronization all records will be in same place. By this way insert conflict will not occur.

Like this, we can reduce possibility of conflict.

10. Selection of replication type


It is must that we should well-known about types of replication before implementing replication because we have to select the proper type of replication based on our environment.

These are the considerations, when we go for replication. By following these points implementation of replication can be done easily.

How to change connection string for EDMX in runtime?



In some cases, we need to change the connection string of edmx model in run time; we can change it from code behind code.

In this article, I am explaining - How to change connection string for EDMX in runtime?

Check the below code-

  protected void btnGetData_Click(object sender, EventArgs e)
        {
            try
            {
                TestDBEntities context = new TestDBEntities(GetConnectionString("DBName"));
                var result1 = from data in context.tab_Employees
                                       select data;
                gvEmpDetails.DataSource = result1.ToList();
                gvEmpDetails.DataBind();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

//Method to get connection string
        private string GetConnectionString(string strDBName)
        {
            SqlConnectionStringBuilder sqlBuilder;
            EntityConnectionStringBuilder entityBuilder;
            try
            {
                sqlBuilder = new SqlConnectionStringBuilder();
                sqlBuilder.DataSource = @"server name";
                sqlBuilder.InitialCatalog = strDBName;
                sqlBuilder.IntegratedSecurity = true;
                sqlBuilder.MultipleActiveResultSets = true;

                entityBuilder = new EntityConnectionStringBuilder();
                entityBuilder.Provider = "System.Data.SqlClient";
                entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
                entityBuilder.Metadata = @"res://*/ModelName.csdl|res://*/ModelName.ssdl|res://*/ModelName.msl";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return entityBuilder.ToString();
        }


In above code, while creating connection string, you need to pass details for connection string. Like-
Database name, Server name etc.

Here ModelName= Name of the model which you have created while generating edmx.

How to avoid or lock enter key in form?


Use this simple code to avoid enter key on form-


  <script type="text/javascript">
        $(document).keypress(
                    function (event) {
                        if (event.which == '13') {
                            event.preventDefault();
                            }
                                    }
                            );
 </script>

Wednesday, January 8, 2014

How to insert bulk record into database using SQL Server,C# and XML

If we have list of records then we can not process each record to insert into database because it is time taking process and it will degrade the performance.In this case we can use bulk insert. Suppose if we have bulk record in xml then we can easily dump that xml record into database.

Check the below code sample to insert bulk record.

Suppose this is sample XML string -

XML Data String

<?xml version='1.0' encoding='utf-8'?>
<Employees>
  <Emp>
    <EmpID>101</EmpID>
    <EmpName>Jitendra</EmpName>
    <Age>27</Age>
  </Emp>
  <Emp>
    <EmpID>102</EmpID>
    <EmpName>Ramesh</EmpName>
    <Age>30</Age>
  </Emp>
  <Emp>
    <EmpID>103</EmpID>
    <EmpName>Raj</EmpName>
    <Age>24</Age>
  </Emp>
 </Employees>
 

 
Now check the below stored procedure –

Stored Procedure

This stored proceduer will take the XML string as input and it will process this XML to insert into table.

--Stored procedure to insert bulk record using XML

CREATE PROCEDURE [dbo].[SP_EmpBulkInsert]   
(    @XMLData text    )   
AS   
BEGIN   
 SET NOCOUNT ON   
 BEGIN TRANSACTION   
 Begin Try   

  DECLARE @XMLDocPointer INT   
  EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT, @XMLData   

   INSERT INTO tab_Employees
   (EmpID, EmpName, Age)   
   SELECT EmpID,EmpName,Age  
   FROM OPENXML(@XMLDocPointer,'/Employees/Emp',2)   
   WITH  (EmpID INT,EmpName nvarchar(50),Age INT)    

   EXEC sp_xml_removedocument @XMLDocPointer   
   COMMIT TRANSACTION   
   Return 0;    
 End Try   
 Begin Catch   
   ROLLBACK TRANSACTION   
 End Catch   
END


In this stored procedure I am inserting data into tab_Employees table, based on column selection data will be inserted to this table. Now chek the below code to call this stored procedure from C# application.

C# Code-

//Code to insert bulk records
        private void btnBulkInsert_Click(object sender, EventArgs e)
        {
            try
            {
                //Code to insert bulk record using XML
                string strConnectionString = "Your connection string";
                //Getting XML string
                string strXML = GetXMLString();
               
                //Connecting to database
                using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection())
                {
                    conn.ConnectionString = Convert.ToString(strConnectionString);
                    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SP_EmpBulkInsert", conn);
                    cmd.Parameters.AddWithValue("@XMLData", strXML);
                    cmd.CommandType = CommandType.StoredProcedure;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    MessageBox.Show("Records inserted successfully.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

         //XML string to insert bulk record
        private string GetXMLString()
        {
            return  @"<?xml version='1.0' encoding='utf-8'?>
<Employees>
  <Emp>
    <EmpID>101</EmpID>
    <EmpName>Jitendra</EmpName>
    <Age>27</Age>
  </Emp>
  <Emp>
    <EmpID>102</EmpID>
    <EmpName>Ramesh</EmpName>
    <Age>30</Age>
  </Emp>
  <Emp>
    <EmpID>103</EmpID>
    <EmpName>Raj</EmpName>
    <Age>24</Age>
  </Emp>
 </Employees>";
        }


In above code, I am getting XML string using GetXMLString() method. After getting the XML string I am passing this string as parameter for stored procedure. Finally when this code will be executed then you will find the new records in tab_Employees table.