Archive for July, 2008
Working with Configuration files
Introduction
Configuration files are central place to configure your web or windows applications. The web.config file is used for configuring the web applications and app.config for windows applications.
The ASP.NET Application comes with web.config file with default configuration sections and you can easily manage them at the intialstage of the project development. As soon as your project grows mature, web.config file turns out to be a huge file.
The configuration files can be different from development environment to production environment.
Example: Connection strings, Application settings, logging and compilation settings are differed from development to production environment.
Maintaining multiple configuration files is pain to manage, For this .NET configuration system has a feature that each configuration section can define an attribute named “configSource” to define an alternative location from where the configuration file has to be loaded.
Example: In web.config file locate the connectionStrings section and add a new attribute name configSource and give the value as “MyConnectionStrings.config”.
1: <connectionStrings configSource="MyConnectionStrings.config"/>
Add a new file called “MyConnectionStrings.config” to the same directory where web.config lives and define its contents as follows:
1: <?xml version="1.0"?>
2: <connectionstrings>
3: <add name="MyDataBase" connectionstring=” ”/>
4: <connectionstrings>
Key points:
- External configuration file must contain the section name as the root element.
- If you use configSource you must not define any other attribute or child element for the respective section in the web.config file.
- It is useful if you move all your configuration files to subfolder to keep root directory clean.
LINQ Architecture
Introduction
Language-Integrated Query (LINQ) is a new feature introduced in visual studio 2008 and .NET Framework 3.5. Developers can write the queries in the code to retrieve the data from various types of data sources like SQL,XML and XQuery.
Earlier developers has to learn the syntax for writing queries for each data source. LINQ simplifies by offering a model to work with the data across various kinds of data sources.
LINQ Architecture
By using LINQ you can query and transform the data in
- XML Document
- SQL Databases
- ADO.NET Datasets
- .NET Collections
LINQ Query operation contains three parts
1. Obtain the data source.
2. Create the Query.
3. Execute the Query.
LINQ Example
class LINQExample
{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
string[] names = new string[4] { “TOM”, “DAN”, “ADAMS”, “BERNARD” };
// 2. Query creation.
// nameQuery is an IEnumerable<string>
var nameQuery =
from name in names
where name == “TOM”
select name;
// 3. Query execution.
foreach (int name in nameQuery)
{
Console.Write("{0,1} ", name);
}
}
}
Important thing to notice is when write a query it do not retrieve any data. In order to get the data from data source you need to execute the query.
The data source in the above example is Array and implicitly supports IEnumerable interface. All types that support IEnumerable<T> are called queryable types.
Query expression contains three clauses from, where and select.
The from clause specifies the data source, where clause applies the filter and select clause specifies the types of returned elements.
Query executes in foreach statement in the example. The actual execution of the query starts when iterate over the query variable in foreach statement.
Forcing Immediate Execution
Queries that perform aggregate operations must first iterate over those elements. Example Count, Max and Average.
These execute without an explicit foreach statement.
int nameCount = nameQuery .Count();
1 comment
Lambda Expressions in C# 3.0
Lambda expressions is one of the features introduced in the C# 3.0. Lambda expressions help you to ease the burden of writing verbose Anonymous Methods.
I will explain the where to use the Anonymous methods first then we see the example on lambda expressions
Anonymous Methods
Anonymous Methods is the feature in C# 2.0. The idea behind writing the anonymous methods is to write methods inline to the code with out declaring a formal named method. Normally they used for small methods that don’t require any reuse.
Example:
class TestProgram
{
static void Main( string[] args )
{
List<string> names = new List<string>();
names.Add(“Kalyan”);
names.Add(“Suresh”);
names.Add(“Naveen”);
string strResult = names.Find(IsKalyan);
}
public static bool IsKalyan(string name)
{
return name.Equals(“Kalyan”);
}
}
You can declare a anonymous method as follows
class TestProgram
{
static void Main( string[] args )
{
List<string> names = new List<string>();
names.Add(“Kalyan”);
names.Add(“Suresh”);
names.Add(“Naveen”);
string strResult = names.Find(delegate (string name )
{
return name.Equals(“Kalyan”);
} );
}
}
Advantage: It saves some typing and puts the method closer to where it is being used which helps with maintenance
Lambda Expressions
Lambda Expressions makes the thing even more easier by allowing you to write avoid anonymous method and statement block.
class TestProgram
{
static void Main( string[] args )
{
List<string> names = new List<string>();
names.Add(“Kalyan”);
names.Add(“Suresh”);
names.Add(“Naveen”);
string strResult = names.Find( name => name.Equals(“Kalyan”));
}
We can also effectively use the Lambda Expressions with LINQ and i will explain the feature in forth coming articles.
No commentsExtension Methods Feature in C# 3.0
It is one of the new feature introduced in C# 3.0 “As the name implies, extension methods extend existing .NET types with new methods.”
Here i am going to extend the String type to write an extension method.
Example Adding a IsValidEmailAddress method onto an instance of string class:
namespace Extensions
{
class TestProgram
{
static void Main(string[] args)
{
string strEmployeeEmail = “kalyan@techbubbles.com”;
if (strEmployeeEmail.IsValidEmail() ) // IsValidEmail is extension method
{
//Do something
}
}
}
public static class Extensions
{
public static bool
IsValidEmail( this string s )
{
// Do something
return;
}
}// this key word in front of the parameter makes this an extension method
}
The extension methods should be static methods in a static class with in same namespace as shown above. The this keyword in front of the parameter makes an extension method.
2 commentsObject and Collection Initializers Feature in C# 3.0
C# 3.0 introduced the another interesting feature Object and Collection initialization expressions.
Object Intialization Expressions allows you to initialize an object without invoking the constructor and setting its properties.
If you take Employee Class as an Example:
public class Employee {
private int iEmpId;
private string strFirstName;
private string strLastName;
public int ID{
get{
return iEmpId;
}
}
public string FirstName {
get {
return strFirstName;
}
set {
strFirstName= value;
}
}
public string LastName {
get {
return strLastName;
}
set {
strLastName = value;
}
}
public Employee() {}
}
We can use Object Intialization Expressions in C#3.0 Features to create a Employee as follows:
Employee objEmployee = new Employee {ID=007, FirstName = “Kalyan” LastName = “Bandarupalli” }
Now observe the above code we have neither invoked the constructor nor set the any properties directly. The code above is equivalent to the following code:
Employee objEmployee = new Employee();
objEmployee.ID = 007;
objEmployee.FirstName = “Kalyan”;
objEmployee.LastName = “Bandarupalli”;
We can use Collection Intialization Expressions in C#3.0 Features to create a list of Employees as follows:
List<Employee> listofEmployees = new List<Employee>
{ {objEmployee.ID = 007, objEmployee.FirstName = "Kalyan”},
{objEmployee.ID = 007, objEmployee.FirstName = "Suresh”},
{objEmployee.ID = 007, objEmployee.FirstName = "Naveen”}
};
The advantage of using this feature is that it saves your time for creating a lot of constructors or initializing the individual property.
2 commentsAutomatically Implemented Properties Feature in C# 3.0
Introduction of Automatic Properties in C# 3.0 make property declaration more concise. It saves some of your time in typing a lot of code.
Example:
class Employee
{
public string FirstName { get; set; }
}
Benefit of using Automatic Properties
We have been creating properties in so many projects and notice that we are writing so many lines of code just for creating a simple property.
Example: Employee class that does not use Automatic Properties
public class Employee {
private int iEmpId;
private string strFirstName;
private string strLastName;
public int ID{
get{
return iEmpId;
}
}
public string FirstName {
get {
return strFirstName;
}
set {
strFirstName= value;
}
}
public string LastName {
get {
return strLastName;
}
set {
strLastName = value;
}
}
}
In order to create a simple property, we are coding extra four or five lines code. So, if we have 100 properties in different entity classes, we have to type too much of code just for creating properties.
If you convert above Employee class with Automatic properties it look like
class Employee
{
public int ID{ get; private set; } // read-only
public string FirstName { get; set; }
public int LastName { get; set; }
}
Note: This is my first article to explain the C# 3.0 tutorial series.
Conclusion
It is one of C# 3.0 Language feature and nothing new except it helps you to improve your productivity.
2 commentsVisual Studio Team System 2008 Team Suite Overview
Microsoft Visual studio team system 2008 is an integrated Application development and management solution which contains tools, processes and guidance to help everyone on the team to improve their skills and work more effectively together.
VS 2008 Team Suite provides set of tools for architecture, design, development, database development,and testing of applications.Team members can collaboratively work with these tools and effectively contribute in all phases of the development.
Team System 2008 having the following editions
- Database Edition
- Architecture Edition
- Development Edition
- Test Edition
- Test Load Agent
- Team Foundation Server
Team Foundation Overview
The core concept when we talk about Team Foundation is TeamProject.
A Team Project is stored on Team Foundation Server and that can uniquely identify by everyone in the team.The team project provides a central location for everyone to co-ordinate his work.
Test driven development using C#
This post explains how TDD can be implemented in C# using NUNIT.
You can read the Introduction TDD to get an idea on TDD.
Nunit is a open source framework to for .NET which helps you to automate the unit testing. Nunit can downloaded from the Nunit site. current version is 2.5.
Nunit provides two utilities for running the automated tests
nunit-gui.exe – GUI toolnunit-console.exe – Command line tool
Using Nunit in Visual studio .NET Project
To implement the TDD we need to write
- Test cases
- program that is having test cases to run against it
Behavior of the Person C# class that we are going to write test cases
The Behavior can be described as follows
- A Person has properties age,full name and cash balance.
- When instantiating a person we should able to provide a first name, last name and age.
- The person full name property should return first name and last name with a space in-between.
- When you are creating person object cash balance should be 20000.
- The cash balance should be reduced by the amount he with draws.
From the Above behavior we can formulate a number of test cases example
- If we create a person with first and last name of “Kalyan” and “Bandarupalli” , and age 27, the person’s full name should not be ” Kalyan Hero”.
- The person full name should be “Kalyan Bandarupalli”.
- The person’s age should be 27.
- Before withdrawing money the person’s cash balance should be 20000.
- After withdrawing 10000 cash, the person’s cash balance should be 10000.
We can implement the above test case in code[C#] using Nunit. To create a test case in your application create a class having the [TextFixture] attribute.
This class will contain test to test the methods,operations and values in Person class.
No commentsIntroduction to Test driven development
Test driven development(TDD) is a agile methodology technique to develop the software applications. It is one of the basic tenets of eXtreme Programming(XP).
In Test driven development life cycle unit-test cases written before the code it self. These test cases contains assertions that can be either true or false.
Unique feature of TDD is developer can focus on the requirements before writing the code. Comparative to other methodologies this is a substantial difference.
The following are the steps in the TDD lifecycle
- Add a test: In Test driven development, we will write a test case for every new feature. This test case will fail because there is no implementation for this feature through code.
- Run all tests: Make sure that every test will fail as there is no implementation for these test cases.
- Write Some Code: In this phase we can write some code that will cause the test to pass. It is important that the code written is only to pass the test not to extend the functionality.
- Run the automated tests and see them succeed: If all test cases are pass it means that the code meets all the tested requirements.Now we can begin the final step of the life cycle.
- Refactor code: Code cleanup activities can be performed now. By re-running the test cases developer can be confident that refactoring is not damaging any existing functionality.
Benefits:
- Test driven development (TDD) can help to build software better and faster
- It allows the programmer to focus on the task to make the test case pass.
- It ensures that all written code is covered by test and this can give the programmer a greater level of trust in the code.
- Large number of test cases help to limit the number of defects in the code.
In the next article i am going to explain about TDD using C#.
1 commentJoins in SQL server
Fundamentals of joins in SQL server
By using joins, we can get the data from two or more tables based on logical condition between the tables.
The two tables in a query related by
- specifying a column from each table used in the join.
- specifying a logical operator to be used in the comparing the columns.
The following are joins by classification
- Inner join
- Outer join
- Left outer join
- Right outer join
- Cross join
- Self join
Inner join: is a join which returns only the rows for which there is
an equal value in the join column. Inner joins can be specified in either the
FROM or WHERE caluses.
Recommended method is specify the join condition in FROM clause which helps in specifying the other conditions in the WHERE clause.
FROM <First_Table> <Join_Type> <Second_Table>
[ON <join-condition> ]
Example: SELECT *
FROM Employee AS e
INNER JOIN Department AS d
ON e.DepartmentID = d.DepartmentID
Inner join becomes an Equi join when you specify equality condition in JOIN clause.
Outer join: is a join which returns all the rows from the at least one of
the tables mentioned in the FROM clause and meeting the condition in the WHERE clause.
Outer joins can be specified in the FROM clause only.
All rows are retrieved from the left table referenced with a left outer join
and all rows retrieved from the right table with a right outer join.
All rows from the both tables are returned in a full outer join.
Left outer join example:
SELECT
Employee.EmployeeID,Employee.EmployeeName,Department.DepartmentName FROM Employee LEFT OUTER JOIN Department ON Employee.DepartmentID = Department.DepartmentID
Right outer join example:
SELECT
Department.DepartmentID,Department.DepartmentName,Employee.EmployeeName FROM Employee RIGHT OUTER JOIN Department ON Employee.DepartmentID = Department.DepartmentID
Cross join: A cross join is join which does not have a WHERE clause and
produces the cartesian product of the tables involved in the join.
The size of the cartesian product result set is the number of rows in the
first table multiplied by the number of rows in the second table.
Example:
SELECT p.SalesPersonID, t.Name AS Territory
FROM Sales.SalesPerson p
CROSS JOIN Sales.SalesTerritory t
Self-Joins: A table can be joined to itself in a self-join. For example, you can use a self-join to find the products that are supplied by more than one vendor.
Example:
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID <> pv2.VendorID