Sumedh Meshram

.Net Technical Blog

TECHGIG : Code Contest HomeThe Great Indian Programming League 2013 - May Edition - Visit a Colony

Problem Statement :

In a colony all houses are in a single line. We call a house either in a good condition or in a bad condition. If a house is good its score is 1 otherwise 0. We decided to perform the scoring of houses in a different way. 

We not only consider that particular house but also the 2 neighboring house.
 
New scoring strategy- The Score of a house if affected by three house, that house and its two neighbors
 
Score-1 : If any of the three houses is in good condition 
Score-2 : if any of the two houses is in good condition 
Score-3 : if all the three houses are in good condition 
 
Now Josheph has the score list of all the houses ( according to new strategy ) and he wants to know what is the condition ( good or bad) of his house just seeing the score of the houses. He assumes that first house is in good condition.

MyResult

Successfully compiledSuccessfully compiled
: 9: 90
 
Solution :
using System;
public class CandidateCode
{
public static int house_condition(int[] input1,int input2)
{
int[] score = new int[input1.Length];	
for(int i=0;i<input1.Length;i++)
{
if(i == 0)
{
score[i] = 1; //first house in good condition

if(i+1<input1.Length)
{
score[i+1] = input1[i]- score[i];	
}
}
else
{
if(i+1<input1.Length)
{	
score[i+1] = input1[i] - (score[i-1] + score[i]);
}
}
}
return score[input2-1];	
}
}

The Partition Problem - Algorithm [Solved]

Partition Problem Problem

Partition problem is the task of deciding whether a given multiset of positive integers can be partitioned into two subsets S1 and S2 such that the sum of the elements in S1 equals the sum of the elements in S2.

using System;
using System.Linq;
public class CandidateCode
{
	public static string partition(int[] input1)
	{
		
		bool[] best_assignment = PartitionValues(input1);
		
		string result1 = "", result2 = "";
            	int total1 = 0, total2 = 0;
            	for (int i = 0; i < best_assignment.Length; i++)
            	{
	        	 if (best_assignment[i])
			 {
	    		   result1 += "\r\n " + input1[i];
	    		   total1 += input1[i];
			 }
			else
		         {
	         	   result2 += "\r\n " + input1[i];
	               	   total2 += input1[i];
		         }
		}
            if (result1.Length > 0) result1 = result1.Substring(2);
            if (result2.Length > 0) result2 = result2.Substring(2);

		return "{"+ result1 + " } {" + result2 + " } total  " + total1.ToString() + " & " + total2.ToString();
	}
	
	private static bool[] PartitionValues(int[] values)
	{
		bool[] best_assignment = new bool[values.Length];
            	bool[] test_assignment = new bool[values.Length];
            	
               	int total_value = values.Sum();

            	int best_err = total_value;
            	PartitionValuesFromIndex(values, 0, total_value, test_assignment, 0, ref best_assignment, ref best_err);
            
            	return best_assignment;
	}
	
private static void PartitionValuesFromIndex(int[] values, int start_index, int total_value,
            bool[] test_assignment, int test_value,
            ref bool[] best_assignment, ref int best_err)
        {
            // If start_index is beyond the end of the array,
            // then all entries have been assigned.
            if (start_index >= values.Length)
            {
                // We're done. See if this assignment is better than what we have so far.
                int test_err = Math.Abs(2 * test_value - total_value);
                if (test_err < best_err)
                {
                    // This is an improvement. Save it.
                    best_err = test_err;
                    best_assignment = (bool[])test_assignment.Clone();
                }
            }
            else
            {
                // Try adding values[start_index] to set 1.
                test_assignment[start_index] = true;
                PartitionValuesFromIndex(values, start_index + 1, total_value,
                    test_assignment, test_value + values[start_index],
                    ref best_assignment, ref best_err);

                // Try adding values[start_index] to set 2.
                test_assignment[start_index] = false;
                PartitionValuesFromIndex(values, start_index + 1, total_value,
                    test_assignment, test_value,
                    ref best_assignment, ref best_err);
            }
        }
}

Implementing Singleton in C#

Implementing Singleton in C#

Context

You are building an application in C#. You need a class that has only one instance, and you need to provide a global point of access to the instance. You want to be sure that your solution is efficient and that it takes advantage of the Microsoft .NET common language runtime features. You may also want to make sure that your solution is thread safe.

Implementation Strategy

Even though Singleton is a comparatively simple pattern, there are various tradeoffs and options, depending upon the implementation. The following is a series of implementation strategies with a discussion of their strengths and weaknesses.

Singleton

The following implementation of the Singleton design pattern follows the solution presented in Design Patterns: Elements of Reusable Object-Oriented Software [Gamma95] but modifies it to take advantage of language features available in C#, such as properties:

 

using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}
 

This implementation has two main advantages:

  • Because the instance is created inside the Instance property method, the class can exercise additional functionality (for example, instantiating a subclass), even though it may introduce unwelcome dependencies.

  • The instantiation is not performed until an object asks for an instance; this approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.

 

The main disadvantage of this implementation, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created:

if (instance == null)

Various approaches solve this problem. One approach is to use an idiom referred to as Double-Check Locking [Lea99]. However, C# in combination with the common language runtime provides a static initialization approach, which circumvents these issues without requiring the developer to explicitly code for thread safety.

Static Initialization

 

 

One of the reasons Design Patterns [Gamma95] avoided static initialization is because the C++ specification left some ambiguity around the initialization order of static variables. Fortunately, the .NET Framework resolves this ambiguity through its handling of variable initialization:

 

public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
   
   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }
}
 

In this strategy, the instance is created the first time any member of the class is referenced. The common language runtime takes care of the variable initialization. The class is marked sealed to prevent derivation, which could add instances. For a discussion of the pros and cons of marking a class sealed, see [Sells03]. In addition, the variable is marked readonly, which means that it can be assigned only during static initialization (which is shown here) or in a class constructor.

This implementation is similar to the preceding example, except that it relies on the common language runtime to initialize the variable. It still addresses the two basic problems that the Singleton pattern is trying to solve: global access and instantiation control. The public static property provides a global access point to the instance. Also, because the constructor is private, the Singleton class cannot be instantiated outside of the class itself; therefore, the variable refers to the only instance that can exist in the system.

Because the Singleton instance is referenced by a private static member variable, the instantiation does not occur until the class is first referenced by a call to the Instanceproperty. This solution therefore implements a form of the lazy instantiation property, as in the Design Patterns form of Singleton.

The only potential downside of this approach is that you have less control over the mechanics of the instantiation. In the Design Patterns form, you were able to use a nondefault constructor or perform other tasks before the instantiation. Because the .NET Framework performs the initialization in this solution, you do not have these options. In most cases, static initialization is the preferred approach for implementing a Singleton in .NET.

Multithreaded Singleton

 

 

Static initialization is suitable for most situations. When your application must delay the instantiation, use a non-default constructor or perform other tasks before the instantiation, and work in a multithreaded environment, you need a different solution. Cases do exist, however, in which you cannot rely on the common language runtime to ensure thread safety, as in the Static Initialization example. In such cases, you must use specific language capabilities to ensure that only one instance of the object is created in the presence of multiple threads. One of the more common solutions is to use the Double-Check Locking [Lea99] idiom to keep separate threads from creating new instances of the singleton at the same time.

 

Note: The common language runtime resolves issues related to using Double-Check Locking that are common in other environments. For more information about these issues, see "The 'Double-Checked Locking Is Broken' Declaration," on the University of Maryland, Department of Computer Science Web site, athttp://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html.

 

The following implementation allows only a single thread to enter the critical area, which the lock block identifies, when no instance of Singleton has yet been created:

 

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}
 

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks.

This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient.

Resulting Context

Implementing Singleton in C# results in the following benefits and liabilities:

Benefits

 

  • The static initialization approach is possible because the .NET Framework explicitly defines how and when static variable initialization occurs.

  • The Double-Check Locking idiom described earlier in "Multithreaded Singleton" is implemented correctly in the common language runtime.

Liabilities

 

 

If your multithreaded application requires explicit initialization, you have to take precautions to avoid threading issues.

Acknowledgments

[Gamma95] Gamma, Helm, Johnson, and Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, 1995.

[Lea99] Lea, Doug. Concurrent Programming in Java, Second Edition. Addison-Wesley, 1999.

[Sells03] Sells, Chris. "Sealed Sucks." sellsbrothers.com News. Available at: http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=411.

 

Inheritance

Inheritance :

  • Inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined.
  • Inheritance is employed to help reuse existing code with little or no modification.
  • The new classes, known as Sub-class or derived class, inherit attributes and behavior of the pre-existing classes, which are referred to as Super-class or Base class.

C# supports two types of Inheritance mechanisms

  1. Implementation Inheritance
  2. Interface Inheritance

Implementation Inheritance:

When a class (type) is derived from another class (type) such that it inherits all the members of the base type it is Implementation Inheritance

Interface Inheritance:

When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.

Benefits of using Inheritance

  • Once a behavior (method) or property is defined in a super class (base class),that behavior or property is automatically inherited by all subclasses (derived class).
  • Code reusability increased through inheritance
  • Inheritance provide a clear model structure which is easy to understand without much complexity
  • Using inheritance, classes become grouped together in a hierarchical tree structure
  • Code are easy to manage and divided into parent and child classes
public class ParentClass
{
    public ParentClass()
    {
        Console.WriteLine("Parent Constructor.");
    }
    public void print()
    {
        Console.WriteLine("Parent Class.");
    }
}
public class ChildClass : ParentClass
{
    public ChildClass()
    {
        Console.WriteLine("Child Constructor.");
    }
    public static void Main()
    {
        ChildClass child = new ChildClass();
        child.print();
    }
}

Output:

Parent Constructor.

Child Constructor.

Parent Class.

Encapsulation

  • Encapsulation is a procedure of covering up of the data & functions into a single unit called as class 
  • An encapsulated object is often called an abstract data type. 
  • Encapsulation can protect your data from accidental corruption. 
  • Rather than defining the data in the form of public, we can declare those fields as private.

Code Example :

public class School
{
	private string Schooldepartname;
	public string SchoolDepartname
	{
		get
		{
			return Schooldepartname;
		}
		set
		{
			Schooldepartname =value;
		}
	}
}
public class Departmentmain
{
	public static int Main(string[] args)
	{
		School d= new School();
		d.SchoolDepartname="Communication";
		Console.WriteLine("The Dept. Name is :{0}",d.SchoolDepartname);
		return 0;
	}
}

 

Output:

The Dept. Name is : Communication

Benefits of Encapsulation :

  • In Encapsulation fields of a class can be read-only or can be write-only.
  • A class can have control over in its fields.
  • A class can change data type of its fields anytime but users of this class do not need to change any code.

From the above we can see the use of Encapsulation by using properties. The property has two accessor get and set. The get accessor returns the value of the some property field. The set accessor sets the value of the some property field with the contents of "value". Properties can be made read-only. This is accomplished by having only a get accessor in the property implementation.

SQL Injection attack by Example and how to prevent it in asp.net:

Today we will be learning about the SQL injection attack and ways to prevent this attack using simple coding practices. Using simple practices you can keep your database away from SQL injection attack. Many databases in today's world are prone to SQL Injection attack. This attack is often used by attackers to attack the database which means it can gain access to database and manipulate the database. This attack can be more dangerous if account, through which you are accessing the database, has all privileges to access database then attacker can delete the tables or even database itself.

What is SQL Injection attack?

Example 1:-

Consider a simple functionality which you have on your website where you use username in the SQL query to get details of user and based on result you proceed.

String Query = “select * from User_master where User_name ='"+ txtUsername.Text;

Now in textbox txtUsername you pass following value as "'; drop table User_master - -"

Now your Query will be like below

select * from User_master where User_name = ''; drop table User_master - -'

 

Now what this above code does it executes two statements in first statement it Executes the statement

select * from User_master where User_name = ''

 

After that semicolon (;) is there which tells SQL that it is end of first statement then after that it executes the second statement. drop table User_master and drops the table Note that:- Even if semicolon is not there it will take two as different statements as SQL it self can not identify SQL statement and Parameter you have to tell him which is query and which is parameter

Ways to prevent SQL injection attack

Below are some of the common coding practices which can be used to prevent the SQL Injection attack and make your application database secure. Use validation for input values: - You can check for User input inside the textboxes and validate them according to the expected value so no other value will be inserted into the database. In below example database expects only Numeric value so we have use a RegularExpressionValidator which will allow only numeric value to be entered inside the textBox

<asp:TextBox ID="txtid" runat="server"></asp:TextBox></span>
        <asp:RegularExpressionValidator ID="regExp" runat="server" ErrorMessage="*" ValidationExpression="^(-)?\d+(\.\d\d)?$"
            ControlToValidate="txtid"></asp:RegularExpressionValidator>

 

Use of Parameterized Query: Another way of preventing SQL Injection is using Parameterized Query, where you pass the required. As we pass parameter differently to Query it is not vulnerable to SQL Injection attack. AS SQL distinguishes between Parameter and Query.

SqlConnection conn = new SqlConnection(connectionString)
        DataSet ds = new DataSet();
        SqlDataAdapter da= new SqlDataAdapter("SELECT * FROM User_master WHERE au_id = @u_id", conn);                
        da.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
        da.SelectCommand.Parameters["@au_id"].Value = txtUsername.Text;
        da.Fill(ds);

 

Use of Stored Procedure: Another way of preventing SQL Injection is using Stored Procedure, where you pass the required parameters with values to the stored procedure which is defined for the stored procedure. As to stored procedure you pass value stored procedure takes it as Parameter so there is no risk of Database attack.

SqlConnection conn = new SqlConnection(connectionString)
        DataSet ds = new DataSet();
        SqlDataAdapter da= new SqlDataAdapter("p_get_user_details", conn);   
        da.SelectCommand.CommandType = CommandType.StoredProcedure;
        da.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
        da.SelectCommand.Parameters["@au_id"].Value = txtUsername.Text;
        da.Fill(ds);

 

Abstraction

Abstraction :

  • Abstraction refers to the act of representing essential features without including the background details or explanations.
  • Abstraction defines way to abstract or hide your data and members from outside world.
  • Classes use the concept of abstraction and are defined as a list of abstract attributes.
  • Simply speaking Abstraction is hiding the complexities of your class or struct or in a generic term Type from outer world.
  • This is achieved by means of access specifiers.
Access Modifier Description (who can access)
Private Only members within the same type.  (default for type members)

Protected

Only derived types or members of the same type.
Internal Only code within the same assembly. Can also be code external to object as long as it is in the same assembly.  (default for types)
Protected internal Either code from derived type or code in the same assembly. Combination of protected OR internal.
Public Any code. No inheritance, external type, or external assembly restrictions.

 

Code Example :

namespace AbstractionExample
{
public abstract class Shape
        {
            private float _area;
            private float _perimeter;

            public float Area
            {
                get
                {
                    return _area;
                }
                set
                {
                    _area = value;
                }
            }
            public float Perimeter
            {
                get
                {
                    return _perimeter;
                }
                set
                {
                    _perimeter = value;
                }
            }
            public abstract void CalculateArea();
            public abstract void CalculatePerimeter();
        }
}


Advantages of abstraction : are the hiding of implementation details, component reuse, extensibility, and testability. When we hide implementation details, we reveal a cleaner, more comprehensible and usable interface to our users. We are separating our interface from our implementation, and this makes component reuse more practical. Many, if not all of the object-oriented concepts we have discussed throughout this document play a role in the abstraction principle. Working together, their end goal is the same, to produce software that is flexible, testable, maintainable, and extensible.

Get Value from Embedded Resource File

In ASP.Net it is better to used embedded resource for setting up the text for controls, message, etc for your web application. Add a App_GlobalResources folder and then add a resource file. Right-click on the resource file, go to properties and set the option as shown below:

Now add a class in your class library as :

using System;
using System.Globalization;
using System.Web;

namespace Common.Helper
{
    public static class ResourceHelper
    {
        const string ResourceBase = "WebUI";

        public static string GetResourceName(string resourceFile, string configKey, bool showWarningOnMissingKey)
        {
            return HttpContext.GetGlobalResourceObject(resourceFile, configKey) as string jQuery152025080017000436783_1326121562716
                           (showWarningOnMissingKey
                                ? string.Format("{0} not found in {1}.resx file", configKey, resourceFile)
                                : configKey);
        }

        public static string GetValue(string key)
        {
            CultureInfo culture = CultureInfo.CurrentCulture;
            //First try to load resource value from App_GlobalResources in case user is localizing control
            object val = HttpContext.GetGlobalResourceObject(ResourceBase, key, culture);
            if (val != null)
            {
                return val.ToString();
            }
            //If no value is found then load it from the embedded resource file (Localization/Resource.resx)
            Type type = HttpContext.Current.ApplicationInstance.GetType();
            if (type.BaseType != null)
            {
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(type.BaseType);
                //string name = assembly.GetName().ToString();
                var myManager = new
                    System.Resources.ResourceManager("Web.UI.App_GlobalResources.WebUI", assembly);
                try
                {
                    return myManager.GetString(key, culture);
                }
                catch (Exception)
                {
                    return string.Format("{0} not found in {1}.resx file", key, "WebUI");
                }
            }
            return string.Format("{0} not found in {1}.resx file", key, "WebUI");
        }
    }
}

If you have a custom controls where you want to read from a resource file: 

txt.Text = ResourceHelper.GetValue(ConfigKey);

Also in you Web pages you can directly use as:

using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Resources;


namespace Web.UI.Reports
{
    public partial class ProspectCallback : System.Web.UI.Page
    {
        #region Page Events
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.Master != null)
            {
                var lblPageTitle = (Label)Page.Master.FindControl("lblPageTitle");
                if (lblPageTitle != null)
                {
                    lblPageTitle.Text = WebUI.PageTitle; //WeUI is namespace of resource file.
                }
            }            
        }
       
    }
}

Hope this helps.

Sumedh. 

Select distinct from generic list using linq

If you have a generic list which has a multiple data like

ID  FirstName  LastName  City  State Zip

1   ABC           Z              PN   LA     25341

2   XYZ           R              UI   TG     56742

1   ABC           W             PN   LA     25341

3   UHY           R             HJ    UH    34256

3   UHY           J              HJ    UH    34256 

Now if you want to get select distinct rows on based on ID, then through Linq this can be done easily as :

 

var unique =
    from w in genericList
    group w by w.ID
    into g
        select g.FirstOrDefault();

 

This will be useful where we have the generic list with duplicate data or data with duplicate IDs.

 

Sumedh

Finding all controls in an ASP.NET Page

This can be done through enumerating all the controls in the control hierarchy:

Add a method in a common class

 

/// <summary>
/// Find the Controls inside a Page
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
public static IEnumerable<Control> EnumerateControlsRecursive(Control parent)
{
     foreach (Control child in parent.Controls)
     {
            yield return child;
            foreach (Control descendant in EnumerateControlsRecursive(child))
               yield return descendant;
      }
 }

 

Implement this method like this on the PreRender event of a page :

 

 protected override void OnPreRender(EventArgs e)
 {
      foreach (var control in RecursiveHelper.EnumerateControlsRecursive(this))
     {
                
        if (control is TextBox)
           SetTextBoxStyle(control as TextBox);

        if (control is RegularExpressionValidator)
           SetTextBoxEnterValidation(control as RegularExpressionValidator);
      }
 }

 

Then add your method seperately for assigning the common attributes to each control.

 

 private static void SetTextBoxStyle(TextBox textBox)
 {
       textBox.CssClass = "emptyMessageStyle";
 }

 

 

Hope this will help.

Sumedh