Sunny Ahuwanya's Blog

Mostly notes on .NET and C#

Want To Pass 70-562? Here’s How.

After studying for the past few months I took the Microsoft .NET Framework 3.5, ASP.NET Application Development exam today and passed with a score of 873.
This is certainly the broadest certification exam I’ve taken so far. I almost spent the entire allotted two and a half hours on the test.
I'm now MCTS .NET Framework 3.5, ASP.NET Applications. This is really cool considering that as at today there are only about 271 certified people worldwide. Cool
I guess everyone else is waiting for the training kit to be released in April next year.

If you can't wait till April, here's how I studied:

Prerequisites:

Study Plan:

  • If you are not comfortable with ASP.NET AJAX, read Introducing Microsoft ASP.NET AJAX by Dino Esposito.
  • Read Programming Microsoft ASP.NET 3.5, also by Dino Esposito. This is a very detailed book on ASP.NET. It covers a broad and practical range of ASP.NET topics.
  • Get a copy of MCTS Self-Paced Training Kit (Exam 70-528). This is the training kit for the .NET 2.0 version of this exam. You’ll need it to study topics not covered in the books I mentioned earlier.
    • Study Chapters 4, 5, 10, 12 and 13.
    • Practice the “Practice tests” on the CD that comes with this kit especially questions from the mentioned chapters.
  • Purchase and practice the Measure-up practice tests, available at http://www.measureup.com/catalog/exam.aspx?vid=5&cid=MCTS&tid=139 . I cannot over-emphasize this step. It is important that you score a 100% twice on ALL the questions before attempting this exam. Do not take the exam if you have not seen and understood all questions and answers in the Measure-up practice tests. It’s a great indicator of your preparedness level.
  • Take a look at the 70-562 Preparation Guide and if there is any topic you do not instantly recognize, look it up in MSDN and learn it.

Tips:

  • Practice every topic from each book you study.
  • If there is anything you do not understand, Google it and master it.
  • Pay particular attention to features that are new with ASP.NET 3.5 such as the Listview control, IIS 7, WCF, Aspnet_merge.exe, Datapager control, etc.
  • Practice a lot of web.config configuration settings and command line tools like Aspnet_Compiler.exe, Aspnet_regiis.exe, etc.


Do not under-estimate this exam; it is difficult because it covers a very wide range of topics. The exam basically tests your ASP.NET 3.5 experience-level.
However, by the time you study and practice all the topics I’ve mentioned, you’ll be quite experienced.
Good luck!!

 

C# Brainteasers Part I

Every now and then, I pick up C# Precisely by Peter Sestoft and Henrik I. Hansen, a great C# reference book that should be recommended more often.
Every time I read the text, I find bemusingly odd but very correct C# code examples.

Here are some C# brainteasers I've compiled from the book. The answers are at the end of this post.

1. What does the following code display?

class Concat
{
    static void Main()
    {
        Console.WriteLine(20 + 45 + "A");
        Console.WriteLine("A" + 20 + 45);
    }
}

Okay, that one was easy -- how about the rest?

2. What is wrong with this code?

class One
{
    sealed void SealedOnly()
    {
        // Do something
    }
    
    virtual void Virt()
    {
        // Do something
    }
}

3. What is wrong with this code?

class BaseClass
{
    public BaseClass (string Arg0)
    {
        //Do stuff       
    }
}

class DerivedClass : BaseClass 
{
    //Do more stuff
}

4. What is wrong with this code?


class Student
{
    public Student (string Name) 
    {
        //Call other constructor
        this.Student(Name, null);
    }

    public Student (string Name, DateTime? DateEnrolled)
    {
        this.name = Name;
        this.dateEnrolled = DateEnrolled;       
    }

    private string name;
    private DateTime? dateEnrolled;

}

5. What is the class access modifier for class A? how about class B?

class A
{
    class B
    {

    }
}


Answers:

1.
The code will display:

65A
A2045

This is because the + operator is left associative.


2.
The code will not compile because of errors (shown in comments) below.

class One
{
    sealed void SealedOnly() //error CS0238: Cannot be sealed because it is not an override 
    {
         // Do something
    }

    virtual void Virt() //error CS0621: virtual or abstract members cannot be private
    {
       // Do something
    }
}

You can’t have a sealed method that does not override a base method.
You can’t have a virtual or abstract method with a private access modifier.


3.
The code will not compile because of the error (shown in the comment) below.
class BaseClass
{
    public BaseClass (string Arg0)
    {
        //Do stuff       
    }
}

class DerivedClass : BaseClass // error CS1501: No overload for method 'BaseClass' takes '0' arguments (DerivedClass must explicitly call BaseClass constructor because there is no parameterless base constructor)
{
    //Do more stuff
}
This one is a bit tricky to explain. The C# compiler generates a parameterless constructor for concrete classes without any defined constructors. If there was no constructor defined for the base class, then the C# compiler will generate a parameterless constructor.
A parameterless constructor will also be generated for the derived class (since it doesn’t have any constructors) which will override the parameterless constructor for the base class.

In this case, a constructor with a single parameter was defined for the base class, so the C# compiler will NOT generate a parameterless constructor for the base class. The derived class however will have a parameterless constructor generated. The problem with the code snippet above is that the derived class’s parameterless constructor can not find a base parameterless constructor to override.

To resolve this issue, you can add a parameterless constructor to the base class, add a constructor with the same signature as the one in the base class to the derived class, or add a parameterless constructor to the the derived class with this declaration:
public DerivedClass(): base("")
{
}
This creates a parameterless constructor for the derived class which calls the base class constructor


4.
The code will not compile because of the error (shown in the comment) below.
    class Student
    {
        public Student(string Name) 
        {
            this.Student(Name, null); // error CS0117: 'Student' does not contain a definition for 'Student'
        }

        public Student(string Name, DateTime? DateEnrolled)
        {
            this.name = Name;
            this.dateEnrolled = DateEnrolled;
        }

        private string name;
        private DateTime? dateEnrolled;

    }
You cannot call constructor code using regular method access syntax, even from another constructor.
To call another constructor, use this syntax:
public Student(string Name) : this(Name, null)
{
}

5.
 A - internal
 B - private
Top-level classes without a class access modifier default to internal (and can only be either public or internal).
Nested classes without a class access modifier default to private.


Generate Stored Procedure Wrapper Methods and Associated Wrapper Classes

Introduction

It is generally a good idea to create a wrapper method for every stored procedure that an application needs to call. Such methods can then be grouped into a single data access utility class. This approach improves type safety and portability.

These methods generally call the Command.ExecuteScalar, Command.ExecuteNonQuery and Command.ExecuteReader ADO.NET methods. They also perform tasks like checking if the Connection object is still connected, adding stored procedure parameters to the Command object, making sure the DataReader object is properly disposed, etc.

On the average, there are about fifty lines of code for a properly written method that wraps an ExecuteReader call! Writing these methods easily eats into overall development time on data-intensive projects that access many stored procedures.

Developers usually resort to copying and pasting code from other wrapper methods and modifying the code to suit the stored procedure call. This process often leads to bugs due to human error.

I figured that since most of these methods share a common programming pattern; it should be possible to describe what your stored procedure looks like to a code generation tool and have the tool generate these methods. Nothing as complex as AutoSproc, just a light tool that lets a developer specify details of the stored procedure, and then generate the wrapper method code.

Implementation

This tool was developed with ASP.NET 2.0. It makes code generation decisions based on information provided by the user – pretty much the same way a human developer would make coding decisions.
It supports .NET 1.1 and .NET 2.0 features, for instance it would create nullable variables for nullable fields if .NET 2.0 is selected. It supports the SQL Server and ODBC data providers.

The actual code generation code (no pun intended) is in APP_Code\MethodGen.cs while the user interface code is in the sprocmethodgen.aspx.
The code generation code can easily be used by another application with a different user interface (for instance, a desktop-application that supplies most of the input from the actual database schema). It can also be easily modified to follow a different programming pattern or support more ADO.NET features.

The meat of the code generation code lies in the GenerateMethod, GenerateTryClause and GenerateResultsWrapperClass methods of the MethodGenerator class. The GenerateMethod method generates the non-varying parts of the method such as sections that add parameters to a command object. It also calls the GenerateTryClause method and optionally the GenerateResultsWrapperClass method.

The GenerateTryClause method generates the big try clause in the method which varies greatly, depending on what type of execution was selected.

The GenerateResultsWrapperClass method generates a class which stores results returned by a DataReader. (It’s better to return a list of strongly typed objects than returning a DataTable.)

Using the Tool

This example uses the ‘Sales by Year’ stored procedure in the Northwind database.

1) Run the ASP.NET solution, and navigate to the web page.

This tool is also available at www.ahuwanya.net/tools/sprocmethodgen/

2) Specify the .NET Version, Data Provider, Stored Procedure name, and Type of Execution.

3) The Sales by Year stored procedure has two input parameters, so specify the two input parameters:

4) After running the stored procedure, it is discovered that it has four columns in the result set, so specify the four result columns:


5) Specify the name of the class that will store the results and the name of the generated method.

6) Click the Generate Code! button to generate the code. You may need to scroll down on the page.
(To view the generated code, click the expand source button below.)

internal static List<SalesInfo> GetSalesByYear(DateTime StartDate, DateTime EndDate, SqlConnection DBConn )
{
	//TODO: Insert method into your data access utility class
	
	//Check if connection is null
	if(DBConn == null)
	{
		throw new ArgumentNullException("DBConn");
	}

	//Open connection if it's closed
	bool connectionOpened = false;
	if(DBConn.State == ConnectionState.Closed)
	{
		DBConn.Open();
		connectionOpened = true;
	}

	//TODO: Move constant declaration below directly into containing class
	const string sprocGetSalesByYear = "[Sales by Year]";

	string sproc = sprocGetSalesByYear;

	SqlCommand cmd = new SqlCommand(sproc,DBConn);
	cmd.CommandType = CommandType.StoredProcedure;
	cmd.Parameters.Add("@Beginning_Date",SqlDbType.DateTime ).Value = StartDate;
	cmd.Parameters.Add("@Ending_Date",SqlDbType.DateTime ).Value = EndDate;
	
	List<SalesInfo> result = new List<SalesInfo>();
	SqlDataReader rdr;
	
	try
	{
		rdr = cmd.ExecuteReader();

		try
		{
			if (rdr.HasRows)
			{
				int shippeddateOrdinal = rdr.GetOrdinal("ShippedDate");
				int orderidOrdinal = rdr.GetOrdinal("OrderID");
				int subtotalOrdinal = rdr.GetOrdinal("Subtotal");
				int yearOrdinal = rdr.GetOrdinal("Year");
				
				while (rdr.Read()) 
				{
					// declare variables to store retrieved row data
					DateTime? shippeddateParam;
					int orderidParam;
					decimal subtotalParam;
					string yearParam;
					
					// get row data
					if (rdr.IsDBNull(shippeddateOrdinal))
					{
						shippeddateParam = null;
					}
					else
					{
						shippeddateParam = rdr.GetDateTime(shippeddateOrdinal);
					}
					orderidParam = rdr.GetInt32(orderidOrdinal);
					subtotalParam = rdr.GetDecimal(subtotalOrdinal);
					if (rdr.IsDBNull(yearOrdinal))
					{
						yearParam = null;
					}
					else
					{
						yearParam = rdr.GetString(yearOrdinal);
					}
					
					// add new SalesInfo object to result list
					result.Add(new SalesInfo(shippeddateParam,orderidParam,subtotalParam,yearParam));
					
				}
			}
		}
		finally
		{
			rdr.Close();
		}
		
	}
	catch(Exception ex)
	{
		//TODO: Handle Exception
		throw ex;
	}
	finally
	{
		cmd.Dispose();

		if(connectionOpened ) // close connection if this method opened it.
		{
			DBConn.Close();
		}
	}

	return result;
	

}

[Serializable]
public class SalesInfo
{
	//TODO: Integrate this class with any existing data object class

	private DateTime? shippeddate;
	private int orderid;
	private decimal subtotal;
	private string year;
	
	public SalesInfo(DateTime? ShippedDate, int OrderID, decimal SubTotal, string Year)
	{
		shippeddate = ShippedDate;
		orderid = OrderID;
		subtotal = SubTotal;
		year = Year;
		
	}

	public SalesInfo()
	{
		shippeddate = null;
		orderid = 0;
		subtotal = 0;
		year = null;
		
	}

	public DateTime? ShippedDate
	{
		get { return shippeddate; }
		set { shippeddate = value; }
	}

	public int OrderID
	{
		get { return orderid; }
		set { orderid = value; }
	}

	public decimal SubTotal
	{
		get { return subtotal; }
		set { subtotal = value; }
	}

	public string Year
	{
		get { return year; }
		set { year = value; }
	}

	
}

7) Copy the generated code into your project.

8) Add the following namespaces to your project.

using System.Data; 
using System.Data.SqlClient; //if using SQL Server Data Provider
using System.Data.Odbc; //if using ODBC Provider
using System.Collections.Generic; //if using .NET 2.0 or later
using System.Collections //if using .NET 1.1

9) Look for //TODO: comments in the generated code and act accordingly. The code will still work, even if the //TODO: comments are ignored.

10) Now you can simply access the sales data from your project with the following statements:

 //Create Sql connection
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True");
//Get Sales Information
List<SalesInfo> sales = GetSalesByYear(new DateTime(1992,1,1),new DateTime(2008,1,1),conn);

Considerations and Limitations

Obviously, this tool cannot generate code for every conceivable ADO.NET database access scenario, however, it’s a lot better to generate a great deal of the code and then modify the code as needed, than to type everything by hand.

Some limitations of this tool include:

Generates only C# code: The best way to make this tool to be language neutral would be to use CodeDom to generate the code, however, this approach would make this tool harder to maintain and extend – It would be an overkill for the scope of this project.
Fortunately, there are lots of C#-to-VB.NET code conversion tools available for VB.NET developers who would like to use this tool.

Lacks support for Output Parameters: This tool only supports input parameters and optionally returns the stored procedure return parameter. The generated code can be manually modified to accommodate other types of parameters.

Lacks support for OLEDB and Oracle Data Providers: This tool only generates code for ODBC and SQL Server Data providers.

Reads only the first Result Set: If your stored procedure returns multiple result sets, one way to handle this is to generate a method for the first result set (choose ExecuteReader), then generate another method as if the second result set were actually the first result set, copy the code that reads the result data and paste it into the first method after calling rdr.NextResults(), change the name of the results variable in the pasted code and pass it back as an out parameter.
Do this for every result set returned.

Lacks support for DbCommand object properties: If you are looking for Transaction, CommandTimeOut, CommandBehavior objects etc. -- It’s easy to modify the generated code for these properties.

Unsuitable for Large Result sets: This tool generates code which returns result sets as an ArrayList or an List of strongly-typed objects. This tool will perform poorly if your stored procedure returned hundreds of thousands of rows because it would have to store all these rows. You should write your own data access method for such scenarios.
Moreover, if your stored procedure returns hundreds of thousands of rows, I recommend you look into implementing some kind of paging mechanism to reduce the number of rows returned.

The Extended Euclidean Algorithm

In cryptographic systems, it is usually necessary to calculate the inverse of the modulus function of one number to another.

For example xy = 1 mod 317. As expected it can be very difficult to compute x for any given y.

The Extended Euclidean Algorithm provides an elegant way to calculate this inverse function. The Algorithm calculates the greatest common divisor (gcd) of  two integers.

y, the inverse of x exists if and only if gcd(x, n) = 1

i.e. , for an integer s, there exists an integer y such that xy + sn = 1, where y is the inverse of x mod n, also known as the modular inverse.

To calculate y, using the Extended Euclidean function:
 

The Extended Euclidean Algorithm for finding the inverse of a number mod n.

We will number the steps of the Euclidean algorithm starting with step 0. The quotient obtained at step i will be denoted by qi. As we carry out each step of the Euclidean algorithm, we will also calculate an auxillary number, yi. For the first two steps, the value of this number is given: y0 = 0 and y1 = 1. For the remainder of the steps, we recursively calculate yi = yi-2 - yi-1 qi-2 (mod n). Continue this calculation for one step beyond the last step of the Euclidean algorithm.

The algorithm starts by "dividing" n by x. If the last non-zero remainder occurs at step k, then if this remainder is 1, x has an inverse and it is yk+2. (If the remainder is not 1, then x does not have an inverse.) Here is an example:

Find the inverse of 15 mod 26.

Step 0:             26 = 1(15) + 11           y0 = 0

Step 1:             15 = 1(11) + 4             y1 = 1

Step 2:             11 = 2(4) + 3   y2 = 0 - 1( 1) mod 26 = 25

Step 3:             4 = 1(3) + 1     y3 = 1 - 25( 1) mod 26 = -24 mod 26 = 2

Step 4:             3 = 3(1) + 0     y4 = 25 - 2( 2) mod 26 = 21

                        y5 = 2 - 21( 1) mod 26 = -19 mod 26 = 7


Notice that 15(7) = 105 = 1 + 4(26) is equivalent to 1 (mod 26).

The Extended Euclidean Algorithm is a gift, cryptographically speaking, even though it has many more applications beyond cryptography.

References:
http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm http://www.antilles.k12.vi.us/math/cryptotut/extended_euclidean_algorithm.htm