Monday, March 22, 2010

SharePoint 2007 - Adding Event Receivers using STSADM

Recently I was thinking about what might be the best way to allow people to script the settings that enable the storing of page history.  I decided that I would start off by providing a simple STSADM command that would allow you to script the adding of event receivers to a list (fortunately making it work for webs and content types didn't really require any additional work so I covered those as well).  The new command I created is called gl-addeventreceiver.


I'll probably eventually come up with something else but this at least is a start - I primarily don't like it because it requires that people know how the web part history project works so I'll probably create a command specific to enabling the history so that it abstracts out the technical details which could always change (there just hasn't been a whole lot of interest in the project so I've not really spent much time on it).  In the meantime this command is a nice generic tool that could be used by developers and administrators for various reasons (I'll probably create an enum and remove command to supplement this one - just haven't gotten around to it yet).


Adding an event receiver via code is really very simple - just a matter of calling the Add method of the SPEventReceiverDefinitionCollection object which you can get via the EventReceivers property of either the SPList, SPContentType, or SPWeb object.  To get an existing event receiver (to check for existence as we don't want to add twice) we have to loop through the collection comparing the assembly name, class name, and event receiver type.

1: /// <summary>
   2: /// Adds an event receiver to the specified target
   3: /// </summary>
   4: /// <param name="url">The URL.</param>
   5: /// <param name="contentTypeName">Name of the content type.</param>
   6: /// <param name="target">The target.</param>
   7: /// <param name="assembly">The assembly.</param>
   8: /// <param name="className">Name of the class.</param>
   9: /// <param name="type">The type.</param>
  10: /// <param name="sequence">The sequence.</param>
  11: /// <param name="name">The name.</param>
  12: public static void Add(string url, string contentTypeName, TargetEnum target, string assembly, string className, SPEventReceiverType type, int sequence, string name)
  13: {
  14:     using (SPSite site = new SPSite(url))
  15:     using (SPWeb web = site.OpenWeb())
  16:     {
  17:         SPEventReceiverDefinitionCollection eventReceivers;
  18:         if (target == TargetEnum.List)
  19:         {
  20:             SPList list = Utilities.GetListFromViewUrl(web, url);
  21:  
  22:             if (list == null)
  23:             {
  24:                 throw new Exception("List not found.");
  25:             }
  26:             eventReceivers = list.EventReceivers;
  27:         }
  28:         else if (target == TargetEnum.Site)
  29:             eventReceivers = web.EventReceivers;
  30:         else
  31:         {
  32:             SPContentType contentType = null;
  33:             try
  34:             {
  35:                 contentType = web.AvailableContentTypes[contentTypeName];
  36:             }
  37:             catch (ArgumentException)
  38:             {
  39:             }
  40:             if (contentType == null)
  41:                 throw new SPSyntaxException("The specified content type could not be found.");
  42:  
  43:             eventReceivers = contentType.EventReceivers;
  44:         }
  45:         SPEventReceiverDefinition def = Add(eventReceivers, type, assembly, className, name);
  46:         if (sequence >= 0)
  47:         {
  48:             def.SequenceNumber = sequence;
  49:             def.Update();
  50:         }
  51:     }
  52: }
  53:  
  54: /// <summary>
  55: /// Adds an event receiver to a the specified event receiver definition collection.
  56: /// </summary>
  57: /// <param name="eventReceivers">The event receivers.</param>
  58: /// <param name="eventReceiverType">Type of the event receiver.</param>
  59: /// <param name="assembly">The assembly.</param>
  60: /// <param name="className">Name of the class.</param>
  61: /// <param name="name">The name.</param>
  62: /// <returns></returns>
  63: private static SPEventReceiverDefinition Add(SPEventReceiverDefinitionCollection eventReceivers, SPEventReceiverType eventReceiverType, string assembly, string className, string name)
  64: {
  65:     if (GetEventReceiver(eventReceivers, eventReceiverType, assembly, className) == null)
  66:     {
  67:         eventReceivers.Add(eventReceiverType, assembly, className);
  68:         SPEventReceiverDefinition def = GetEventReceiver(eventReceivers, eventReceiverType, assembly, className);
  69:         if (!string.IsNullOrEmpty(name))
  70:         {
  71:             def.Name = name;
  72:             def.Update();
  73:         }
  74:         return def;
  75:     }
  76:     return null;
  77: }
  78:  
  79: /// <summary>
  80: /// Gets the event receiver.
  81: /// </summary>
  82: /// <param name="eventReceivers">The event receivers.</param>
  83: /// <param name="eventReceiverType">Type of the event receiver.</param>
  84: /// <param name="assembly">The assembly.</param>
  85: /// <param name="className">Name of the class.</param>
  86: /// <returns></returns>
  87: private static SPEventReceiverDefinition GetEventReceiver(SPEventReceiverDefinitionCollection eventReceivers, SPEventReceiverType eventReceiverType, string assembly, string className)
  88: {
  89:     foreach (SPEventReceiverDefinition erd in eventReceivers)
  90:     {
  91:         if (erd.Assembly == assembly && erd.Class == className && erd.Type == eventReceiverType)
  92:         {
  93:             return erd;
  94:         }
  95:     }
  96:     return null;
  97: }


The help for the command is shown below:


C:\>stsadm -help gl-addeventreceiver

stsadm -o gl-addeventreceiver


Adds an event receiver to a list, web, or content type.

Parameters:
        -url <web or list URL>
        -assembly <assembly>
        -class <class name>
        -type <itemadding | itemupdating | itemdeleting | itemcheckingin | itemcheckingout | itemuncheckingout | itemattachmentadding | itemattachmentdeleting | itemfilemoving | fieldadding | fieldupdating | fielddeleting | sitedeleting | webdeleting | webmoving | itemadded | itemupdated | itemdeleted | itemcheckedin | itemcheckedout | itemuncheckedout | itemattachmentadded | itemattachmentdeleted | itemfilemoved | itemfileconverted | fieldadded | fieldupdated | fielddeleted | sitedeleted | webdeleted | webmoved | emailreceived | contextevent | invalidreceiver>
        -target <site | list | contenttype>
        [-contenttype <content type name if target is ContentType>]
        [-sequence <sequence number>]
        [-name <the name to give to the event receiver>]


The following table summarizes the command and its various parameters:



Command NameAvailabilityBuild Date
gl-addeventreceiverWSS v3, MOSS 2007Released: 9/13/2008





Parameter NameShort FormRequiredDescriptionExample Usage
url YesThe URL to the web or list to add the event receiver to.-url http://portal/pages
assemblyaYesThe fully qualified assembly name containing the event receiver class to add.-assembly "Lapointe.WebPartPageHistory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3216c23aba16db08"

-a "Lapointe.WebPartPageHistory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3216c23aba16db08"
classcYesThe fully qualified class name of the event receiver to add.-class Lapointe.WebPartPageHistory.ListEventReceivers.SourceListEventReceiver

-c Lapointe.WebPartPageHistory.ListEventReceivers.SourceListEventReceiver
type YesThe event type to add.  The command does not validate that you are adding the correct type for the specified target or that the specified class contains handlers for the type specified.-type itemupdated
target NoThe target type to add the event receiver to.  Must be either "list", "site", or "contenttype".  If omitted defaults to "list".-target list
contenttypectNo, unless target is contenttypeThe name of the content type to add the event receiver to if the target is contenttype.-contenttype "Page"

-ct "Page"
sequenceseqNoThe sequence number specifies the order of execution of the event receiver.-sequence 1000

-seq 1000
namenNoThe name to give to the event receiver.  The name has no significance but can be useful when later listing the event receivers.-name "Handle Saving of Page History"

-n "Handle Saving of Page History"



The following is an example of how to add three event receivers to a pages library - the three commands illustrated below constitute the required event receivers that must be enabled to turn on the web part page history:

stsadm -o gl-addeventreceiver -url http://portal/pages -assembly "Lapointe.WebPartPageHistory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3216c23aba16db08" -class "Lapointe.WebPartPageHistory.ListEventReceivers.SourceListEventReceiver" -target list -sequence 1000 -type itemcheckedin

stsadm -o gl-addeventreceiver -url http://portal/pages -assembly "Lapointe.WebPartPageHistory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3216c23aba16db08" -class "Lapointe.WebPartPageHistory.ListEventReceivers.SourceListEventReceiver" -target list -sequence 1000 -type itemupdating

stsadm -o gl-addeventreceiver -url http://portal/pages -assembly "Lapointe.WebPartPageHistory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3216c23aba16db08" -class "Lapointe.WebPartPageHistory.ListEventReceivers.SourceListEventReceiver" -target list -sequence 1000 -type itemupdated

Thursday, March 11, 2010

Working with BCS in Visual Studio 2010 series

The SharePoint Team Blog has a great series that walks you through the creation of an external list using Visual Studio 2010 and the new Business Data Connectivity Designer! The first two posts of the series are already live with more to come.





Microsoft Windows PowerShell 2.0 Programming for the Absolute Beginner

Configure SharePoint Server 2010 for Mobile Device Access

Microsoft SharePoint 2010 includes support for using feature phones to access documents, lists, calendars on SharePoint 2010, performing people and document searches and receiving SMS alerts on SharePoint content.
Microsoft SharePoint Workspace Mobile 2010 allows Windows phone users to access offline documents on SharePoint 2010.
Microsoft SharePoint Server 2010 supports accessing information from a web browser enabled mobile phone or other devices. It delivers:
  • Lightweight interface and navigation for accessing document libraries, lists, wikis, blogs, web part pages and LOB data
  • Web companions for viewing Word, Excel and PowerPoint documents
  • Mobile MySite for staying in touch with colleagues
  • Mobile search experience for finding people, contact information, SharePoint content and finding data in custom databases
  • SMS Alerts for changes to SharePoint content
  • Features are customizable and, all the information is in SDK.

SharePoint Home Page with Mobile View:

When you access Microsoft SharePoint 2010 site from mobile phone, this view will be automatically redirected to mobile view as a picture below.
image

View all Site Contentclip_image007

User can click or choose the “View All Site Content” link on top of the home page. It will switch to the following kind of library:
  • Parent site
  • Lists of List
  • Document Libraries
  • Pictures Libraries
  • Sub sites
The following sections will tell you things you need to know for deployment.

Previewing the mobile experience on the desktop

You can preview the mobile experience on a desktop web browser. To do this, add “?mobile=1” to the end of a SharePoint URL for a document, home page, web part page, wiki page, list view page, list item details/edit/new form page, or Search center page. This does not work for all pages/lists/documents but can show you an idea of the mobile experience.

SharePoint Deployment for Mobile Access

This section walkthroughs configuration that needs to be setup to deploy SharePoint 2010 for mobile access also provides a list of mobile browsers that support mobile view.
  • Firewall setting
  • Enabling mobile access
  • Developing custom mobile solutions
  • Browser standards and requirements
  • Accessing the mobile experience
  • Security and Privacy

 

Firewall Considerations

As mobile phones connect to the public Internet, the SharePoint server needs to be accessible outside of the corporate firewall. IT administrators can publish SharePoint via an SSL VPN gateway, use a mobile proxy or expose SharePoint server to internet directly.

SSL VPN Access

One option is to use an SSL VPN gateway server, like Microsoft’s forthcoming Forefront Unified Access Gateway (UAG) Server, to publish SharePoint sites across the firewall as illustrated in the diagram below. The SSL VPN server needs to support the mobile devices that you are planning to enable access too. Microsoft UAG server, currently in Beta, supports mobile browsing access. to understand more UAG in detail. Forefront UAG RC0 is available at here.
Once the SharePoint server is published outside the firewall, the Alternative Access Mapping settings in the Central Administration page need to be configured. In addition, the sites to be published need to belong to a zone which allows cross firewall access. These settings are found under Central Administration. Go to System Settings and under System Settings choose Configure cross Firewall access zone.
To configure the SharePoint Workspace mobile client to access and offline documents on a SharePoint server, users need to enter the UAG server address in the settings page.

image

Mobile Proxy Servers

Mobile Proxy Servers such as Microsoft’s Mobile Device Manager or Blackberry Enterprise Server can also handle behind-the-firewall access to SharePoint. The server needs to pass the mobile browser’s HTTP headers directly through to SharePoint to operate properly.
SharePoint Workspace mobile client works with Microsoft’s Mobile Device Manager.

Direct Internet Access

SharePoint can be placed on an extranet to enable device access. Only basic authentication is supported, however, and with any Internet-facing servers we recommend a combination of technology and policy safeguards such as SSL.
There are no configuration requirements for mobile phones which are within the corporate firewall.

 

Enable Contents for Mobile Access

While most mobile-enabled content is readily accessible out of the box, there are some data types that are either not supported or require additional configuration steps.
Web part pages, document libraries/picture libraries, lists (e.g., calendars, contacts, tasks, etc.) blogs, wikis, Office documents, Search and MySite are available out of the box. The “list view” and “image” web parts are mobile enabled out of the box. Want to mention that MySite and Search functions are only available on MOSS server.
Other web parts need to have a “mobile web part adapter” written which enables mobile functionality. More details on mobile adapters can be found in the Developing Custom Mobile Solutions section below. Pages under the “_Layouts” folder are not available as mobile pages.

 

Developing Custom Mobile Solutions

SharePoint provides a mobile web part framework for developing custom solutions. By adding mobile web part adapter render classes to the web parts, existing web parts can be interacted with as part of the mobile experience. Some base adapter classes are available for common functions. The SharePoint 2007 mobile SDK can be a good starting point to learn about this development option. For SharePoint 2010, SharePoint mobile pages can be customized by modifying the underlying layouts page. In addition, a mobile page can be configured to redirect to an alternative mobile page.

 

Browser Standards and Requirements

SharePoint 2010 supports a wide range of mobile browsers as list below. You don’t need to do any additional setting on mobile device.
  • IE Mobile on Windows Mobile 5/6/6.1/6.5
  • Safari4 on iPhone 3G/S
  • BlackBerry 4.x and newer versions
  • Nokia S60
  • NetFront 3.4, 3.5 and newer versions
  • Opera Mobile 8.65 and newer versions
  • Openwave 6.2, 7.0 and newer versions
SharePoint Workspace mobile client is available exclusively on Windows phones.

 

Accessing the mobile experience

To access mobile pages, the URL is the same as that of the desktop browser page. However, it can vary depending on the configuration and presence of web proxies. If the proxy-enabled URL is not known, the user can choose the “E-mail a link” button on the Page tab of the SharePoint ribbon in web part page, wiki page, list view page to receive the address in email body. SharePoint 2010 will automatically redirect to the mobile page if a user accesses the URL via a mobile browser.
clip_image009 Recognition was made by USERAGENT to recognize for accessing mobile browser to redirect to mobile view is managed by the file “compat.browser” within the server’s IIS directory that manages device profiles (If the web application port is 80, the file path will be "\inetpub\wwwroot\wss\VirtualDirectories\80\App_Browsers\compat.browser"). With a text editor, the file can be modified to change redirect behavior. The IsMobileDevice attribute of that mobile browser when set to FALSE will cause SharePoint to bypass the mobile view for that browser.
Please refer below MSDN document for browser profile definition.
http://msdn.microsoft.com/en-us/library/ms228122.aspx

Security and Privacy

Within the firewall SharePoint Workspace mobile client uses NTLM or Kerberos authentication schemes. Outside the firewall Basic authentication scheme over SSL is used to communicate with the SharePoint server published on UAG.
Recommend enabling SSL communication for mobile browsing access to maintain secure communications between the mobile device and SharePoint server.
When 2-factor authentication is required, it needs to be handled by the SSL VPN or proxy server and the mobile device.
Finally, administrators should be aware that mobile browsers might cache information on the device. Recommend setting policies around device locking and types of information accessible on mobile phones to minimize the risk of privacy or other issues if a device is lost.
Hopefully this information is helpful to you

Monday, March 8, 2010

ASP.NET 4.0 and Visual Studio 2010 Web Development Beta 2 Overview

This whitepaper provides an overview of the new exciting features available with ASP.Net 4.0.
Below is a list of the topics covered in the document:

Core Services
Web.config File Minification
Extensible Output Caching
Auto-Start Web Applications
Permanently Redirecting a Page
The Incredible Shrinking Session State
Expanding the Range of Allowable URLs
Extensible Request Validation
Object Caching and Object Caching Extensibility
Extensible HTML, URL, and HTTP Header Encoding
Performance Monitoring for Individual Applications in a Single Worker Process
Multi-Targeting

New Features in ASP.NET AJAX 4
Client Template Rendering
Instantiating Behaviors and Controls Declaratively
Live Data Binding
Using the Observer Pattern with JavaScript Objects and Arrays
The DataView Control
The AdoNetServiceProxy Class
The DataContext and AdoNetDataContext Classes
Refactoring the Microsoft AJAX Framework Libraries
The DOM Ready Event
Using JSONP to Retrieve Cross-Domain Data.

Web Forms
Setting Meta Tags with the Page.MetaKeywords and Page.MetaDescription Properties
Enabling View State for Individual Controls
Changes to Browser Capabilities
Routing in ASP.NET 4
Setting Client IDs
Persisting Row Selection in Data Controls
ASP.NET Chart Control
Filtering Data with the QueryExtender Control
Html Encoded Code Expressions
Project Template Changes
CSS Improvements
Hiding div Elements Around Hidden Fields.
Rendering an Outer Table for Templated Controls
ListView Control Enhancements
CheckBoxList and RadioButtonList Control Enhancements
Menu Control Improvements
Wizard and CreateUserWizard Controls

ASP.NET MVC
Dynamic Data
Enabling Dynamic Data for Existing Projects
Declarative DynamicDataManager Control Syntax
Entity Templates
New Field Templates for URLs and E-mail Addresses
Creating Links with the DynamicHyperLink Control
Support for Inheritance in the Data Model
Support for Many-to-Many Relationships (Entity Framework Only)
New Attributes to Control Display and Support Enumerations
Enhanced Support for Filters

Visual Studio 2010 Web Designer Improvements
Improved CSS Compatibility
HTML and JScript Snippets
JScript IntelliSense Enhancements.

Web Application Deployment with Visual Studio 2010
Web Packaging
Web.config Transformation
Database Deployment
One-Click Publish for Web Applications

 ASP.NET 4.0 Programmer's ReferenceASP.NET 4.0 Programming