Monday, October 10, 2011

How to Compare two datatable objects

An easy solution to compare two datatable object with the support of business object classes.

public static DataTable CompareObject(object x, object y)
        {
            //return if input objects are of not same type
            DataTable dtComp = new DataTable();
            DataColumn DtCol1 = new DataColumn("Field_Name");
            DataColumn DtCol2 = new DataColumn("Old_Value");
            DataColumn DtCol3 = new DataColumn("New_Value");
            dtComp.Columns.Add(DtCol1);
            dtComp.Columns.Add(DtCol2);
            dtComp.Columns.Add(DtCol3);
            Type type = x.GetType();
            Type type1 = y.GetType();
            if (!type.Equals(type1))
                return dtComp;
          
            PropertyInfo[] properties = type.GetProperties();
            FieldInfo[] fields = type.GetFields();
            int compareValue = 0;
            try
            {
                foreach (PropertyInfo property in properties)
                {
                    DataRow Drow = dtComp.NewRow();
                    //Logic to Compare a ArrayList Collection
                    if (property.PropertyType == typeof(System.Collections.ArrayList))
                    {
                    }
                    //Logic to Compare a ArrayList Collection
                    if (property.PropertyType.IsArray == true)
                    {                     

                    }
                    else if (property.PropertyType.IsPrimitive == false && property.PropertyType.IsClass == true)
                    {
                        try
                        {
                            int compare = Compare((object)property.GetValue(x, null), (object)property.GetValue(y, null));
                            if (compare != 0)
                            {                               
                                Drow[0] = property.Name;
                                Drow[1] = (object)property.GetValue(x, null).ToString();
                                Drow[2] = (object)property.GetValue(y, null);
                                dtComp.Rows.Add(Drow);
                                continue;
                            }
                        }
                        catch { }
                    }
                    IComparable valx = property.GetValue(x, null) as IComparable;
                    if (valx == null)
                        continue;
                    object valy = property.GetValue(y, null);
                    compareValue = valx.CompareTo(valy);
                    if (compareValue != 0)
                    {
                        Drow[0] = property.Name;
                        Drow[1] = (object)property.GetValue(x, null).ToString();
                        Drow[2] = (object)property.GetValue(y, null);
                        dtComp.Rows.Add(Drow);
                        continue;
                    }
                  
                }
                foreach (FieldInfo field in fields)
                {
                    DataRow Drow = dtComp.NewRow();
                    IComparable valx = field.GetValue(x) as IComparable;
                    if (valx == null)
                        continue;
                    object valy = field.GetValue(y);
                    compareValue = valx.CompareTo(valy);
                    if (compareValue != 0)
                    {
                        Drow[0] = field.Name;
                        Drow[1] = valx.ToString();
                        Drow[2] = valy.ToString();
                        dtComp.Rows.Add(Drow);
                        continue;
                    }
                  
                }
            }
            catch
            {
            }
            return dtComp;
        }



  public static int Compare(object x, object y)
        {
            //return if input objects are of not same type
            Type type = x.GetType();
            Type type1 = y.GetType();
            if (!type.Equals(type1))
                return 1;
          
            PropertyInfo[] properties = type.GetProperties();
            FieldInfo[] fields = type.GetFields();
            int compareValue = 0;
            try
            {
                foreach (PropertyInfo property in properties)
                {
                    //Logic to Compare a ArrayList Collection
                    if (property.PropertyType == typeof(System.Collections.ArrayList))
                    {
                        System.Collections.ArrayList List1 = new System.Collections.ArrayList();
                        System.Collections.ArrayList List2 = new System.Collections.ArrayList();
                        List1 = (System.Collections.ArrayList)property.GetValue(x, null);
                        List2 = (System.Collections.ArrayList)property.GetValue(y, null);
                        for (int count1 = 0; count1 < List1.Count && count1 < List2.Count; count1++)
                        {
                            if (!Object.Equals(List1[count1], List2[count1]))
                            {
                                compareValue = 1;
                                return compareValue;
                            }
                        }
                    }
                    //Logic to Compare a ArrayList Collection
                    if (property.PropertyType.IsArray == true)
                    {
                        object[] Obj1 = (object[])property.GetValue(x, null);
                        object[] Obj2 = (object[])property.GetValue(y, null);
                        for (int count1 = 0; count1 < Obj1.Length && count1 < Obj2.Length; count1++)
                        {
                            if (!Object.Equals(Obj1[count1], Obj2[count1]))
                            {
                                compareValue = 1;
                                return compareValue;
                            }
                        }

                    }
                    else if (property.PropertyType.IsPrimitive == false && property.PropertyType.IsClass == true)
                    {
                        try
                        {
                            int compare = Compare((object)property.GetValue(x, null), (object)property.GetValue(y, null));
                            if (compare != 0)
                            {
                                compareValue = compare;
                                return compare;
                            }
                        }
                        catch { }
                    }
                    IComparable valx = property.GetValue(x, null) as IComparable;
                    if (valx == null)
                        continue;
                    object valy = property.GetValue(y, null);
                    compareValue = valx.CompareTo(valy);
                    if (compareValue != 0)
                        return compareValue;
                }
                foreach (FieldInfo field in fields)
                {
                    IComparable valx = field.GetValue(x) as IComparable;
                    if (valx == null)
                        continue;
                    object valy = field.GetValue(y);
                    compareValue = valx.CompareTo(valy);
                    if (compareValue != 0)
                        return compareValue;
                }
            }
            catch
            {
            }
            return compareValue;
        }

Wednesday, September 7, 2011

DataGridView TextChanged Event Handling

Hi,
Find out the event handling for the datagridview events while changing its text in cells.
We can apply the validations on the text entered in text box cells of datagirdview


 private void dgvAttributes_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            try
            {
                index = 0;
                if (dgvAttributes.CurrentCell.ColumnIndex == 1)
                {
                    index = 1;
                    rowid = dgvAttributes.CurrentCell.RowIndex;
                    // Check box column
                    temp = (DataGridViewComboBoxCell)dgvAttributes.CurrentCell;
                    ComboBox comboBox = e.Control as ComboBox;
                    comboBox.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
                }
                else  if (dgvAttributes.CurrentCell.ColumnIndex == 3)
                {
                    TextBox txt = e.Control  as TextBox;
                    txt.KeyPress += new KeyPressEventHandler(txt_SelectedTextChanged);
                }
               else  if (dgvAttributes.CurrentCell.ColumnIndex == 4)
                {
                    TextBox txt = e.Control as TextBox;
                    txt.KeyPress += new KeyPressEventHandler(txt_SelectedTextChanged);
                }
               else  if (dgvAttributes.CurrentCell.ColumnIndex == 5)
                {
                    TextBox txt = e.Control as TextBox;
                    txt.KeyPress += new KeyPressEventHandler(txt_SelectedTextChanged);
                }

            }
            catch (Exception ex)
            { }
        }
        void txt_SelectedTextChanged(object sender,KeyPressEventArgs e)
        {           
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

Friday, July 1, 2011

Find Stored Procedure Related to Table in Database

Search in All Stored Procedure

Following code will help to find all the Stored Procedures (SP) which are related to one or more specific tables. sp_help and sp_depends does not always return accurate results.
----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'

22 New Features of Visual Studio 2008

1. LINQ Support
LINQ essentially is the composition of many standard query operators that allow you to work with data in a more intuitive way regardless.
LINQ
The benefits of using LINQ are significant – Compile time checking C# language queries, and the ability to debug step by step through queries.
2. Expression Blend Support
Expression blend is XAML generator tool for silverlight applications. You can install Expression blend as an embedded plug-in to Visual Studio 2008. By this you can get extensive web designer and JavaScript tool.
3. Windows Presentation Foundation
WPF provides you an extensive graphic functionality you never seen these before. Visual Studio 2008 contains plenty of WPF Windows Presentation Foundation Library templates. By this a visual developer who is new to .NET, C# and VB.NET can easily develop the 2D and 3D graphic applications.
Visual Studio 2008 provides free game development library kits for games developers. currently this game development kits are available for C++ and also 2D/3D Dark Matter one image and sounds sets.
4. VS 2008 Multi-Targeting Support
Earlier you were not able to working with .NET 1.1 applications directly in visual studio 2005. Now in Visual studio 2008 you are able to create, run, debug the .NET 2.0, .NET 3.0 and .NET 3.5 applications. You can also deploy .NET 2.0 applications in the machines which contains only .NET 2.0 not .NET 3.x.
5. AJAX support for ASP.NET
AJAX
Previously developer has to install AJAX control library separately that does not come from VS, but now if you install Visual Studio 2008, you can built-in AJAX control library. This Ajax Library contains plenty of rich AJAX controls like Menu, TreeView, webparts and also these components support JSON and VS 2008 contains in built ASP.NET AJAX Control Extenders.
6. JavaScript Debugging Support
Since starting of web development all the developers got frustration with solving javascript errors. Debugging the error in javascript is very difficult. Now Visual Studio 2008 makes it is simpler with javascript debugging. You can set break points and run the javaScript step by step and you can watch the local variables when you were debugging the javascript and solution explorer provides javascript document navigation support.
7. Nested Master Page Support
Already Visual Studio 2005 supports nested master pages concept with .NET 2.0, but the problem with this Visual Studio 2005 that pages based on nested masters can't be edited using WYSIWYG web designer. But now in VS 2008 you can even edit the nested master pages.
8. LINQ Intellisense and Javascript Intellisense support for silverlight applications
javascriptintellisense
Most happy part for .NET developers is Visual Studio 2008 contains intellisense support for javascript. Javascript Intellisense makes developers life easy when writing client side validation, AJAX applications and also when writing Silverlight applications
Intellisense Support: When we are writing the LINQ Query VS provides LINQ query syntax as tool tips.
9. Organize Imports or Usings: We have Organize Imports feature already in Eclipse. SInce many days I have been waiting for this feature even in VS. Now VS contains Organize Imports feature which removes unnecessary namespaces which you have imported. You can select all the namespaces and right click on it, then you can get context menu with Organize imports options like "Remove Unused Usings", "Sort Usings", "Remove and Sort". Refactoring support for new .NET 3.x features like Anonymous types, Extension Methods, Lambda Expressions.
10. Intellisense Filtering: Earlier in VS 2005 when we were typing with intellisense box all the items were being displayed. For example If we type the letter 'K' then intellisense takes you to the items starts with 'K' but also all other items will be presented in intellisense box. Now in VS 2008 if you press 'K' only the items starts with 'K' will be filtered and displayed.
11. Intellisense Box display position
javascriptintellisense
Earlier in some cases when you were typing the an object name and pressing . (period) then intellisense was being displayed in the position of the object which you have typed. Here the code which we type will go back to the dropdown, in this case sometimes programmer may disturb to what he was typing. Now in VS 2008 If you hold the Ctrl key while the intellisense is dropping down then intellisense box will become semi-transparent mode.
12. Visual Studio 2008 Split View
spit
VS 205 has a feature show both design and source code in single window. but both the windows tiles horizontally. In VS 2008 we can configure this split view feature to vertically, this allows developers to use maximum screen on laptops and wide-screen monitors.
Here one of the good feature is if you select any HTML or ASP markup text in source window automatically corresponding item will be selected in design window.
13. HTML JavaScript warnings, not as errors: VS 2005 mixes HTML errors and C# and VB.NET errors and shows in one window. Now VS 2008 separates this and shows javascript and HTML errors as warnings. But this is configurable feature.
14. Debugging .NET Framework Library Source Code:
Now in VS 2008 you can debug the source code of .NET Framework Library methods. Lets say If you want to debug the DataBind() method of DataGrid control you can place a debugging point over there and continue with debug the source code of DataBind() method.
15. In built Silverlight Library
silverlight
Earlier we used to install silverlight SDK separately, Now in VS 2008 it is inbuilt, with this you can create, debug and deploy the silverlight applications.
16. Visual Studio LINQ Designer
LINQ
Already you know in VS 2005 we have inbuilt SQL Server IDE feature. by this you no need to use any other tools like SQL Server Query Analyzer and SQL Server Enterprise Manger. You have directly database explorer by this you can create connections to your database and you can view the tables and stored procedures in VS IDE itself. But now in VS 2008 it has View Designer window capability with LINQ-to-SQL.
17. Inbuilt C++ SDK
Earlier It was so difficult to download and configure the C++ SDK Libraries and tools for developing windows based applications. Now it is inbuilt with VS 2008 and configurable
18. Multilingual User Interface Architecture - MUI
MUI
MUI is an architecture contains packages from Microsoft Windows and Microsoft Office libraries. This supports the user to change the text language display as he wish.
Visual Studio is now in English, Spanish, French, German, Italian, Chinese Simplified, Chinese Traditional, Japanese, and Korean. Over the next couple of months. Microsoft is reengineering the MUI which supports nine local languages then you can even view Visual studio in other 9 local languages.
19. Microsoft Popfly Support
popfly
Microsoft Popfly explorer is an add-on to VS 2008, by this directly you can deploy or hosting the Silverlight applications and Marshup objects
20. Free Tools and Resources
People may feel that I am a promoter to Visual Studio 2008 as a salesman, but we get plenty of free resources and free tools with Visual Studio 2008.
  • Visual Studio 2008 Trial

  • 101 LINQ Samples

  • Free .NET 3.5 control libraries with free sample programs,

  • You can get plenty of free video training tutorials from Microsoft BDLC - Beginner Developer Learning Center,

  • C++ games development library,

  • Microsoft has provided lot of e-Books,

  • P2P library and

  • Microsoft is providing Coding4Fun sample program kit.

  • Visual Studio Registration Discounts: If you register the Visual Studio you get Free Control Libraries, Books, Images, and Discounts.

  • Download Visual Studio 2008 free trial 21. We can use for Commercial
    Earlier you were spending lot of money to host your .NET applications for commercial use. Now you no need to worry Now Microsoft is providing you to host your application free on Popfly for web pages and also visual studio express projects.
    If you like this article, Please share with others

  • Monday, June 13, 2011

    Code Access Security in .NET 2.0


    Introduction
    Code access security is a concept of .NET Framework that restricts the execution privileges of the code on the resources and its operations. Usually administrators configure security policy of the code. This is done by sets of permissions with groups of code called as Code Groups. In the next section we will look into the code groups in detail. Using Code Access Security, the code can request for permissions to execute. Once a code has requested for permission, the permissions are granted to it based on its assembly permissions security policy. We will also be covering the types of policies in the next section.
    Security Stack Walk and Security Demands
    Each assembly has a set of corresponding grants. If an assembly needs to execute a method that uses other assemblies, it requests the .NET runtime for permission to execute. This process is called Security Stack Walk. According to MSDN, Security stack walk is the process of examining the permissions of each caller in the stack and determining whether the permission being demanded has been granted to each caller. If a caller that does not have the demanded permission is found, the security check fails and a SecurityException is thrown.
    Permissions
    In the previous sections we understood that before the code executes it can ask the runtime for the permission to execute. The permission for an assembly is given by placing attributes. Placing attributes and asking permissions is known as declarative syntax. (It should be noted that it is not mandatory for the code to ask for the permission.)
    Let us understand this with the help of an example. If we have an application that reads and writes to the local hard disk then the application must have FileIOPermission. If the code does not request FileIOPermission and the local security settings do not allow your application to have this permission, a security exception is raised when the application attempts to write to the disk. There are 2 things that need to be understood here.
    ·         The local system security does not allow the application to do anything on the disk.
    ·         The Application does not request for the FileIOPermission.
    On a different scenario, if the application requests FileIOPermission and the local security settings does not permit the application to have FileIOPermission, the application will generate the exception. But in this case, we can programmer can ensure that user will not loose any data.
    Different Types of permissions
    We have different types of permission sets. Let us see some of them in detail.
    1.    Minimum permissions (RequestMinimum) - Permissions for the code have to run.
    2.    Optional permissions (RequestOptional) - Permissions for the code that can be bypassed to run without them.
    3.    Refused permissions (RequestRefuse) - Permissions that you want to ensure will never be granted to your code, even if security policy allows them to be granted.
    Listing 1 shown below is the code written in C# that explains the request for permission from an assembly using attributes.
    Listing 1
    [assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")] 

    Code Groups
    As per MSDN, the definition of Code Group is "a logical grouping of code that has a specified condition for membership." A code group has some permission sets associated with it. Based on these permission sets, the security policy will be configured by the administrators. A named permission set consists of at least one permission set and a name and description for the permission set. Administrators can use named permission sets to establish or modify the security policy for code groups. Please find the built-in named permission sets provided by the common language runtime.
    ·         Nothing - no permissions (code cannot run)
    ·         Execution - permission to run (execute), but no permissions to use protected resources
    ·         Internet - the default policy permission set suitable for content from unknown origin
    ·         LocalIntranet - the default policy permission set within an enterprise
    ·         Everything - all standard (built-in) permissions, except permission to skip verification
    ·         FullTrust - full access to all resources
    Let us see how a code group forms in configuration file and then discuss each element in detail. Listing 2 forms a code group. The code group is of the type NetCodeGroup. This is from the assembly “mscorlib.” The NetCodeGroup class provides the Web permission to the site from which the assembly is downloaded. It forms the union of PolicyStatement objects and grants permission based on the same. A PolicyStatement consists of a set of granted permissions and possible special attributes for the code group. There are three types of schemes available for NetCodeGroup: Http, Https and File. The IMembershipCondition defines the test to determine whether a code assembly is a member of a code group. The IMembershipCondition has a method Check which does the same. AllMembershipCondition is the class which represents the membership condition that matches all the code.
    Listing 2
    <CodeGroup
     class="System.Security.Policy.NetCodeGroup, mscorlib, Version=2.0.0.0,
     Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1"
    Name="Internet_Same_Site_Access"
    Description="All Internet code gets the right to connect back to the site of its origin.">
    <IMembershipCondition
     class="System.Security.Policy.AllMembershipCondition, mscorlib,
     Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1"/>
    <connectAccessRules>
    <codeOrigin scheme="file"/>
    <codeOrigin scheme="http">
    <connectAccess scheme="http"
    port="$origin"/>
    The figure below shows different types of code groups that inherit from the abstract class code group.
    Figure 1

    Policy Levels
    A policy level consists of a set of code groups organized into a single rooted tree, a set of named permission sets that are referenced by the code groups to specify permissions to be granted to code belonging to the code group and a list of fully-trusted assemblies.
    1.    Enterprise: security policy for all managed code in an enterprise. This is the topmost hierarchy for applying policy level settings.
    2.    Machine: security policies for all managed code run on the computer
    3.    User: Security policy for all managed code run by the user. For the current user the security settings get applied.
    4.    Application domain: security policy for all managed code in an application
    The figure below shows the configuration wizard for the .NET Framework 2.0. The policy level Enterprise security policy has Code Groups, Permission Sets and Policy Assemblies within it.
    Figure 2
    Configuring the Code Access security
    We have been discussing a Permission Sets, Code group and Policy Level. Now, we will try to understand how an Administrator configures the code access security using .NET Framework configuration wizard. Figure 3 shows editing the Permission set to full trust. We have other options, such as Skip Verification, Execution, Local intranet, Internet and Nothing.
    Figure 3
    The figure given below shows the modification of Membership condition to all code. We have all the options listed with their meanings.
    ·         All Code –  all assemblies meet this condition
    ·         Application Directory – all assemblies in the directory or a child directory of running app
    ·         Hash – all assemblies with a hash that matches the given hash
    ·         Publisher – all assemblies digitally signed with a specified certificate
    ·         Site – all assemblies downloaded from a specified site
    ·         Strong Name – all assemblies with a specified strong name and public key
    ·         URL – all assemblies downloaded from a specified URL
    ·         Zone – all assemblies that originate from one of five specified zones listed below
    ·         My Computer – Internet, Local Intranet, Trusted Sites and Untrusted Sites
    Figure 4
    Conclusion
    Code access security is a concept of .NET Framework that restricts the execution privileges of the code on the resources and its operations. The permission for an assembly is given by placing attributes. Placing attributes and asking permissions is known as declarative syntax.