Archive for March 22, 2010

Sharepoint WebPart Lifecycle Events

This post describes the lifecycle events of a Sharepoint Connectable WebPart wih a single ViewState backed property;

On Page Load

  • Constructor
  • OnInit
  • OnLoad
  • ConnectionConsumer method is called if web part is connectable (sets the connection providers interface in the webpart)
  • CreateChildControls
  • OnPreRender (if your web part is connectable you would typically call the connection provider here to retrieve data)
  • SaveViewState
  • Render
  • RenderChildren
  • RenderContents

On 1st Postback
(PostBack click handler sets ViewState via public Property)

  • Constructor
  • OnInit
  • CreateChildControls
  • OnLoad
  • PostBack click handling
  • ConnectionConsumer method is called if web part is connectable (sets the connection providers interface in the webpart)
  • OnPreRender (if your web part is connectable you would typically call the connection provider here to retrieve data)
  • SaveViewState
  • Render
  • RenderChildren
  • RenderContents

On 2nd Postback

(PostBack click handler sets ViewState via public Property)

  • Constructor
  • OnInit
  • LoadViewState
  • CreateChildControls
  • OnLoad
  • PostBack click handling
  • ConnectionConsumer method is called if web part is connectable (sets the connection providers interface in the webpart)
  • OnPreRender (if your web part is connectable you would typically call the connection provider here to retrieve data)
  • SaveViewState
  • Render
  • RenderChildren
  • RenderContents

Note that during the 2nd postback, LoadViewState, is called, since in the 1st postback the click handler sets the value of the ViewState backed public property.

How to: Handle an Event using .NET in MOSS 2007

This example shows how to add a simple event handler that prevents items from being deleted from a list. Two procedures are involved in this task:
* Creating an event handler in Microsoft Visual Studio
* Adding the event handler as a Feature in Windows SharePoint Services

To create the event handler in Visual Studio
1. Create a new project in Visual Studio by clicking File, pointing to New, and then clicking Project.
2. In the New Project dialog box, select Visual C# in the Project types box, select Class Library in the Templates box, type DeletingEventHandler in the Name box, and then click OK.
3. In Solution Explorer, select DeletingEventHandler, and click Add Reference on the Project menu.
4. In the Add Reference dialog box, select Microsoft.SharePoint on the .NET tab and then click OK.
5. In the Code Editor, import the Microsoft.SharePoint namespace as follows.

using Microsoft.SharePoint;

6. Change the name of the class to DeletingAction and make it inherit from the SPItemEventReceiver class, as follows.

public class DeletingAction : SPItemEventReceiver

7. Add the following code within the class to override the ItemDeleting method in C#

  1. public override void ItemDeleting(SPItemEventProperties properties) 
  2.     properties.Cancel = true
  3.     properties.ErrorMessage = “Deleting items from “ + properties.RelativeWebUrl + ” is not supported.”

8. In Solution Explorer, right-click the DeletingEventHandler node, and then click Properties.
9. In the Properties dialog box, click the Signing tab, select Sign the asembly, select Choose a strong name key file, and then click .
10. In the Create Strong Name Key dialog box, type DeletingEventHandler.snk in the Key file name box, optionally specify a password for the key, and then click OK.
11. To build the project, click Build Solution on the Build menu, or press CTRL+SHIFT+B.
12. Find the \DeletingEventHandler\bin\Debug folder in the Visual Studio Projects folder, and drag the DeletingEventHandler.dll file to Local_Drive:\WINDOWS\assembly to place the DLL in the global assembly cache.

To add the event handler as a Windows SharePoint Services Feature

1. Create a folder in Local_Drive:/Program Files/Common Files/Microsoft Shared/web server extensions/12/TEMPLATE/FEATURES called DeletingEventHandler.
2. Create a Feature.xml Files file in this folder like the following that identifies the Feature and its element manifest file and sets the Feature scope to Web site.
Xml

  1. “Web”  
  2.    Title=“Deleting Event Handler”  
  3.    Id=“GUID”  
  4.    xmlns=“http://schemas.microsoft.com/sharepoint/”
  5.     
  6.       “Elements.xml”/> 
  7.     
  8.  

3. To replace the GUID placeholder in the previous Id attribute, generate a GUID by running guidgen.exe located in Local_Drive:\Program Files\Microsoft Visual Studio 8.
4. Create an Elements.xml file in the DeletingEventHandler folder that identifies the assembly, class, and method to implement as the event handler. This example applies the event handler to all announcements lists of a site, as specified by the ListTemplateId attribute. For the IDs of other default Windows SharePoint Services list template types, see the Type attribute description of the ListTemplate element.
Xml

  1. “http://schemas.microsoft.com/sharepoint/”
  2.    “104”
  3.        
  4.          DeletingEventHandler 
  5.          ItemDeleting 
  6.          10000 
  7.          DeletingEventHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a26b5449ac4a4cf3 
  8.          DeletingEventHandler.DeletingAction 
  9.           
  10.           
  11.        
  12.     
  13.  

5. To get the Public Key Token of the assembly, in Windows Explorer find the DeletingEventHandler.dll file in the Local_Drive:\WINDOWS\assembly, right-click the file, click Properties, and on the General tab of the Properties dialog box, select and copy the token.
6. At a command prompt, navigate to \Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN on the local drive, and type each of the following commands to install the Feature in the deployment, activate the Feature on a specified subsite, and reset Microsoft Internet Information Services (IIS) so that the changes take effect:

stsadm -o installfeature -filename DeletingEventHandler\Feature.xml

stsadm -o activatefeature -filename DeletingEventHandler\Feature.xml -url http://Server/Site/Subsite

iisreset

7. Try to delete an item in an announcements list on the specified Web site to see the effects of the event handler Feature.

MVVM Compared To MVC and MVPVP


MVVM Compared To MVC and MVP

 

image

MVC – Model View Controller

Let’s look at MVC first. You’ll notice a few things about the diagram:

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.

There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.

Note the one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.

The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP – Model View Presenter

Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:

The input begins with the View, not the Presenter.

There is a one-to-one mapping between the View and the associated Presenter.

The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.

The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.

MVVM – Model View View Model

So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:

The input begins with the View, not the View Model.

While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View *could* share the same View Model. However, my own feeling is that this is a bad practice and creates Franken-ViewModels that have too many responsibilities. It’s better to keep it as a one-to-one mapping instead.

You’ll also notice that the View has no idea about the Model in the MVVM pattern. This is because, as far as the View knows, its “Model” IS the View Model (hence its name). Because of how data-binding and other features like commanding work in WPF and Silverlight, there is rich communication between the View and View Model, isolating the View from having to know anything about what’s really happening behind the scenes.

Model View Presenter (MVP) pattern


Model View Presenter (MVP) pattern


Introduction

MVP pattern is a type of UI design pattern which enables decoupling of the UI logic without UI representation and by that enables treating code base without consideration on presentation technology used.

One of the commonly stated advantages of this approach is that it enables writing of appropriate test scripts to test UI part of application. MVP enables that without the need of using third party tools which scripts user UI actions and which are fairly easy to use for testing simple actions like button click, but to write a user UI scripts for data manipulation of a grid or some more complex layout. All the logic is inside the presenter and the presenter is talking to view only through the interface, so any mock object could be used for testing as long it implements the view interface

Second advantage is the fact that by decoupling code in presenter level we are enabling reuse of the code logic to totally different presentation technologies. For the example, the same presenter can be used without any problem in both Web Form and Win Form worlds, as long as they implement agreed interface

Third advantage is in the fact that in big companies (like the one I’m working in) to implement your supportive UI code, you are often forced to wait on UX (user experience) people to make the web forms and that sometimes is a very long period. Also the way of communication between products, tech leads and developers is quite often based on some word document based FRD which (from developer perspective) is not the most precise way of specifying requirements. MVP is allowing the tech leads to crystallize results of an FRD to a set of interface definition of a view and that interface could be immediate base for developers to start coding , without waiting for anyone knowing very precise what are the requirements. (Who said TDD? 🙂 )

Illustration 1. Logical view of the MVP pattern.

 

Short diagram description

View is responsible for visual representation of the form and it contains a presenter in private field. View is implementing interface whose members are approximated and technology striped UI elements of the view. When some event occurs on view is just forwarding it to presenter and it is presenter responsibility to handle the event. Presenter is manipulating view by talking to interface representation of the view. Presenter should never reference directly view members (UI controls). Presenter for his logic operations is using Model which can be persisted state or representation of the object which provides necessary functionality

Implementation procedure:

Create a view by using standard Visual Studio IDE tools.

For my example I will create first a web form with:

    • a label on top which would show possible validation error
    • Last name, first name, address and a city text boxes
    • Search text box with a button

    Illustration 2. UI look of the view made by web form

    Interface would be created in a separate project called presenter so we could reuse it later to demonstrate usage outside of our web application. Web application should have a reference to the presenter project

    Illustration 3. Project structure  – separating and referencing presenter

    Create a interface as an abstract form of a view with setters only for text boxes (because presenter would fill == set them) and getter property only for searcher (presenter would take that value and perform a search)

    Illustration 4. View interface definition

    namespace Presenter

    {

        public interface IUserView

        {

            string FirstName { set;}

            string LastName { set;}

            string Address { set;}

            string City { set;}

            string ErrorMessage { set;}

            string SearchCriteria { get;}

        }

    }

    After creation of interface we are implementing it on view by setting and getting UI element values in the property

    Illustration 5. View interface implementation

        #region IUserView Members

        public string FirstName

        {

            set { firstName.Text = value; }

        }

        public string LastName

        {

            set { lastName.Text = value; }

        }

        public string Address

        {

            set { address.Text = value; }

        }

        public string City

        {

            set { city.Text = value; }

        }

        public string ErrorMessage

        {

            set

            {

                errorMessageLabel.Text = value;

                errorMessageLabel.Visible = value != “”;

            }

        }

        public string SearchCriteria

        {

            get { return searchCriteria.Text; }

        }

        #endregion


    Creation of presenter class includes creation of a private field of view interface type and overloading of a constructor to accept that view interface

    Illustration 6. Presenter  wiring the view

     namespace Presenter

    {

        public class UserViewPresenter

        {

            IUserView _view;

            /// 

            /// Initializes a new instance of the UserViewPresenter class.

            /// 

            /// 

            public UserViewPresenter(IUserView view)

            {

                _view = view;

                SetCustomerData();

            }

    Presenter would have to implement business logic, which In our example is finding of a customer for a given code. I’ve created Customer.xml file as D:\Customer.XML

    Illustration 7. Exampled data used for sample 

     

    Presenter would implement therefore a method named SetCustomerData which task is to find a customer of a given code and update the view with resulting data. In case the entered code is not a valid number presenter would show appropriate message on validator that there is a syntax error. In case there are no contacts with a given code presenter should empty view and show a message that not existing code has been entered.

    Illustration 8. Implementation of a presenter logic 

    public void SetCustomerData()

    {

    int searchCode;

          bool isValid = int.TryParse

                (_view.SearchCriteria, out searchCode);

    if (isValid)

          {

                using (DataSet ds = new DataSet())

                {

                      string filePath=string.Format(

    “{0}Customers.xml”,

    AppDomain.CurrentDomain.BaseDirectory                  

                      );

    ds.ReadXml(filePath);

                      ds.Tables[0].PrimaryKey

                            = new DataColumn[]

    {ds.Tables[0].Columns[“Code”]};

                            DataRow dr=

                                ds.Tables[0].Rows.Find

                                (_view.SearchCriteria);

    if (dr != null)

                      {

                            _view.FirstName

                               = dr[“FirstName”].ToString();

                            _view.LastName

                               = dr[“LastName”].ToString();

                            _view.Address

                               = dr[“Address”].ToString();

                            _view.City

                               = dr[“City”].ToString();

                            _view.ErrorMessage

                               = “”;

    }

                      else

                      {

                            _view.FirstName = _view.LastName

                                = _view.Address = _view.City = “”;

                            _view.ErrorMessage

                                = “Contact not existing”;

    }

    }

    }

          else

          {

                _view.FirstName = _view.LastName =

                _view.Address = _view.City = “”;

                _view.ErrorMessage = “Not a valid code!!!”;

    }

    }

    Presenter would implement therefore a method named SetCustomerData which task is to find a customer of a given code and update the view with resulting data. In case the entered code is not a valid number presenter would show appropriate message on validator that there is a syntax error. In case there are no contacts with a given code presenter should empty view and show a message that not existing code has been entered.

    Illustration 9. Results of an example – Code 1 entered – user shown 

    Illustration 10. Results of an example – Non existing valid code entered

     

    Illustration 11. Results of an example – Invalid code entered

    Now I will show reuse of the presenter for implementing the same logic in totally different technology: WinForm

    I’ll slightly change the look by switching the places between search criteria and the error message and city would be presented now by ComboList

    Illustration 12. UI look of the view made by windows form

    Usage of MVP patterns allows me just to implement view interface to win form and to view up presenter by passing to its constructor WinForm and all the same functionality is present without touching a presenter. That’s why the presenter is speaking to interface which shouldn’t be technology specific

    Illustration 13. Wiring up the win form view to the presenter

    using System.Windows.Forms;

    using Presenter;

    namespace WinForm

    {

        public partial class UserViewForm : Form, IUserView

        {

            private UserViewPresenter _presenter;

            public UserViewForm()

            {

                InitializeComponent();

                _presenter = new UserViewPresenter(this);

                _presenter.SetCustomerData();

            }

          

            private void searchButton_Click(object sender, System.EventArgs e)

            {

                _presenter.SetCustomerData();

            }

            #region IUserView Implementation

                      // The same implementation like in WebForm case

                      // Wire up the control text properties to interface members

            #endregion

        }

    }

     

    So the complete solution would be something like:

    Illustration 13. Complete project tree

    And the result is the same functionality encapsulated in presenter is been reused for a win form

    Illustration 14. Results of an example in win form – Existing code entered

    Illustration 15. Results of an example in win form – Non existing code entered

    Illustration 16. Results of an example in win form – Invalid code entered

    Conclusion

    MVP is very powerful UI design pattern which has multiple benefits for developing all kinds of user interfaces. That is the reason why CAB (Composite Application Block) is using it as a one of basic UI building principles

    Abstract Factory Design Pattern Implementation in C#

     
    Abstract Factory Design Pattern Implementation in C#

    Context

    An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.

    Sometimes one wants to construct an instance of one of a suite of classes, deciding between the classes at the time of instantiation. In order to avoid duplicating the decision making everywhere an instance is created, we need a mechanism for creating instances of related classes without necessarily knowing which will be instantiated.

    Solution

    Create an Abstract Factory class to answer instances of concrete classes (usually subclasses). The class of the resultant instance is unknown to the client of the Abstract Factory.

    There are two types of Abstract Factory:

    • Simple Abstract Factory is an abstract class defining Factory methods to answer instances of concrete subclasses. The choice of which subclass to instantiate is completely defined by which method is used, and is unknown to the client.
    • The second form of Abstract Factory is an abstract class defining a common protocol of Factory methods. Concrete subclasses of the abstract factory implement this protocol to answer instances of the appropriate suite of classes.

    See below for an example, both VB.NET and C# implementation

    Applicability

    • Need to abstract from details of implementation of products -The system shall be independent of how its constituent pieces are created, composed, and represented.
    • Need to have multiple families of products – The system shall be configured with one of multiple families of products.
    • Need to enforce families of products that must be used together – A family of related product objects is designed to be used together, and you need to enforce this constraint.
    • Need to hide product implementations and just present interfaces – You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

    Characteristics

    • An abstract factory is an object maker.
    • It typically can produce more than one type of object.
    • Each object that it produces is known to the receiver of the created object only by that object’s interface, not by the object’s actual concrete implementation.
    • The different types of objects that the abstract factory can produce are related — they are from a common family
    • An abstract factory isolates concrete classes
    • It makes exchanging product families easy
    • It promotes consistency among products
    • It supports adding new kinds of products and their families.

    Example

    The Example here has an implementation of an Abstract Factory as an Interface IAVDevice that has methods that can create an Audio object and a Video object.

    The client Codes against IAVDevice and gets IAudio and IVideo interfaces.

    Passing “cd” in the command line creates a family of cd objects (Audio and Video) and “dvd” creates a family of dvd objects (Audio and Video).

    The client doesn’t care which object (cd audio video or dvd audio video), IAVDevice interface returns as it codes against IAudio and IVideo interface.

    C# Implementation

    To run the example from console first make the exe and then run it by using

    csc /out:AbstractFactory.exe AbstractFactory.cs  //Creates AbstractFactory
    AbstractFactory cd                               //CD Family
    AbstractFactory dvd                              //DVD Family

    using System;

    public interface IAVDevice
    {
        IAudio GetAudio();
        IVideo GetVideo();
    }

    public interface IVideo
    {
        string GetPictureQuality();
    }

    public interface IAudio
    {
        string GetSoundQuality();
    }

    class CCd:IAVDevice
    {
        public IAudio GetAudio()
        {
            return new CCdAudio();
        }
        public IVideo GetVideo()
        {
            return new CCdVideo();
        }
    }

    class CDvd:IAVDevice
    {
        public IAudio GetAudio()
        {
             return new CDvdAudio();
        }
        public IVideo GetVideo()
        {
            return new CDvdVideo();
        }
    }

    class CCdAudio:IAudio
    {
        public string GetSoundQuality()
        {
            return "CD Audio is better then DVD Audio";
        }
    }

    class CCdVideo:IVideo
    {
        public string GetPictureQuality()
        {
            return "CD video quality is not as good as DVD";
        }
    }

    class CDvdAudio:IAudio
    {
        public string GetSoundQuality()
        {
             return  "DVD Audio is not as good as CD Audio";
        }
    }

    class CDvdVideo:IVideo
    {
        public string GetPictureQuality()
        {
            return "DVD video quality is better then CD";
        }
    }

    class CAVMaker
    {
        public IAVDevice AVMake(string xWhat)
        {
            switch (xWhat.ToLower())
            {
                case "cd"":
                    return new CCd();
                case "dvd"":
                     return new CDvd();
                default:
                    return new CCd();            
            }
        }
    }

    public class AbstractFactory
    {
        static void Main(string[] args)
        {
            CAVMaker objFactMaker = new CAVMaker();
            IAVDevice objFact;
            IAudio objAudio;
            IVideo objVideo;
            string strWhat;
            strWhat = args[0];
            objFact = objFactMaker.AVMake(strWhat);
            objAudio = objFact.GetAudio();
            objVideo = objFact.GetVideo();
            Console.WriteLine(objAudio.GetSoundQuality());
            Console.WriteLine(objVideo.GetPictureQuality());
        }
    }

    HOW TO:Forms Based Authentication (FBA) on SharePoint 2010


    ** Note: This FBA configuration method is based upon the pre-release version of SharePoint 2010 and may change in the final release **

    The following article details FBA configuration on a SharePoint 2010 site. If you are looking for information regarding the configuration of FBA on a SharePoint 2007 / WSS 3.0 site, check out this article instead.

    Setup your SharePoint 2010 site

    1. In Central Admin, create a new site. By default, this will use Windows Authentication. Since we haven’t setup FBA yet, we need to setup the Web Application first as a Windows site.
    2. Create the Web Application
    3. Create a default Site Collection, and make a windows user (below we’ve used the Administrator account) a Site Administrator.

    Setup your User Database

    1. Setup the ASP.NET Membership Database. Note: You can use custom membership stores, DotNetNuke, even Live! credentials. But the .NET membership database is very simple to setup. This requires the SQL Server database. You can use the integrated version that is supplied with SharePoint, Express or a fully featured SQL Server (Standard or Enterprise) Edition.
    2. Find the setup file aspnet_regsql.exe located at either of the following locations depending upon your OS:
      %windir%\Microsoft.NET\Framework\v2.0.5027
      %windir%\Microsoft.NET\Framework64\v2.0.5027
    3. When the ASP.NET SQL Server Setup Wizard appears, select “Configure SQL Server for application services”, then click Next
    4. Enter the SQL Server and Database name.
      sqldb
    5. Above, I have named the database FBADB
    6. Click Next and Finish

    Provide Access to the Membership Database

    As an administrator, you’ll be able to add and modify user accounts. But from the SharePoint runtime, we’ll have to provide access to the membership store. This can be done in two ways. If using SSPI (Integrated Security) for the connectionstring from SharePoint, you’ll need to determine the Service Account that runs the Application Pool. Then you’ll provide access to this windows (or service) account in SQL Server to the FBADB database. Or, if you don’t want to use SSPI, or don’t want to take the time to figure out the startup service account for SharePoint you can simply create a login to the FBADBdatabase. Following are steps for the second approach.

    1. Open SQL Server Management Studio (SSMS 2008) and select Security , then Logins
    2. Right Click Logins and Select “New Login”
    3. Create a SQL Server account. Below, we’d created the account FBAService with password pw
      sqluser2
    4. Select “User Mapping”
    5. Mark the checkbox next to FBADB, and select the row.
    6. In “Database role membership”, make the user a dbo_owner.
      rolemember
    7. Click OK to save the new user.

    Setup IIS 7.0 Defaults

    1. Open up Internet Information Services Manager
    2. Select the Web Server, then double click Connection Strings
      Cstring
    3. Click Add..
    4. Enter the Server (.), Database (FBADB) and the Credentials for the user FBAService (by clicking the Set button). If you want to use SSPI, simpy select “Use Windows Integrated Security” instead.
      cstring2
    5. Click OK to save
    6. Click to Select the Server from the Connections pane again, and double click Providers.
    7. On the Feature dropdown, select .NET Users. Your machine may take a while to respond while the configuration is read.
    8. On the Actions menu, click Add..
    9. On the Add Provider form, select SqlMembershipProvider as the Type
    10. Provide a name: FBA.
    11. Drop down ConnectionStringName and select FBADB
    12. Set any other parameters you’d like. I set some Password related options for user interaction later.
      provider
    13. Click OK to save
    14. From the Feature dropdown, select .NET Roles, then click Add..
    15. Provide a name: FBARole, and select Type: SqlRoleProvider
    16. Select the ConnectionStringName: FBADB
      roleprovider
    17. Click OK to save the .NET role.

    Setup the FBA Zone in SharePoint 2010

    1. Browse to SharePoint 4.0 Central Administration, Select Security
      centraladmin
    2. In Application Security, select Specify Authentication Providers
      specificauthent
    3. Select the Web Application.
    4. Click the Default Zone.
      defaultzone
    5. Ensure the Web Application is the correct one on the next page!
    6. Change Authentication Type to Forms
    7. Check Enable Anonymous (* note that this does not immediately enable Anonymous access; it merely makes the option available on the front-end web application *
      zone1
      zone2

    1. Click Save.
    2. When the process is finished, the membership provider should now display FBA.

    What SharePoint has done behind the scenes is make the necessary changes to the IIS website to support Forms based authentication. But we still have a little problem. If we browse to the site right now, we won’t be prompted for Windows credentials anymore. Not only do we NOT have a user in the .NET membership database, but we have no FBA based administrators. Let’s tackle that next.

    IIS 7.0 Web Site Configuration for SharePoint 2010 FBA

    1. In IIS Manager, select the SharePoint site. In this example, we used the default site (80).
    2. Double click the .NET Users icon
    3. Click Set Default Provider from the actions pane on the left and select FBA
      dftuser
    4. Click OK to save.
    5. While we’re here, let’s add our first user. This will be used as an administrative account on the FBA site. Click Add..
      newuser
    6. Select a User, Email and Password. Depending upon parameters you defined earlier you may be prompted with challenge/response questions.
      ** The password may require some strength by default. If you receive an error message that states the “password is invalid”, simply add a number or non-alpha character.
    7. Next, select the SharePoint Central Administation v4 web site from the connections menu in IIS.
    8. Click .Net Users, then in the Actions menu select “Set Default Provider” and set that to FBA.

    Set the User as Site Administrator on the SharePoint 2010 Web Site

    1. In SharePoint Central Admin v4, go to Application Management
    2. In the Site Collections section, select “Change Site Collection Administrators
      siteadmins
    3. On the next page, select the Site Collection we’ve been using.
    4. You’ll note that the primary site collection administrator has a little red squiggly. Why? We don’t have Windows Authentication enabled for this site and therefore no way to resolve. Delete the Administator account.
    5. In the field type the user created above (we used fbaadmin), then click the Check Names button. You should see a black underline noting that the name was resolved.
      fbaadmin

     

    Test the site

    1. In a Web Browser, when you access the site http://localhost (if that’s what you used), you’ll be presented with the SharePoint login screen, not a Windows login pop-up. (Wow, and you thought SharePoint 2007 had a spartan login screen. Get a load of this !)
      login
    2. Login with the fbaadmin credentials and you should be able to access the site.
      homepage2

     

    Add the reference to the user friendly people picker

    You know the picker…so you can easily find those needles in the haystack. For that to work in Central Admin and this site against your .NET membership database, you need to add a reference to the provider.

    1. In IIS Manager, browse to the Central Admin web application. Explore the folder and find the web.config file. Open in Notepad.
    2. Find the node and use the following:

     




     

    Final Note

    If you plan to use the same membership database for multiple sharepoint sites AND you choose to encrypt the passwords, you’ll need to add one final step. In IIS 7,  on the first site, select the Machine Keys icon. Copy those keys. In the next site that you create, you’ll need to use the same machine keys and disable “Automtically Generate” and disable “Generate Unique Key”. This is crucial as the machine key is used to determine the encrypted password that is passed back to the .NET membership database.

    Enable Forms Based Authentication (FBA) for SharePoint 3.0 on IIS 7


    Forms Based Authentication

    There are several reasons to use FBA for SharePoint. For one, your external users might not exist in the Windows AD, might have no reason to be included or perhaps you’d like to enable anonymous access to certain resources of your SharePoint site. Not that if you only use the SQL Server to provide FBA authentication of users, there is no need to hold Windows CALs.

    Setup your SharePoint site

    1. In Central Admin, we created a site on port 500. 500 will be the future FBA site and 501 will be the Windows site.
    2. Since we haven’t setup FBA yet, we need to setup the Web Application first as a Windows site.
    3. Create the Web Application
    4. Create a default Site Collection, and make a windows user (below we’ve used the Administrator account) a Site Administrator.
      sitecol

    Setup your User Database

    1. Setup the ASP.NET Membership Database. Note: You can use custom membership stores, DotNetNuke, even Live! credentials. But the .NET membership database is very simple to setup. This requires the SQL Server database. You can use the integrated version that is supplied with SharePoint, Express or a fully featured SQL Server (Standard or Enterprise) Edition.
    2. Find the setup file aspnet_regsql.exe located at either of the following locations depending upon your OS:
      %windir%\Microsoft.NET\Framework\v2.0.5027
      %windir%\Microsoft.NET\Framework64\v2.0.5027
    3. When the ASP.NET SQL Server Setup Wizard appears, select “Configure SQL Server for application services”, then click Next
    4. Enter the SQL Server and Database name.
      aspnetsetup
    5. Above, I have named the database FBADB
    6. Click Next and Finish

    Provide Access to the Membership Database

    As an administrator, you’ll be able to add and modify user accounts. But from the SharePoint runtime, we’ll have to provide access to the membership store. This can be done in two ways. If using SSPI (Integrated Security) for the connectionstring from SharePoint, you’ll need to determine the Service Account that runs the Application Pool. Then you’ll provide access to this windows (or service) account in SQL Server to the FBADB database. Or, if you don’t want to use SSPI, or don’t want to take the time to figure out the startup service account for SharePoint you can simply create a login to the FBADBdatabase. Following are steps for the second approach.

    1. Open SQL Server Management Studio (SSMS 2008) and select Security , then Logins
    2. Right Click Logins and Select “New Login”
    3. Create a SQL Server account. Below, we’d created the account FBAService with password pw
      sqluser2
    4. Select “User Mapping”
    5. Mark the checkbox next to FBADB, and select the row.
    6. In “Database role membership”, make the user a dbo_owner.
      rolemember
    7. Click OK to save the new user.

    Setup IIS 7.0 Defaults

    1. Open up Internet Information Services Manager
    2. Select the Web Server, then double click Connection Strings
      Cstring
    3. Click Add..
    4. Enter the Server (.), Database (FBADB) and the Credentials for the user FBAService (by clicking the Set button). If you want to use SSPI, simpy select “Use Windows Integrated Security” instead.
      cstring2
    5. Click OK to save
    6. Click to Select the Server from the Connections pane again, and double click Providers.
    7. On the Feature dropdown, select .NET Users. Your machine may take a while to respond while the configuration is read.
    8. On the Actions menu, click Add..
    9. On the Add Provider form, select SqlMembershipProvider as the Type
    10. Provide a name: FBA.
    11. Drop down ConnectionStringName and select FBADB
    12. Set any other parameters you’d like. I set some Password related options for user interaction later.
      provider
    13. Click OK to save
    14. From the Feature dropdown, select .NET Roles, then click Add..
    15. Provide a name: FBARole, and select Type: SqlRoleProvider
    16. Select the ConnectionStringName: FBADB
      roleprovider
    17. Click OK to save the .NET role.

    Last Prep – Install the CKS FBA Solution

    As you’ll see later, we can administer users in IIS 7.0 in a very rudimentary fashion. By using the Community Kit for SharePoint, available on CodePlex, you’ll be able to maintain users from within the SharePoint site as well as providing some self-service user control (password reset, etc.)

    1. Download the bits from here. (* Disclaimer: It’s codeplex, and it’s beta *)
    2. After unpacking, deploy via commandline with the following syntax to your web application:
      deploy [site]
      ex
      : c:\temp\deploy http://scdev01:400

    Setup the FBA Zone in SharePoint

    1. Browse to SharePoint Central Admin, Select Application Management
    2. In Application Security, select Authentication Providers
    3. Select the Web Application.
    4. Click the Default Zone.
      defaltzone
    5. Ensure the Web Application is the correct one on the next page!
    6. Change Authentication Type to Forms
    7. Check Enable Anonymous (* note that this does not immediately enable Anonymous access; it merely makes the option available on the front-end web application *)
      fbasetup
    8. Click Save.
    9. When the process is finished, the membership provider should now display FBA.

    What SharePoint has done behind the scenes is make the necessary changes to the IIS website to support Forms based authentication. But we still have a little problem. If we browse to the site right now, we won’t be prompted for Windows credentials anymore. Not only do we NOT have a user in the .NET membership database, but we have no FBA based administrators. Let’s tackle that next.

    IIS Web Site Configuration

    1. In IIS Manager, select the SharePoint site. Earlier we called it FBA Demo- FBA – 500
    2. Double click the .NET Users icon
    3. Click Set Default Provider and select FBA
      dftuser
    4. Click OK to save.
    5. While we’re here, let’s add our first user. This will be used as an administrative account on the FBA site. Click Add..
      newuser
    6. Select a User, Email and Password. Depending upon parameters you defined earlier you may be prompted with challenge/response questions.
      ** The password may require some strength by default. If you receive an error message that states the “password is invalid”, simply add a number or non-alpha character.
    7. Next, select the SharePoint Central Administation web site from the connections menu.
    8. Click .Net Users, then in the Actions menu select “Set Default Provider” and set that to FBA.

    Set the User as Site Administrator on the Web Site

    1. In SharePoint Central Admin, go to Application Management
    2. In SharePoint Site Management, select “Site Collection Administrators
    3. On the next page, select the Site Collection we’ve been using.
    4. You’ll note that the primary site collection administrator has a little red squiggly. Why? We don’t have Windows Authentication enabled for this site and therefore no way to resolve. Delete the Administator account.
    5. In the field type the user created above (we used fbaadmin), then click the Check Names button. You should see a black underline noting that the name was resolved.
      newsiteadmin

     

    Test the site

    1. In a Web Browser, when you access the site http://localhost:500 (if that’s what you used), you’ll be presented with the SharePoint login screen, not a Windows login pop-up.
      loginprompt
    2. Login with the fbaadmin credentials and you should be able to access the site.
      fbalogin

     

    Add the reference to the user friendly people picker

    You know the picker…so you can easily find those needles in the haystack. For that to work in Central Admin and this site against your .NET membership database, you need to add a reference to the provider.

    1. In IIS Manager, browse to the Central Admin web application. Explore the folder and find the web.config file. Open in Notepad.
    2. Find the node and use the following:

     




    User Management

    You could manage .NET users from within IIS 7.0, but it’s really rudimentary. Instead, I prefer the CKS solution that we installed earlier.
    fbamanage

    In the SharePoint site that has been converted to FBA, select Site Settings. You’ll notice some new options under Users and Permissions for FBA. FBA User Management is a simple utility to create and manage users from within the SharePoint site. For more information on what this feature has to offer, visit the CodePlex site that hosts the application.

    Final Note

    If you plan to use the same membership database for multiple sharepoint sites AND you choose to encrypt the passwords, you’ll need to add one final step. In IIS 7,  on the first site, select the Machine Keys icon. Copy those keys. In the next site that you create, you’ll need to use the same machine keys and disable “Automtically Generate” and disable “Generate Unique Key”. This is crucial as the machine key is used to determine the encrypted password that is passed back to the .NET membership database.

    In the next article, we’ll add a second zone to allow local Windows users to access the resources of this site.

    MVC vs. MVP vs. MVVM


    MVC vs. MVP vs. MVVM

    An important FAQ. The answer actually depends on where the person is coming from. MVC is a fundamental pattern which has been tweaked quite a bit to fit into various platforms. For instance if you had asked anybody how to implement an MVC in ASP.NET (prior to release of ASP.NET MVC framework) you would get very different answers. So let’s start with basic. The common motivation behind all 3 is separation of concerns, cutting flab from UI (good for UI designers), swapping UIs (for instance windows to web), make UI easy for Unit Testing, etc. Have a look at the below diagram, I have taken it from CAB documentation.

    MVCMVP

    MVC: Three components – View (your UI), Model (your business entities / data – that view is displaying) & Controller (contains the logic that alters the model depending on the action triggered by UI, typically implementing a Use Case). It’s widely known that MVC is a compound pattern (View and Controller have Strategy implementation, View itself can be a Composite implementation & View and Model are synched through Observer). In this case Controller doesn’t know anything about View, and the idea is that a View can switch Controllers (for instance depending upon who has logged to the system) & a single controller can be used by multiple Views. View subscribes to the changes done to the model & hence both are sync from the data perspective. One of the disadvantages of MVC is that it’s difficult to unit test. Controller manipulates the data but how about asserting those changes from a view perspective. For instance on click of a button you raise an event to controller, and controller modifies the value in model. This value modification changes the font size / color in View. Unit testing this scenario is slightly difficult in MVC.

    MVP: Again three components. But dependencies change (look at arrows in the diagram). Over here we replace Controller with Presenter (one which presents the changes done in model back to view). The main difference between both is that Presenter refers back to the view while Controller doesn’t. Normal pattern found here is to create an abstraction of the View (in terms of properties / events) & Presenter refers to it. This makes the mocking of View much easier & hence the Unit Testing aspect. Presenter here hence takes the responsibility of not only manipulating model but also updating the view. Of course the implementations of MVP differ in real world in terms of how much thin the view is, some prefer keeping basic logic still inside view & taking complex logic in presenter, while others prefer keeping the entire logic in Presenter. Martin fowler describes 2 variations on MVP on these lines namely – Supervising Controller & Passive View described below

    (A Passive View handles this by reducing the behavior of the UI components to the absolute minimum by using a controller that not just handles responses to user events, but also does all the updating of the view. This allows testing to be focused on the controller with little risk of problems in the view.

    Supervising Controller uses a controller both to handle input response but also to manipulate the view to handle more complex view logic. It leaves simple view behavior to the declarative system, intervening only when effects are needed that are beyond what can be achieved declaratively.)

    MVVM: Model–View-ViewModel talks of creating a new model (in addition to your domain model). This model normally adds additonal properties from the prespective of View (as we understand that View has controls in addition to data which it’s displaying). For instance if View had a property IsChecked and Presenter was setting in classic MVP, in MVVM Presenter will have that IsChecked Property which View will sync up with (doesn’t it look like Strategy pattern has been replaced with Observer?). So now a Presenter becomes more like a combo of – View Properties & Model properties which would be synchronized with View. So why not rename Presenter to ViewModel? Do that and you get MVVM. MVVM is attractive for platforms which support bi-directional binding with less effort. Also a minor tradeoff is ViewModel unlike Presenter can stand on its own (Presenter normally requires a View’s interface). Martin fowler describes similar pattern called Presentation Model & Josh Smith captures MVVM implementation for WPF / Silverlight in this article.

    MVVM

    ASP.NET MVC: So what has MVC got to do with ASP.NET MVC? First, Web works on a different model. Here, user interacts with HTML in browser and send a request back to the server for processing (for client side Ajax you might go just for data). As the interaction is normally stateless, when the request comes back to the server we need to recreate our View, load the model back & manipulate both of them as required. There are 2 variations on how handle this recreation – Page Controller & Front Controller. Make Page the decision maker – in this widely implemented pattern HTTP request is specific to physical page on server (.aspx for instance) & page in turn creates itself (builds the view from postback data) decides what model it needs and triggers the manipulation (events in codebehind file) it requires. As you see here the distinction between View & Controller becomes blur & is little difficult to separate. This where ASP.NET MVC comes in which behaves like a Front Controller – where Controller is the decision maker. Here all HTTP requests are mapped to methods on the Controller Class. Controller class recreates the model & view as required and does the manipulations. This makes unit testing easier as we can directly instantiate the front controller class & invoke methods on it to perform the assertions.

    A Tour of Windows Workflow Activities

    Windows Workflow Activities
     
     
    Out-of-the-Box Activities 
    Controlling Flow through Conditions 
    Loops and Repeated Activities 
    Synchronization Blocks 
    Exception Handling 
    Transactions 
    Calling Out Other Code 
    Summary
     

    Most enterprise applications contain business processes that developers and architects find natural to express through workflows. Ultimately, a workflow is a program that captures the interactions among real-world entities. The workflow waits for stimulus from the external world, and the arrival of that stimulus could take arbitrarily long periods of time.
    A pillar of the upcoming Microsoft® .NET Framework 3.0, Windows® Workflow Foundation provides the programming model and runtime engine for building workflow-enabled applications on a Windows platform equipped with the .NET Framework 2.0 or higher, running at least Windows XP Service Pack 2 (SP2) or Windows Server® 2003.
    Don Box and Dharma Shukla wrote a Windows Workflow Foundation primer in the January 2006 issue of MSDN®Magazine. In recent Cutting Edge columns (March 2006 and April 2006), I addressed a very common type of workflow application where the execution of the workflow is conditioned by human intervention (see June 2003 Cutting Edge column and June 2004 Cutting Edge column). From a software perspective, the need for a human operator mostly means asynchronous event handling, state persistence, and the availability of a shared server. Windows Workflow Foundation supports virtually any scenario where human operators are involved.
    Each workflow is a declarative program wherein each program statement is represented in terms of a component called an activity. One of the biggest myths about Windows Workflow Foundation is that all the constituent activities are linked either sequentially or by state-machine transition. In fact, Windows Workflow Foundation virtualizes the execution model in terms of an activity automata. This enables you to write composite activities which can capture any type of control flow pattern, ranging from fancy joins and merges to state machines to graphs to sequences to interleavings to non-local exits, and so on. In short, it allows you to model the control flow patterns that exist in the real world, through high-fidelity composite activities. However, Windows Workflow Foundation ships with built-in activities for only two patterns: sequential and state-machine workflows.
    A sequential workflow has clear starting and ending points and execution proceeds from start to finish, one step after the next, following one possible route. State-machine workflows are expressed as a set of states, each of which may contain activities and is triggered by an event. You define an initial and a completed state and execution proceeds from state to state following all defined transitions until the completed state is reached.
    As I mentioned, the building block of the workflow is the activity. Building such a workflow means combining activities to create the desired model for the problem to face. Windows Workflow Foundation comes with a large set of built-in activities, but it is also completely extensible through custom activities. Understanding goals and capabilities of the out-of-the-box activities is key to making full sense of the true potential of the platform. This column will provide a tour of the standard workflow activities you get when you install the Windows Workflow Foundation runtime and the Visual Studio® 2005 designer.

    Out-of-the-Box Activities
    Windows Workflow Foundation is part of the .NET Framework 3.0 (formerly code-named WinFX®). Even though it’s still a beta, I found the latest Community Technology Preview (CTP) to be very stable; a number of companies are extensively using it to develop applications. As a result, a number of tools and custom activities are already available and a useful support community is growing on newsgroups and forums such as wf.netfx3.com. If you have, or will soon have, some interest in workflow applications, be aware that it’s never too early to get properly acquainted.
    To find the latest download, go to Windows Workflow Foundation. Once it’s installed, start Visual Studio 2005, open a Visual Basic® or C# workflow project, and take a look at the contents of the toolbox. Depending on the type of project you select, it should look like one of the toolboxes inFigure 1.
    The contents of the toolbox are context-sensitive and change based on the type of workflow you select. In particular, the left-hand toolbox in Figure 1 also includes the state activities required when you create a state-machine workflow. The toolbox window on the right only includes activities for a sequential workflow. The set of predefined activities can be split into a few categories based on the goals and expected behavior. Figure 2 shows a possible categorization: control flow, execution, events, Web services, and state machines.

      Figure 2 Categories of Workflow Activities
    Flow Execution Events Web Services State
    IfElse TransactionScope EventDriven WebServiceInput SetState
    While Sequence Listen WebServiceOutput State
    CAG Compensate HandleExternalEvent WebServiceFault StateInitialization
    Policy SynchronizationScope EventHandlingScope InvokeWebService StateFinalization
    Replicator Code Delay    
    Throw Parallel      
    Suspend InvokeWorkflow      
    Terminate CallExternalMethod      
    FaultHandler CompensatableSequence      
      CompensatableTransactionScope      

    Figure 1 Workflow Activities in Toolbox (Click the image for a larger view)

    Control flow activities govern the sequence in which the graph activities execute. The list includes conditional blocks as well as constructs for implementing loops. Execution activities include constructs to terminate or suspend a workflow, throw an exception, execute internal or external code, or spawn another workflow. Most workflows need synchronization with the host environment—typically a Windows Forms or ASP.NET application. The activities in the events group let the workflow stop waiting for external events, handle received events, or just wait before proceeding with the next step. Finally, the Web services and state groups target two special features of a workflow—exposing the internal engine as a Web service and as a state machine. Let’s examine the key activities in the framework, proceeding by groups.

    Controlling Flow through Conditions
    When conditions are specified in a workflow, the runtime engine evaluates them and then acts based on the result. Two of the core condition-based activities are IfElse and Policy. The IfElse activity works like a classic If statement in a high-level programming language. It may contain any number of condition-based branches and also a default branch to fall into if no other condition is met. The Policy activity, instead, represents a collection of rules. In Windows Workflow Foundation, a rule consists of a condition and one or more resulting actions. Think of a rule as an If-Then-Else statement, where the condition corresponds to the Boolean guard of the If block, and the actions define the behavior of the Then and Else clauses. Let’s get to know more about each of these activities and then compare them.
    When added to a workflow, the IfElse activity looks like Figure 3. By default, it has two branches, and new branches can be added by right-clicking and selecting Add Branch from the context menu. When the runtime engine reaches an IfElse activity it begins evaluating the condition of the various branches proceeding from the left to right. The condition of each branch is determined and the first branch that evaluates to true is run. You can alter the evaluation order of the branches by moving branches around through the commands in the activity’s context menu. To enable a branch, you need to specify a valid condition. You specify a condition in either of two ways—through an expression or through a piece of code.
    Figure 3 IfElse Activity in Action (Click the image for a larger view)

    If you opt for an expression, set the branch in the designer and give a public home to the Condition entry in the Visual Studio 2005 Properties box. Next, expand the expression editor and enter an expression that touches on workflow members and evaluates to a Boolean value. For example, if the workflow class features a public property named MinimumLength you can set the condition as follows:

    this.MinimumLength >= 8 

    The editor shown in Figure 4 fully supports IntelliSense® and provides access to private and public members of the workflow. This means that you call out a Boolean function as well. Suppose you have a property declared like this:

    Public Property MinimumLength() As Integer
    Get
    Return _minLength
    End Get
    Set(ByVal value As Integer)
    _minLength = value
    End Set
    End Property

    Figure 4 Condition Editor for IfElse Activities (Click the image for a larger view)

    When you try to read the value of MinimumLength, the runtime ends up invoking the get accessor of the property, which returns the value of the private member _minLength. The final branch in an IfElse activity can lack a condition. In this case, it will work as the Else branch of the IF workflow statement.
    The second way to specify a condition is through ad hoc code. In this case, you add a method to the workflow class, as follows:

    Sub EvalCondition(ByVal sender As Object, _
    ByVal e As ConditionalEventArgs)
    e.Result = ... ' Boolean value
    End Sub

    The function must match the signature that accepts an object and a ConditionalEventArgs class and returns void. The Result member of the ConditionalEventArgs class will be set to the Boolean value that represents the evaluation of the condition.

    IfElse activities can be nested to express complex logic, but the design of the logic remains hardcoded in the workflow. This is good and bad at the same time. It’s a good thing because it allows you to design the workflow exactly as you want and integrate it with the rest of the activities. It’s a bad thing when you need to create a set of rules to initialize portions of the workflow’s state. Having a bunch of IfElse activities only to assign values to internal members of the workflow is clearly overkill.
    You should use a combination of IfElse activities when you really need to control the flow of the workflow and orchestrate various blocks of the work. If what you need is just a sequence of programmatic If statements with simple code attached to branches, then you’re better off using a Policy activity. A Policy activity is a collection of rules. The code associated with each rule, though, is limited to setting a property on a workflow or calling a workflow method or a static method on types in referenced assemblies.
    The activity is associated with a sorted collection of rules that you define through the editor. Each rule has a priority and an Active property. The combination of the two properties determines whether the rule should be evaluated and with which priority. In addition, a rule must specify a reevaluation behavior—Always (default) or Never. If set to Always, the rule is reevaluated as needed, otherwise it is evaluated only the first time and never changes whatever happens to the workflow’s state.
    Instead, the rule set as a whole is subject to forward chaining. Simply put, forward chaining refers to the ability of the actions of one rule to cause other dependent rules to be reevaluated. For example, an action that updates the value of a field that another rule tests requires a reevaluation of the involved rules (unless reevaluation is disabled on the rule). There are three types of forward chaining.
    Implicit chaining indicates that the runtime engine will figure out which fields are modified by some actions and automatically reevaluate them. This mechanism succeeds as long as actions work on properties explicitly. What if you have an action like the following:

    IF this.MinimumLength <= 8 THEN RefreshInternalState()

    Who knows what the RefreshInternalState method is going to do? The method might touch on workflow properties that are involved with other rules in the policy activity. By using attributes on the method declaration, you can explicitly indicate the behavior of the method:

     _
    Public Sub RefreshInternalState()
    Me.PasswordLevel = 1
    End Sub

    The RuleWrite attribute indicates that the method is going to modify the specified property; likewise, the RuleRead attribute indicates that the method reads from the specified properties. In this way, unequivocal information is provided to the runtime engine to keep the rule set in sync.
    Finally, you can write actions that explicitly call out updates on involved properties. Here's an example:

    IF this.MinimumLength <= 8 THEN 
    RefreshInternalState()
    Update("PasswordLevel")

    The Update method in the rule action orders the reevaluation of all rules that include the specified property.

    Loops and Repeated Activities
    The native set of activities provides classic While activity as well as a Replicator activity that has some points in common with a classic For loop. The While activity accepts a condition and evaluates it at the beginning of each iteration. If the condition is true, the activity runs the specified child activity and repeats until the condition becomes false. Note that a single activity is permitted in the body of the While. For this reason, you might want to use a composite activity such as Sequence or Parallel to execute multiple activities in the loop. (The term "interleaved" is probably more appropriate than "parallel" here. There is no true concurrency going on with the Parallel activity, only interleavings within the same thread.)
    Similar to a Foreach statement, the Replicator activity creates and executes a given number of instances of the specified child activity. You can specify only one child activity, but using composite or custom activities is allowed. You can't control the number of iterations through a declarative property. Instead, you write a handler for the Initialized event and populate the CurrentChildData collection with initialization data for each of the desired instances:

    Sub replicator1_Initialized(ByVal sender As Object, _
    ByVal e As EventArgs)
    Console.WriteLine("Initializing ...")
    replicator1.CurrentChildData.Add("You are #1")
    replicator1.CurrentChildData.Add("You are #2")
    replicator1.CurrentChildData.Add("You are #3")
    End Sub

    The preceding code snippet orders three instances of the child activity of the Replicator, each initialized with a given string. Note that if you leave the CurrentChildData collection empty, the Replicator won't run any child activity and is limited to firing top-level events such as Initialized and Completed. You can initialize child activities using an object (not necessarily a string), including instances of custom classes. The Replicator also includes events to signal initialization and completion of each child activity. By default, child instances run in sequence; by setting the ExecutionType property, though, you can opt for a parallel execution. When a parallel execution is requested, all child activity instances get created before the replicator starts and executes on parallel threads. When working in sequential mode, the next activity is instantiated only when the previous has finished.
    If no global condition is set through the UntilCondition property, the Replicator ends when all replicates have completed; otherwise, the activity terminates when the UntilCondition is true. Note, though, that the activity will hang if all the child activities have completed and the UntilCondition property evaluates to false; the Replicator never loops through the child activities like in a While loop. The UntilCondition is evaluated after the global initialization of the activity, after each child activity has completed, and after all included activities have completed. If, at any time, the condition evaluates to true, the Replicator will exit immediately.
    You can mix together conditional execution and loops in the ConditionedActivityGroup (CAG) activity. The CAG contains a number of child activities (possibly composite activities) and runs them until a global condition is met. Basically, a CAG combines the behavior of While and IfElse activities. Its internal logic is expressed by the following pseudocode:

    While condition
    If child1.WhenCondition Then child1.Execute
    If child2.WhenCondition Then child2.Execute
    :
    If childN.WhenCondition Then childN.Execute
    End While

    Each child activity has a WhenCondition property. Based on the evaluation of the specified condition, the activity is run or skipped in the current iteration. Note, though, that if the child activity has no WhenCondition set, it is executed only the first time and skipped for all subsequent iterations. All conditions are evaluated whenever required based state change dependencies.
    The CAG activity terminates after the UntilCondition returns true and immediately cancels any currently executing activities. If no condition is specified, CAG completes when no child activities are running either because they have no condition set or the condition evaluates to false.

    Synchronization Blocks
    A sequential workflow that has no interleaved activities doesn't bother about serializing access to shared members. However, operation is different when a Parallel activity is used with two or more sequences running in an interleaved manner. Take a look at Figure 5. The While activity contains a Sequence block which, in turn, chains Parallel and Code activities. Internally, the Parallel activity has four different blocks, each performing a mathematical operation on a number defined as a member of the workflow class. The four branches in the Parallel activity execute in an interleaved manner. (There is only one thread in a workflow instance at any one time. That thread switches back and forth between the branches of the Parallel activity.) What about cross-task synchronization? By default, each piece of code running inside any of the child activities will perform a direct access to the shared member.

    Figure 5 Parallel Tasks (Click the image for a larger view)

    With the simple schema of Figure 5, it may happen that each parallel branch runs as an atomic operation. This would be purely coincidental, though, and strictly based on the complexity and the duration of each operation. What if each branch is made of multiple activities? SynchronizationScope provides a declarative and explicit way of modeling synchronized access of shared state within a given workflow instance across a set of activities.
    The section of the workflow running inside a SynchronizationScope activity is a sort of atomic operation that can't be interrupted. There's no transactional semantics here and the operation wrapped up in the SynchronizationScope activity cannot be rolled back. The SynchronizationScope activity plays a key role in all solutions based on activities that have parallel execution paths, such as Parallel, Replicator, and CAG.
    To quickly figure out the role of a SynchronizationScope activity, take a look at Figure 6, which represents a modified version of the workflow in Figure 5. The blockMultiply activity counts two code blocks interspersed with a delay. The blockDivide activity contains one code block with no synchronization. If you place the contents of the blockMultiply outside of a synchronization scope, the blockDivide will likely execute during the delay phase of blockMultiply. Depending on what kind of updates you're making, this might be a serious issue. The SynchronizationScope activity safeguards the continuity of a section of the workflow.

    Figure 6 Parallel Tasks and Synchonization Scopes (Click the image for a larger view)

    Exception Handling
    Just as any other .NET-based application, a workflow can throw and catch exceptions. In particular, you use the Throw activity to throw a particular exception. The Throw activity requires a couple of settings—the type of the exception to throw and a workflow class member to store an instance of the exception object for further customization. You can use custom exception types as long as the type is referenced in the workflow project.
    To catch exceptions thrown by workflow activities, you add a FaultHandler activity. The workflow designers provide a container for all fault handlers you add. Each handler is bound to a workflow section that executes as soon as the exception is caught. After adding the FaultHandler activity, you define the type of the exception to catch. You can access the exception object through the Fault property. Note that to visualize fault handlers you have to switch the view in the Visual Studio 2005 designer and select the View Faults tab by clicking on the tab list at the bottom of the designer's view.

    Transactions
    The .NET Framework 2.0 includes an object to handle transactions easily and effectively—no matter the number and type of participant objects and the scope, local or distributed, of the transaction. The object is named TransactionScope and you typically use it according to this pattern:

    Using ts As New TransactionScope
    ...
    ts.Complete
    End Using

    The TransactionScope object guarantees that the transaction is either committed or rolled back in case of failure and, more importantly, it determines whether you need a local or distributed transaction and enlists any necessary resources. As the code reaches a point where it won't be running locally, TransactionScope escalates to the Distributed Transaction Coordinator (DTC) as appropriate. Any objects that implement the ITransaction interface can be enlisted with a transaction. The list includes all standard ADO.NET 2.0 data providers, while Microsoft Message Queue works in compatibility mode.
    It is worth noting that there are a number of differences between TransactionScope and Enterprise Services as far as distributed transactions are concerned. TransactionScope belongs to a transaction framework designed specifically to fit .NET-based applications—System.Transactions. Internally, though, the classes of the System.Transactions namespace sometimes end up delegating some work to DTC and COM+. Why is TransactionScope important here? The TransactionScope Windows Workflow Foundation activity is just a workflow wrapper for an instance of the TransactionScope .NET class.
    When you add a TransactionScope activity to a workflow, you can set the timeout for the transaction to complete and the desired level of isolation. All activities composed in the scope of the transaction form a unit of work that fulfills the classic ACID schema. When all child activities have successfully completed, the transaction commits and the workflow proceeds with the next step. The TransactionScope activity automatically rolls back if an exception is thrown from within the scope. Writing transactional workflows doesn't require you to explicitly deal with commit and rollback semantics—you just let things go if you want to commit and throw an exception to abort. The activity will comfortably manage everything else.
    Note that you can't nest two or more TransactionScope activities. Likewise, you can't suspend the workflow from within a transaction using the Suspend activity. Instead, you can incorporate event handlers in the transaction through either the Listen or the EventHandlingScope activities. In this case, though, the workflow host should include a persistence service, otherwise an exception would be thrown if the workflow attempts to save its state on idle.
    A related activity, CompensatableTransactionScope, also supports compensation. Compensation is the process of logically undoing the completed transactions in case of any subsequent business exceptions. Compensation differs from rollback in that it is a way to cancel the effects of a successfully completed and committed transaction when a rule is violated later in the workflow. The typical example of a rollback is when you have a transaction that transfers money across two accounts. The first call withdraws money from one account and the second call adds the same amount to another account. As long as the database supports the two-phase commit model, the rollback restores a consistent state in case of exceptions thrown within the transaction.
    Imagine an order processing workflow where a transaction is used to process payment through, say, a credit card service. As the first step, money is withdrawn from the credit card to pay for some goods. Next, after the transaction completed successfully, it turns out that the goods are no longer available for sale. Such a business rule violation requires that the results of the transaction are compensated with proper code—typically crediting money to the charge card.
    By right-clicking on the CompensatableTransactionScope activity, you can switch to the compensation view of the transaction and add all the activities that would compensate the effects of the transaction. In Figure 7, the OrderScope transaction is associated with a compensation activity code that will refund any money withdrawn in case of a business exception. As I mentioned earlier, exceptions in the workflow are caught by an exception handler. For a given exception (say, ProductDiscontinued) you invoke a Compensate activity bound to the transaction activity whose effects are canceled. In general, the Compensate activity triggers the compensation mechanism for any activity that is compensatable—that is, for any activity that implements the ICompensatableActivity interface. Along with CompensatableTransactionScope, CompensatableSequence also implements this interface and can be used for nontransaction-based compensation scenarios. However, you can write custom activities that support compensation as well.

    Figure 7 Transaction and Compensation Activities (Click the image for a larger view)

    Calling Out Other Code
    There are a few other activities to invoke and execute code. They are Code, InvokeWorkflow, InvokeWebService, and CallExternalMethod. The Code activity is the most flexible and represents a block of custom code you insert at some point in the workflow. The Code activity fires the ExecuteCode event that you handle within the workflow and makes it run the code you want. The code, though, is incorporated in the workflow and compiled with it. The Code activity can call into an external assembly as long as you put into the ExecuteCode event handler any necessary code that loads the assembly and selects the method.
    The InvokeWorkflow activity takes a reference to a workflow and invokes it asynchronously. You can pass input parameters but be aware that the InvokeWorkflow activity completes before the launched workflow starts its execution. In no way can you synchronize the current execution with that of an external workflow or process the output parameters in the current workflow.
    The InvokeWebService activity synchronously invokes a Web service method through a proxy class. The behavior of the activity can be simulated using a Code activity and calling a Web service from there.
    Finally, the CallExternalMethod activity is used to call a method on a local service. A local service is any class available to the workflow that implements an interface decorated with the ExternalDataExchange attribute. In addition, the class that represents the local service must be added to the workflow runtime as an external data exchange service:

    Dim service As New ExternalDataExchangeService 
    runtime.AddService(service)
    Dim localService As New YourService()
    service.AddService(localService)

    You configure a CallExternalMethod activity to call into any of the methods of the interface implemented by the local service. Why is CallExternalMethod limited to calling into the methods of a well-known interface? The reason lies in the fact that the activity is not a mere code executor but is designed to work in conjunction with the HandleExternalEvent activity to implement a two-way communication with a local service. With the CallExternalMethod activity you invoke a method on the service; you handle any event raised by the service by placing a HandleExternalEvent activity in the workflow.

    Summary
    Activities are the building blocks of workflows. You create workflow solutions by composing activities in the Visual Studio 2005 designer. Like server controls in ASP.NET and controls in Windows Forms, workflow activities are the essence of the solution and form the primary tool chest for developers. The Windows Workflow Foundation provides a number of in-box activities to cover the most common needs. Here I reviewed the native activities that cover transactions, parallel and conditional execution, loops, and exception handling. A number of free additional activities are available at wf.netfx3.com. Check them out!

    SharePoint 2010: A Developer’s Top 15 List

    SharePoint 2010: A Developer’s Top 15 List

    Developers of SharePoint should be giddy with excitement in all of the tools and features coming out of Visual Studio 2010 and SharePoint Designer 2010.

    1. “Save site as template” now exports as a WSP which can be imported into Visual Studio 2010 as a new project

    2. BDC is now Business Connectivity Services which supports full Create, Read, Update, Delete calls to sources, plus Office 2010 integration using new SharePoint Designer 2010 tools 

    3.  LINQ to SharePoint to replace complex CAML queries in code.  Strongly typed, intelli-sense, joins and projections
               
    4.  Developer Dashboard displays call stack, load time, and other valuable data to debug and review code

    5.  Relationships between lists, supporting cascade deletes (transactions are actually handled on SQL Server)

    6.  Large List?  No problem! Just be certain of data in views.  Use throttling and indexes for performance.  10’s to 100’s of thousands of documents = no problem.

    7.  Column Validation – lets us add validation logic when defining columns

    8.  Client Object Model – simple API to Add, Retrieve, Update and Manage data.  Commands are batched for performance:

    ClientContext cnt = new ClientContext (“http://siteurl”);
    Web site = context.Web;
    context.Load(site);
    context.ExecuteQuery();
    site.Title = “Something New”;
    site.Update();
    context.ExecuteQuery();

    9.  Rest APIs – uses ADO.NET Data Services.  Out of the box services in SharePoint.  Retrieve data off of site in 3 lines of code.

    10.  Better Events and Workflow.  Event Receivers and Workflows now possible at the site scope level (workflow does not bind to a list).  Event receivers can run asynchronously

    11.  Easily build dialog forms using AJAX. 

    12.  Silverlight web part out of the box. – code doesn’t need to run on server!!!

    13.  Sandboxed Solutions – can monitor counters on server (CPU, RAM, etc.) to automatically shutdown bad code.  Uses a proxy worker process so not direct access to Microsoft.SharePoint.dll

    14.  WSP is the unified developer platform (for both Site Collections and local machine)

    15.  Integration with Team Foundation Server (TFS):  work item tracking, source control, team build, manage test cases, automated testing, and load testing!

    « Older Entries