Translate

Sunday, September 9, 2012

Using NUnit for Microsoft .Net

Using NUnit for Microsoft .Net

Introduction to Unit Testing using NUnit


In this post we will be discuss about the following

What is Unit Testing?
Advantages
Disadvantages
Introduction to  nUnit
Demo
Ncover
Resources

What is Unit Testing

Unit testing is a method/process by which individual units of source code of the software programs are being tested,a unit as the smallest testable part of an application. In procedural programming a unit could be an entire module but is more commonly an individual function or procedure. In object-oriented programming a unit is often an entire interface, such as a class, but could be an individual method.

This helps the developers to modify the source code without immediate concerns about how such changes might affect the functioning of other units or the program as a whole. Once all of the units in a program have been found to be working in the most efficient and error-free manner possible, larger components of the program can be evaluated by means of integration testing. 

Advantages

The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. Unit testing provides a strict, written contract that the piece of code must satisfy. As a result, it affords several benefits.

            Unit testing allows the programmer to re-factor code at a later date, and make sure the module still works correctly (i.e. regression testing). This provides the benefit of encouraging programmers to make changes to the code since it is easy for the programmer to check if the piece is still working properly. 
         
           Because some classes may have references to other classes, testing a class can frequently spill over into testing another class. A common example of this is classes that depend on a database: in order to test the class, the tester often writes code that interacts with the database. This is a mistake, because a unit test should never go outside of its own class boundary. As a result, the software developer abstracts an interface around the database connection, and then implements that interface with their own mock object. This results in loosely coupled code, minimizing dependencies in the system


Disadvantages

            Unit-testing will not catch every error in the program. By definition, it only tests the functionality of the units themselves. Therefore, it will not catch integration errors, performance problems and any other system-wide issues. In addition, it may not be easy to anticipate all special cases of input the program unit under study may receive in reality. Unit testing is only effective if it is used in conjunction with other software testing activities.

            It is unrealistic to test all possible input combinations for any non-trivial piece of software. A unit test can only show the presence of errors; it cannot show the absence of errors.

Introduction to nUnit


            NUnit is a unit-testing framework for all .Net languages. Initially ported from JUnit
            Current Version:Production release, version 2.6,It is being build/designed based unit testing tool for Microsoft .NET. It is written entirely in C#  Language and has been completely redesigned to take advantage of many .NET language features, 
            for example custom attributes and other reflection related capabilities. NUnit brings xUnit to all .NET languages

Download and Current  Versions


Official nUnit Site for download


















Start Unit Testing


Nunit has both GUI and console interfaces 

NUnit Tutorial:http://www.nunit.org/


Unit Testing :Coding Tips
Method Call Coverage
All public methods must be called at least once
Indirect calls allowed
Assertions:
Use AssertEquals(string, object, object) method
Consider use of Random class
Check boundary conditions and failure scenarios (forced-error tests)


Assertions

Assertions are central to unit testing in any of the nUnit frameworks, and NUnit is no exception. NUnit provides a rich set of assertions as static methods of the Assert class. If an assertion fails, the method call does not return and an error is reported to developer. If a test contains more than one assertions, any that follow the one that failed will not be executed. This is the reason, it's usually best to try for one assertion per test. Each method may be called without a message, with a simple text message or with a message and arguments. In the last case the message is formatted using the provided text and arguments.

The Assert class provides the most commonly used assertions.
It provides For convenience of presentation, we group Assert methods as follows:

  1. Equality Asserts 
  2. Identity Asserts 
  3. Comparison Asserts 
  4. Type Asserts 
  5. Condition tests 
  6. Utility methods

Equality Asserts
These methods test whether the two arguments are equal. Overloaded methods are provided for common value types so that languages that don't automatically box values can use them directly.

Assert.AreEqual( int expected, int actual );
Assert.AreEqual( int expected, int actual, string message );
Assert.AreEqual( int expected, int actual, string message, 
                 params object[] parms );

Identity Asserts

Assert.AreSame and Assert.AreNotSame test whether the same objects are referenced by the two arguments.

Assert.AreSame( object expected, object actual );
Assert.AreSame( object expected, object actual, string message );
Assert.AreSame( object expected, object actual, string message, 
                params object[] parms );

Contains
Assert.Contains is used to test whether an object is contained in an array or list.
Assert.Contains( object anObject, IList collection );
Assert.Contains( object anObject, IList collection, string message );

Condition Tests
Methods that test a specific condition are named for the condition they test and take the value tested as their first argument and, optionally a message as the second. The following methods are provided:
Assert.IsTrue( bool condition );
Assert.IsTrue( bool condition, string message );
Assert.IsTrue( bool condition, string message, object[] parms );

Utility Methods
 Two utility methods, Fail() and Ignore() are provided in order to allow more direct control of the test process:
Assert.Fail();
Assert.Fail( string message );
Assert.Fail( string message, object[] parms );

Constraint-Based Assert Model
Assert.That

The constraint-based Assert model uses a single method of the Assert class for all assertions. The logic necessary to carry out each assertion is embedded in the constraint object passed as the second parameter to that method.

Here's a very simple assert using the constraint model:

      Assert.That( myString, Is.EqualTo("Hello") );


Sample Code:


using NUnit;
using NUnit.Framework;
using Rhino.Mocks;
using UniversityEmployeeInformation.UniversityEmployeeRepository;


namespace UniversityEmployeeRepositoryTest
{
    [TestFixture, System.ComponentModel.Description("UniversityEmployeeRepository Test")]
    public class UniversityEmployeeTest
    {
   
        private IUniversityEmployeeRep _employee;
     
   
        [TestFixtureTearDown]
        public void TestFixtureTearDown()
        {

        }
        [SetUp]
        public void Initialize()
        {
             _employee = new UniversityEmployeeRep();
        }
        [Test]
        public void GetEmployee()
        {
            EmployeeFilter employeeFilter = new EmployeeFilter();
            employeeFilter.EmployeeId = 1234;
       
           List<UniversityEmployeeDo> employees=_employee.GetEmployees(employeeFilter);
            Assert.IsNotNull(employees);
        }
   
    }
}


This sample code demonstrate the unit testing with Nunit

Create a class UniversityEmployeeTest  specify the description of testing class by using the attribute
TestFixture,this class has two method which is initializing and shutdown of test case when it is run

1.    [SetUp]
        public void Initialize()
        {
             _employee = new UniversityEmployeeRep();
        }
In the above method we can initialize the object and creation
2.[TestFixtureTearDown]
        public void TestFixtureTearDown()
        {

        }
In the above method we can specify the method to closed the object when the test is executed

3. public void GetEmployee() is the method where it is mentioned   [Test] which we informing the nunit framework that ,this is the method need to test.

In the "GetEmployee()" test case we are just testing the GetEmployees method from Employee class this method returns the list of employees based on the employee filter is passed to "GetEmployees" method.
Since this is a simple test case we just verifying with Assert " Assert.IsNotNull" which returns true if the records exist and it will return false if there is no record exists.



Resources
[1] NUnit - Documentation.  Retrieved March 28, 2005, from http://nunit.org/documentation.html
[2] George, Boby and Laurie Williams. An Initial Investigation of Test Driven Development in Industry. Retrieved March 30, 2005, from http://collaboration.csc.ncsu.edu/laurie/Papers/TDDpaperv8.pdf
[3] Ganssle, Jack.  XP Deconstructed. Dec 10, 2003. http://www.embedded.com/showArticle.jhtml?articleID=16700086
[4] Provost, Peter.  Test Driven Development in .NET. http://www.codeproject.com/dotnet/tdd_in_dotnet.asp
[5] Introduction to Test Drive Development (TDD).  Retreived April 1, 2005, from http://www.agiledata.org/essays/tdd.html
[6] Mugridge, Rick. Test Driven Development and the Scientific Method. http://www.agiledevelopmentconference.com/2003/files/P6Paper.pdf














Wednesday, September 5, 2012

Exception Handling in .Net or Handling Exception in C#

Exception Handling or Handling Exception

What is an Exception

An exception is an indication of an error or exceptional condition such as when try to open a file that is not physically exists or when we write a method which throws exception, the calling code must be able to detect and handle exception.
If the calling method code cannot handle the exception, the exception is automatically propagated to the code that invoked the calling code.

The exception is propagated until a section of code handles the occurred exception.
If no code handles the exception, there are 100 percent chances that it will give runtime errors and will report unhandled exception and finally the application will crash.

How Exceptions Propagate in .Net Framework

This is where exceptions in the .NET Framework prove useful. An exception is an indication of an error or exceptional condition. A method can throw an exception when it detects that something unexpected has happened, for example, it tries to open a file, but the file does not exist. When a method throws an exception, the calling code must be prepared to detect and handle this exception. If the calling code does not detect the exception, it is aborted and the exception is automatically propagated to the code that invoked the calling code. This process continues until a section of code takes responsibility for handling the exception. Execution continues in this section of code after the exception-handling logic has completed.

For an example, suppose the ABC method calls the DEF method. As part of its processing,the DEF method calls the GH method. While it is running, the GH method throws an exception. This exception may cause the GH method to abort, and the exception is passed back to the DEF method. If the DEF method is not prepared to handle the exception, it also aborts and the same exception is passed back to the ABC method. If the ABC method handles the exception, execution continues in the ABC method after the exception-handling logic. If the ABC method is not prepared to handle the exception, the exception will be propagated back to the method that called the ABC method. If this is the Main method, and Main is also not prepared to handle the exception, the application reports the unhandled exception to the user and then terminates.
ABC method can catch and handle its own exceptions to provide a degree of robustness that the calling code may not even be aware of. For example, a method that updates a database may catch an exception that occurs if the connection to the database fails. It may try connecting again, possibly with an alternative set of credentials. This process can be hidden from the code that called the method.

Using Try and Catch in C#

try/catch block is the plays a key role in programming. We wrap the code that may fail and cause an exception in a try block, and add one or more catch blocks to handle any exceptions that may occur.

The following example shows about how to implement Try Catch

try
{
// Try block.
}
catch ([catch specification 1])
{
// Catch block 1.
}
catch ([catch specification 2])
{
// Catch block 2.
}
catch ([catch specification 3])
{
// Catch block 3.
}
catch ([catch specification n])
{
// Catch block n.
}

It can have “n” number of catch blocks.

Catch: The catch specification for each block determines what exceptions will be caught and what variable is used to store the exception, if any. we can specify catch blocks for different types of exceptions.
The .NET Framework defines many different exception types for many of the common exceptions that can occur.
Few of exception types in namespace for example System.IO namespace that handle file I/O throw
the FileNotFoundException exception if an application attempts to access a nonexistent file. In addition, the common language runtime (CLR) itself throws a DivideByZeroException exception if you attempt to perform numeric division by zero. When an exception occurs, you do not have to include a catch block for every type of exception, and exceptions that are not matched will be propagated as described earlier.

If we are not specifying exception type in the catch block then it catches any type of exception

For example

//Try Block code
Try
{
}
//Catch Block Code
Catch
{
}

If we want to know what is the exception occurred we can access by using variable of exception declared in catch block

For example
catch (Exception ex)
{
// Catch block, can access exception in ex.
}

In above example “ex” will give the more information about exception

Important to Note:
 Exception types can implement a hierarchy of exceptions.
 For example,
 The .NET Framework provides an exception type called ArithmeticException, which you can   use to indicate an error when evaluating an arithmetic expression. The DivideByZeroException type is a specific classification of ArithmeticException (the .NET Framework also defines two other types of ArithmeticException called OverflowException and NotFiniteNumberException). If you catch the
DivideByZeroException exception, only that exception type is caught. However, if you catch the ArithmeticException exception, this catch block will trap DivideByZeroException, OverflowException, and NotFiniteNumberException. Therefore, if you have multiple catch blocks, you must ensure that you place the blocks.


Raising Exceptions

Creating an Exception object

1.     System.Exception
  System.SystemException
 System.FormatException
 System.ArgumentException
System.NotSupportedException

List describe the different types of Exception



Type
Description
FormatException
It throw this exception if the caller specified an argument that contains data that does not have the required format. For example, if the caller passes a string argument that does not contain information in the format that the method expects, the method should throw a FormatException exception.
ArgumentException
It throw this exception if the caller specifies an argument to a method that does not conform to the requirements of the method. You can use this exception type to indicate generalized errors with arguments, or you can use the ArgumentOutOfRangeException and
ArgumentNullException types to indicate more
specific errors (for example, if you pass the value 100 to a method, and the method expects a value between 1 and 99, or if you pass the value null as an argument).
NotImplementedException
It throw this exception to indicate that you have not yet implemented the code in a method.
This exception is primarily useful while you are
developing code when you have defined the
method, but have not written the code for the
body of the method
NotSupportedException
You can throw this exception if a caller attempts to perform an unsupported operation by using your method, such as specifying arguments that indicate that the caller wants to write to a read-only file.
FileNotFoundException
DirectoryNotFoundException
DriveNotFoundException
You can throw these exceptions in methods that
attempt to open files on behalf of a caller. If the
name of the file that is indicated by arguments that the caller specifies reference a file that does not exist, or the file is in a folder or drive that does not exist.





Tuesday, September 4, 2012

SharePoint Workflows

SharePoint Workflows

Workflow is the technology introduced by Microsoft for both .net and SharePoint, Workflow involves automation of a business process, in entire or part, during which documents, information or tasks are passed from one person to another person to perform for action(Approve/Reject/Initiate) according to a set of procedural rules.

Workflow is a system that manages the execution of a business process.  Many organizations implement workflows for many different reasons such as:

Better efficiency
Auditing and tracking
Easy tracking
Gives efficient reports
Consistency
Better customer support
Easy to implement out of the box workflow

Workflow actually breaks into smaller parts called activity, there is provision to create the workflow in two different ways
  1. 1     Sequential by Sequential Workflow where the task and process execution is done in predefined sequence and assigned to next level based on the outcome of each step
  2. State Machine workflow involves the undefined steps and it depends on the behavior of each state of the activity.

Activity:  activity is the workflow’s smallest piece or item that execute

There are three types of activities:
 Standard activities.
Control flow activities.
Container activities.

Standard Activities
Standard activities are those that perform some tasks like log history or sending an e-mail or executing
a .NET code or creating a task ect.
Control flow activities
Control flow activities are those that are used as decision points. Examples of control flow activities are if-else, while loop ect.

Container activities
Container activities are those that can host or execute other activities and create a composite activity.
Composite activities are those which involves one or more tasks or activities
Sequence activity, conditioned activities groups are some of the container activities.

Association Form
It is a form so that users associating the workflow can input the information.

Initiation Form
Initiation forms are used to get the input from users. This can also be used for overriding associated data for specific instances of the workflow

Task Forms
Tasks Forms are those that are presented to the users when the user is assigned a task, it asks the user to perform action on the item in SharePoint.

Friday, August 31, 2012

Using Overriding and Hiding Methods in C#


Overriding in C#


Extend or replace functionality in the base class
It is required to provide an implementation that has the same meaning as the original method, but has an implementation that is specific to the class. Virtual methods typically provide a default implementation that
inheriting classes are expected to replace with their own code.
To override a method in a subclass, you use the override keyword, as the following
code example shows
public Class Employee
{
protected int EmployeeNumber;
protected string EmployeeFirstName;
protected string EmployeeLastname;
protected float Salary;
Protected virtual void WorkAssigned()
{
}
}

//Program Manager class inheriting from  Employee class
Public Class TechnicalManager:Employee
{
Protected  Override void WorkAssigned()
{
}
}


Hiding Methods in C#
You can define methods in an inherited class that have the same name as methods
in a base class, even if they are not marked as virtual, abstract, or override.
However, this means that there is no relationship between your method and the
original method, and new method hides the original method.

Code
Public Class Employee
{
protected void  ActOn()
{
...
}
}
class Manager : Employee
{
public new void  ActOn()
{
// Hiding he ActOn method in the base class
//Code goes here
}

}

Inheriting from Classes and Implementing Interfaces

What is Inheritance or How to define Inheritance in C#


Inheritance is the most feature in the object oriented programming.
Inheritance helps not do the repetition of code the same code in the multiple places when dealing with
different classes  which have several features in common and are related to each other. Even they are
different subclasses of the same type, each with its own distinguishing feature


Declared and Define Inherited Class
Parent/Base Class
public Class Employee
{
protected int EmployeeNumber;
protected string EmployeeFirstName;
protected string EmployeeLastname;
protected float Salary;
Protected void WorkAssigned()
{
}

}

//Program Manager class inheriting from  Employee class
Public Class TechnicalManager:Employee
{
Public void ProgramManagerWorkAssigned()
{
}
}

//Program Technical Manager class inheriting from  Employee class
Public Class TechnicalManager:Employee
{
Public void TechnicalManagerWorkAssigned()
{
}
}


example, Program Manager and  Technical Manager ,Engineer are all employees of a Software Company .
When we are writing an application to simulate the Employee Management System, how would you specify that
Program Manager and Technical Manager and Engineer have several features that are the same, but also
other features that are different? For example, they all have an employee reference  employee number and a name and so on, also each one has different responsibilities. When we want to define class of Program Manager and Technical Manager and Engineer each has to be inheriting the employee. So we don’t need to define the common features in all the classes.

In C# inheritance is implemented by using “:” 

Thursday, August 30, 2012

How to Modify Navigation Settings in SharePoint

How to Modify Navigation Settings in SharePoint


It is sometimes it is required to hide/show the navigation of site created in the SharePoint
Sharepoint has a provision to add/remove /hide any links which is displayed in the SharePoint.

Steps

1.     Click on Site Actions èSite Settings. From theèLook and Feel section,
Choose Navigation.
 In the Current Navigation section,
2.     choose the option Display the same navigation items as the parent site and select the Show Pages checkbox:


How to Create Publishing site in SharePoint 2010

How to Create Publishing site in SharePoint 2010

To a new publishing site, publishing site is most important site template used in most of the orgainizations and it gives very good the content management site where the administrators are required to publish the content frequently.This can be done by creating content pages in the sharepoint.

Steps

1.     Go to Central Administration and click on the link for Create Site Collections.

2.     Ensure that the web application is selected correctly.


3. In the Template Selection section, choose the Publishing tab and select the
Publishing Portal template, as shown in the following screenshot:









4. Provide the Primary and Seconday Site Collection Administrator.
5. click OK.
6.Publishing site is created sucessfully.