Translate

Saturday, September 15, 2012

Using SPFarm in SharePoint

Using SPFarm in SharePoint

How to use SPFarm

SPFarm is the top level object in SharePoint for any SharePoint installation involves the Farm configuration this is the main object through it is possible to identify collection of server running in the current SharePoint Farm

The sample demo shows how to access the SPFarm Object using SharePoint Object Model
The following sample demonstrate how we can iterate through the farm.Servers that is servers collection
And adding these information in two dictionaries

Code:

           SPFarm farm = SPFarm.Local;
            Dictionary<string, string> serversNames = new Dictionary<string, string>();
            Dictionary<string, string> serversAddress = new Dictionary<string, string>();
            int counter = 0;
            foreach (SPServer server in farm.Servers)
            {
                serversNames.Add("Server Name : " + counter, server.Name);
                serversAddress.Add("Address of Server: " + counter, server.Address);
                counter++;
            }

Sunday, September 9, 2012

Fantastic 40 templates sharepoint 2010

Fantastic 40 templates sharepoint 2010


http://www.wssdemo.com/application/default.aspx

In C # Managing the Lifetime of Objects and Controlling Resources

In C # Managing the Lifetime of Objects and Controlling Resources

Garbage Collector

It is found that all the applications which we create use some resources.The resources fall into two broad categories:
1.managed resources that are handled by the common language runtime (CLR)
2.unmanaged resources that are maintained by the operating system outside the scope of the CLR.

A managed resource is typically an object based on a class defined by using a managed
language, such asC#.

Unmanaged resources include items implemented outside the Microsoft .NET Framework, which include such as Component Object Model (COM) components, file handles, database connections, and network
connections.
Managing resources is important in any applications development,that you develop.
Microsoft has provided “GC” which is called “Garbage Collector “ it facilities  by automatically reclaiming the resources by a managed object when it is no longer referenced by an applica
tion.Managed resources are handled by the .NET Framework garbage collector.However, unmanaged resources are not controlled by the garbage collector; it must take special steps to dispose of them properly and prevent them from being held longer than necessary.


Object life Cycle




An object has several distinct stages in its life cycle, which starts at creation and
ends in destruction. Creating an object is very simple; the new keyword to instantiate the new object. However, the process that you use to create an object is not really this simple. When we create a
new object, It follows the following steps:

Steps
1. A big block of memory will be allocated to hold the object.

2. The object is initialized. The block of memory is converted to an object.
The runtime handles the allocation of memory for managed objects.

Destroying an Object

When you have finished with an object, it can be destroyed.
We use destruction to reclaim any resources used by that object. Like creation,
destruction is a two-phase process:

1. The object is cleaned up; for example, by releasing any unmanaged resources
used by the application, such as file handles and database connections.

2. The memory used by the object is reclaimed.You can control only the first of these steps—cleaning up the object and releasing resources by implementing a destructor.
The CLR handles the release of memory used by managed objects

Using IDisposable Interface

The IDisposable interface defines a single method called Dispose, which takes do not take any
parameters. The Dispose method should release all of the unmanaged resources that an object owns. It should also release all resources owned by its base types by calling the Dispose method of the parent type.Visual C# includes constructs that ensure that resources are released in a timely
fashion for classes that implement the IDisposable interface.


Sample Demo

class Employee : IDisposable
{
bool isDisposed = false;
string name;
public Employee(string Name)
{
name = Name;
}
public void PaySalary()
{
if (!isDisposed)
{
Console.WriteLine("Employee {0} paid.", name);
}
else
{
throw new ObjectDisposedException("Employee already
disposed.");
}
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool IsDisposing)
{
if (IsDisposing)
{
isDisposed = true;
Console.WriteLine("Employee object disposed.");
}
GC.SuppressFinalize(this);
}
}

Create WCF Service and Host in SharePoint

Create WCF Service and Host in SharePoint

Creating a custom SharePoint WCF Service

There are situations where SharePoint could be acting as a data store providing your business data
to external applications or any web service or any components. These applications requesting data may need to provide information  on having a valid subscription or license before accessing the data. The out-of-the-box web services will not provide you a way to verify this information before allowing access. There may also be a scenario where you may want to strip out confidential information from the list
before passing the data to these external applications. In these scenarios, you can create
your own custom web service which could validate the credentials, or strip out the confidential
data before passing the information to these external applications.


In this example, we will create a custom SharePoint WCF service which returns us the string.This service is 
being host in _layout\_vti_bin directory in internet manager IIS.

Steps to Create a WCF Service:


In order to create a custom SharePoint WCF service,follow the following steps:

1. Open Visual Studio 2010 and create an empty SharePoint project.


2. Name the project CustomWCF. Deploy the solution as the farm solution.
3. Add a SharePoint mapped folder for ISAPI. In this folder, create a folder
named CustomWCF.
4. Add an empty text file named CustomWCF.svc to the CustomWCF folder
underneath ISAPI.
5. Add a new item to the project and select the WCF Service template in the Visual
Studio:
6. This will add three files to your project namely: CustomWCF.cs, ICustomWCF.cs,
and app.config.
7. Move the app.config file from the root folder to the ISAPI\CustomWCF folder in
the project and rename it web.config.
8. Build your project.
9. Open the Visual Studio command prompt and navigate to the bin\debug
directory of your project and execute the following command to get the public
key token of the assembly:
Sn –T CustomWCF.dll
10. Add the following line to the CustomWCF.svc file and add the public key token
obtained from the previous step:
<%@ ServiceHost Debug="true" Language="C#" Service="CustomWCF.
CustomWCF, CustomWCF, Version=1.0.0.0, Culture=neutral, PublicKeyT
oken=2832c7898c525539" CodeBehind="CustomWCF.cs" %>
11. The default DoWork method the Visual Studio added to ICustomWCF.cs returns string
12. Make the same change in the CustomWCF.cs file as well. This is the file where
the interface is implemented. Add the following line of code as shown in the

sample code
public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

13. Add the AspNetComaptibility attribute to the class that is implementing the
interface. So your CustomWCF.cs
class should look as follows:
using System.ServiceModel.Activation;
namespace CustomWCF
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Required)]
    public class CustomWCF : ICustomWCF
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}
14. Build and deploy the application. You should now be able to access this WCF service
from the browser by typing in the URL: http://servername/_vti_bin/
CustomWCF/CustomWCF.svc.

15. Screenshot similar to the following







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.