Saturday, July 11, 2009

Sharepoint: Coding Standards

The guidelines contained here should be used in all SharePoint development as a standard to ensure consistency, performance, and security.

  • General Coding
    o Follow the .Net Developer’s Guide “Guidelines and Best Practices”: http://msdn2.microsoft.com/en-us/library/ms184412(vs.80).aspx
    o FXCOP is a Microsoft developed utility that checks code against a set of rules. FXCOP should be run on all code, and is available for download from
    http://www.gotdotnet.com/workspaces/fxcop/
  • CAML Tools
    The following CAML tools are available for aid with CAML development:
    o U2U: Build, test, and execute CAML queries
    § Provides: U2UCamlCreator.exe application to build CAML query strings in a WYSYWIG fashion, and a reference assembly (U2U.SharePoint.CAML.Server.dll) which encapsulates code for SPQuery class of the WSS OM (which allows execution of CAML query strings)
    § Download from:
    http://www.u2u.info/SharePoint/U2U%20Community%20Tools/Forms/AllItems.aspx
    o CAML Viewer 1.0: Allows writing and testing of CAML queries easily (similar to a tool such as SQL Analyzer), viewing the CAML used in list views, and generates and formats code. This tool is based on the object model, and can be downloaded from: http://blog.spsclerics.com/articles/607.aspx
    o CAML Check: Provides for the execution of CAML queries against a list and is based on the object model. This tool does not provide a user interface, however the source code is provided so it can be expended. This tool can be downloaded from: http://projectdistributor.net/Releases/Release.aspx?releaseId=89
  • Visual Studio 2005 extensions
    o Visual Studio 2005 extensions for Windows SharePoint Services 3.0 Tools for developing custom SharePoint applications: Visual Studio project templates for Web Parts, site definitions, and list definitions; and a stand-alone utility program, the SharePoint Solution Generator. http://www.microsoft.com/downloads/details.aspx?FamilyID=19f21e5e-b715-4f0c-b959-8c6dcbdc1057&DisplayLang=en o Visual Studio 2005 extensions for .NET Framework 3.0 (Windows Workflow Foundation) Provides developers with support for building workflow-enabled applications using Windows Workflow Foundation http://www.microsoft.com/downloads/details.aspx?FamilyId=5D61409E-1FA3-48CF-8023-E8F38E709BA6&displaylang=en
  • Web part guidelines:
    o Use ASP.Net 2.0 web parts instead of SharePoint web part, even if calling SharePoint object model code: http://msdn2.microsoft.com/en-us/library/ms367238.aspx
    o Do not stream HTML with individual statements, because if an error occurs in the middle of the execution, then the error will be streamed in the middle of the other information. Instead, batch the html with System.Text.StringBuilder and render with HtmlTextWriter
    o If you need to call a Web service, server proxy settings may not have been set, so ensure machine was configured. If it wasn’t, let admin set it in config file, and if it wasn’t set there, then obey the toolpane setting
    o When configuration is required for a web part before it can function, put a link to the configuration dialog in the body of the Web Part; an example of this is the stock ticker web part that requires the input of at least one symbol
    o When using web part properties, set a default value
    o For information on uploading a document programmatically:
    http://blogs.officezealot.com/legault/archive/2007/02/19/20162.aspx
    o BaseAreaWebPart is derived from CacheableWebPart, which allows per user or shared caching; also subscribes to the hidden data access web part which issues only one database query per page for performance improvements
    o Reference the following whitepaper that provides in-depth information regarding web parts:
    http://www.sharepointcustomization.com/resources/whitepapers/Web%20Parts2003.pdf
    o Review the items listed in “Best Practices for Developing Web Parts for SharePoint Products and Technologies” http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_sp2003_ta/html/ODC_WSSWebPartTips.asp
  • Code Access Security
  • Site Templates vs. Site Definitions
    o As a change from SPS 2003, in MOSS 2007, site templates and features are recommended above the use of site definitions.
    o Features are recommended for customizations that require code, and for customizations that may need to be upgraded after the site has been created.
    § Features can be applied using a Site Definition or Site Template Association (Feature Stapling). Please note that this only works with Sites created from a Site Definition.
    o Site templates are recommended for simple customizations that will not need to be changed after they are deployed
  • Localization
    o For localization, all strings must be stored in resource files, not hard coded
  • Monitoring, Logging and Reporting
    o All errors should be logged consistently to the event log using the Microsoft Enterprise Library:
    http://msdn2.microsoft.com/en-us/library/aa480464.aspx.
  • Security
    o All code should run as the current user whenever possible
    o No code should bypass SharePoint security and show data to users who do not have appropriate permissions
    o No User Names and Passwords may be stored – use the Business Data Catalog if they are required
    o No in-line code is allowed in Site pages. These are the pages which are created dynamically and stored in the document libraries. SharePoint applies strict security policy on these pages and they run in no-compile mode.
  • Disposing SP Objects properly
    o Make sure SharePoint objects like SPSite and SPWeb are being disposed properly. Do not dispose of any item returned directly from the Microsoft.SharePoint.SPContext.Site or Microsoft.SharePoint.SPContext.Web property except when you obtain reference to these using a constructor or when you use AllWebs. Refer to this article about disposing SharePoint objects: http://msdn2.microsoft.com/en-us/library/aa973248.aspx
  • Caching and scalability
    o Follow the guidelines for Data & SharePoint Object Caching and writing scalable code described in the “Common coding issues when using SharePoint Object Model” article at http://msdn2.microsoft.com/en-us/library/bb687949.aspx.
  • Configuration Data
    o In a shared environment no AppSetting entries are generally allowed in the web.config configuration file of WSS. Instead consider using your own application specific configuration file and store along within your application or feature folder. The feature.xml file should be used for storing Feature properties. A SharePoint list can be considered for storing common configuration data.
  • SharePoint Feature Guidelines
    o All Feature scope should be Site collection scope or lower instead of at the Web-application level. If features can be re-used then they could be deployed at the web-application level.
    o Feature Title should be appropriately named.
    o Provide full description which should include information on the usage, any restrictions, and dependencies on other features, assembly, ownership and contact information. This description should be included in the Feature.xml in addition to any documentation.
  • Upgrade
    o Web Part Upgrade:
    http://msdn2.microsoft.com/en-us/library/microsoft.sharepoint.webpartpages.webpart.afterdeserialize.aspx
    o Solutions:
    http://msdn2.microsoft.com/en-us/library/aa543659.aspx
  • References
    o For a complete reference to best practices, refer to following articles included in the WSS 3.0 SDK 1.1 updated on December 2007.
    o Best Practices: Common Coding Issues When Using the SharePoint Object Model
    o Best Practices: Using Disposable Windows SharePoint Services Objects

Sharepoint: Shared Environment Scenario (What Sharepoint Admins Want)

Appropriate use of built in functionality (80:20Rule)

To avoid redundant work and also to minimize issues occuring in your MOSS implementations, it is always desirable to use built in functionality wherever possible, instead of building replacement pieces from scratch. As a rule any application/portal developed must be in the boundaries of the 80:20 rule i.e. 80% native implementation and 20% custom (maximum limit).
Some examples of using built in functionality include:

Easy maintainability of customizations

All code and customizations should be documented, and built in a way so that any developer other than the original author will be able to maintain the code. Some examples of ways to improve the maintainability include:

  • Adding comments to the code that describe what the code does and why
  • Compiling all code from the source code in source control
  • Logging all error conditions and status changes to the event log

Flexibility for Code Reuse

To provide the best value to a shared environment/platform, an admin would always want to reduce duplicate efforts and reuse existing functionality wherever possible. To enable this, custom functionality must be flexible enough to work in environments other than the one originally designed for. Some examples of making code flexible include:

  • Setting Site URLs and List Names through properties instead of hard coding them
  • Using Sub Site relative URLs instead of absolute URLs, or Web Application relative URLs
  • Using resource files for strings so that code can be localized into different languages
  • Creating functionality as a SharePoint Feature so that it can be activated on any site
  • Creating reusable components such as web parts or web services
  • Use Universal Data Connections (UDCs) to connect to data sources in InfoPath Forms

Performance & Scale

To provide a good user experience and support a high number of sites, all customizations must have good performance and scale. There are two major parts of performance: how long the page takes to load (latency), and how many people can visit the page at the same time (throughput).
Some examples of ways to improve performance and scale include:

Usability

To provide the best user experience, all custom sites should have a high level of usability. This can be achieved by following standards and simplifying the options presented to the end user.
Some examples of improving usability include:

  • Providing descriptive text to guide users through steps
  • Using breadcrumbs to show users where they are in the site
  • Using standard SharePoint UI such as settings pages or the people picker

Monday, July 6, 2009

Applications Pools vs Application Domains

Many people are puzzled when they're asked this question about the difference between application pools and application domains. Although there is no direct comparison between these two but they provide almost the same functionality (though at different layers/levels) i.e. Isolation between applications. After reading this article one would be comfortable with the two terms: Application Pool and Application Domain. To start with let's discuss Application Domains.

Application Domains

An AppDomain is a .NET term (In IIS7, AppDomains play a larger role within IIS, but for the most part it's an ASP.NET term). Historically, process boundaries have been used to isolate applications running on the same computer. Each application is loaded into a separate process, which isolates the application from other applications running on the same computer. The applications are isolated because memory addresses are process-relative; a memory pointer passed from one process to another cannot be used in any meaningful way in the target process. In addition, you cannot make direct calls between two processes. Application domains provide a more secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. You can run several application domains in a single process with the same level of isolation that would exist in separate processes, but without incurring the additional overhead of making cross-process calls or switching between processes. An AppDomain contains InProc session state (the default session state mode). So if an AppDomain is killed/recycled, all of your session state information will be lost. (if you are using the default InProc session state). Applications can have multiple AppDomains in them although often times there is a one-to-one relationship between them. You can recycle an AppDomain in ASP.NET through the 'touch trick'. There are a few ways to do it, but the most straight forward is to edit your web.config file in notepad and add a space to an insignificant place. Then save the file. This will cause the AppDomain to recycle. This *does not* touch the IIS application though. Recycling an AppDomain will come pretty close to starting ASP.NET fresh again for that particular ASP.NET application, so although it doesn't recycle the apppool, it can give ASP.NET a fresh start in many situations.

The ability to run multiple applications within a single process dramatically increases server scalability. The isolation provided by application domains has the following benefits:

  • Faults in one application cannot affect other applications. Because type-safe code cannot cause memory faults, using application domains ensures that code running in one domain cannot affect other applications in the process.
  • Individual applications can be stopped without stopping the entire process. Using application domains enables you to unload the code running in a single application.
    Code running in one application cannot directly access code or resources from another application.
  • Permissions granted to code can be controlled by the application domain in which the code is running.
  • Isolating applications is also important for application security. For example, you can run controls from several Web applications in a single browser process in such a way that the controls cannot access each other's data and resources.

Now lets have a look at Application Pools.

Application Pools

Application pools is another way of isolation applications but on an IIS level. When you run IIS 6.0 in worker process isolation mode, you can separate different Web applications and Web sites into groups known as application pools. An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Any Web directory or virtual directory can be assigned to an application pool.
Every application within an application pool shares the same worker process. Because each worker process operates as a separate instance of the worker process executable, W3wp.exe, the worker process that services one application pool is separated from the worker process that services another. Each separate worker process provides a process boundary so that when an application is assigned to one application pool, problems in other application pools do not affect the application. This ensures that if a worker process fails, it does not affect the applications running in other application pools. Application pools, then, are essentially worker process configurations that service groups of namespaces.
Multiple application pools can operate at the same time. An application, as defined by its URL, can only be served by one application pool at any time. While one application pool is servicing a request, you cannot route the request to another application pool. However, you can assign applications to another application pool while the server is running.

Sunday, July 5, 2009

Authentication Methods in MOSS

There are many scenarios wherein we have to suggest/analyse every possible way of authentication to a Sharepoint portal. I especially in many situations have faced such queries from the Sharepoint admins/architects so that they have knowledge of every possible scenario that exists and the choice that they make is the best possible. I remember a situation wherein I was consulting on a Sharepoint implementation that had an audience of around 1.5 lakh employees of the company, around 20,000 odd external partner users and some part of the portal open to general public as well. One can go with the following approach:

Firstly let’s look at intranet users and make a valid assumption that we are working with a Microsoft based architecture using Active Directory (AD) as their directory services model. Next we need partners to be able to access the MOSS 2007 server but let’s assume the client doesn’t want to allocate them each an AD account on their domain, even if that account were locked down. Architecturally, the most obvious solution is Forms Based Authentication (FBA) using a role and membership provider to allocate and authenticate credentials. And finally let’s supply internet users with anonymous access to the server. Of course, we will have planned the security groups within which the access accorded to each of our types of user (intranet, extranet, internet) is restricted and have strict governance of how and when access is granted between these groups to have a foolproof solution. So an internet user may have access to published pages but not to the collaborative working areas of the site. Extranet users may only have access to dedicated partner sites in which they have been explicitly granted access and any general partner sites. Intranet users will have access to general staff areas an any site explicitly granted to them.

There would be many scenarios similar to the one I mentioned above and the above solution can be one of the answer to this situation. But I still believe this may not be the optimal solution in every case and hence one would need to know the different authentication methods available. Many articles/blogs have explained each of these methods in detail so I would not repeat that rather have links of the good articles explaining each of these techniques. Mentioned below are the methods that exist:

  • NTLM/Kerberos through AD
  • Forms Based Authentication (FBA)
  • Anonymous Access
  • ADAM (Active Directory Application Mode) -well everybody has his/her own perspective and one would treat ADAM method as the one using ASP.NET 2.0 forms-based authentication against a different membership database (AD) for the Extranet, perfect but I thought it to mention it seperately as it is one unique method.

Reference Links

Since this is the article which talks about authentication so I thought I would add the SSO piece as well in here so that the users need not go to any other place to search for it. Here's the link for two of the good articles to solve this mystery:

Saturday, May 30, 2009

Manageability of custom code on a MOSS server environment

Types of Custom Code
To ensure manageability for a MOSS server, all custom code should be packaged into one of the standard SharePoint constructs for building custom applications. Any custom code should be deployed with a solution (described below).

Ø Solution
A solution package is a cabinet (.cab) file with a .wsp file name extension and a manifest file. It can contain the following components:

  • Web Part files (*.webpart, *.dwp)
  • Site definitions
  • Code access security policies
  • Feature definitions and their corresponding element definitions and files
  • Template files and root files, which can include the following:

---- _layouts files
---- Resources (*.resx)
---- Resource files (for example, *.doc or *.xls)

  • Assemblies, which can include the following:

---- Safe control entries
---- Resources

For a detailed description of solutions and web-part packages, refer to
http://msdn2.microsoft.com/en-us/library/aa543741.aspx.

Ø Features
Features reduce the complexity involved in making simple site customizations, and are robust when upgrades are applied to a deployment. Features eliminate the need to copy large chunks of code to change simple functionality. Features thus reduce versioning and inconsistency issues that may arise among front-end Web servers. Features make it easier to activate or deactivate functionality in the course of a deployment, and administrators can easily transform the template or definition of a site by simply toggling a particular Feature on or off in the user interface. Features provide the following capabilities:

  • Pluggable behavior for activating or deactivating Features at a given scope
  • Scoping semantics for determining where custom code runs
  • A scoped property bag for storing data required by a Feature within its scope
  • Pluggable behavior for installing or uninstalling Features within a deployment
  • The basis of a unified framework for distributed deployment of WSS solutions

For a detailed description, refer to http://msdn2.microsoft.com/en-us/library/ms460318.aspx

Ø Excel User Defined Functions
User-defined functions (UDFs) are custom functions that extend the calculation and data-import capabilities of Excel. Developers create custom calculation packages to provide:

  • Custom implementations to built-in functions.
  • Functions that are not built into Excel.
  • Custom data feeds for legacy or unsupported data sources, & application-specific data flows.

Users who create workbooks can call UDFs from a cell through formulas—for example, "=MyUdf(C6*2.2)"—just like they call built-in functions.

Excel Services UDFs give you the ability to use formulas in cells to call custom functions written in managed code and deployed to Microsoft Office SharePoint Server 2007. You can create UDFs to:

  • Call Web services from the UDFs.
  • Get data from custom data sources into worksheets.
  • Call custom mathematical functions.

http://msdn2.microsoft.com/en-us/library/ms493934.aspx

Ø User Controls
SharePoint does not directly support ASP.NET Web user controls but they can be hosted inside a web-part. Web parts such as SmartPart & Son of SmartPart for SharePoint 2007 can be used for this purpose. It’s deployed in the GAC which can be leveraged to host your user controls instead of writing your own web-part to host these controls. If you prefer to write your own host web-part, it should be deployed in the BIN directory of SharePoint web-application.


Ø InfoPath Form Templates
InfoPath Forms Services, as part of either Office Forms Server 2007 or Microsoft Office SharePoint Server 2007, provides a Web browser experience for filling out InfoPath forms. For computers that do not have Microsoft Office InfoPath 2007 installed, users are able to work with the same form layout and logic as a user with InfoPath installed on their computer. Additionally, the same form can be used in the browser or in the client, which simplifies the form template design and management process. The InfoPath Forms Services technology is built as a feature on the Microsoft Office SharePoint Server 2007 platform. InfoPath 2003/2007 doesn’t have built-in support for consuming WSE 2.0 enabled web-services.
http://msdn2.microsoft.com/en-us/library/ms772182.aspx


Ø Business Data Catalog Application Definitions
One of the major design goals for the Business Data Catalog is to enable you to surface business data from various business applications such as SAP, Siebel, databases and web-services with minimal coding effort. To achieve this goal, the Business Data Catalog provides homogeneous access to the underlying data sources with a declarative metadata model that provides a consistent and simplified client object model. Version 1.2 of WSS 3.0 SDK includes BDC Definition Editor which automatically generates the XML definition file required for exposing data sources. BDC is exposed as a Shared Service in SharePoint which means that this application definition will be seen by everyone. The real value of BDC in SharePoint is reach, search and composite application. It’s recommended that you should use LOB application itself for changing data.
For complete technical details, go to
http://msdn2.microsoft.com/en-us/library/ms563661.aspx.

Security
Code Access Policy
The Sharepoint environment should not allow custom code to run with full-trust by default. SharePoint Server should be configured to run with medium trust (WSS_MEDIUM). Any custom assemblies should be deployed in the BIN directory hence will run with medium trust which does not allow direct access to system resources like registry or event logs or calling a public web-service. In order to grant specific permissions to an assembly, the custom code access policy is used to give controlled and granular access. Please refer to the following MSDN article for a detailed discussion;
http://msdn2.microsoft.com/en-us/library/bb530301.aspx

Elevation of Privileges
This new feature in SharePoint 2007 allows you to execute code under increased level of privilege than that of a current user.

No Support for WSE 2.0
SharePoint does not have inherent capability of using Web-Services Secured (WSE 2.0) in the current version. A custom solution is required to pass credentials to consume such a web-service.