Saturday 31 July 2010

Best Practice Sharepoint 2010 coding tips

1.> SharePoint Dispose Checker Tool - Run the SP Dispose Checker Tool on all custom code you write.
SPSite & SPWeb object has a big load and we need to ensure dispose is always called. 2 easiest ways to ensure Site and web objects are always disposed are shown below:
SPSite site;
try
{
site = new SPSite("http://demo1"); // Create the SPSite object
...
}
finally
{
if (site != null) // Check if the SPSite object exists
{
site.Dispose(); // Clean up the SPSite object as it has not be disposed of
}
}

Alternatively I prefer to use using statements
using (SPSite site = new SPSite(http://demo1/))
{

.... // SPSite.Dispose method will be called always
}
Run the SPDisposeCheck tool on all code before deploying outside of you development environment, this can be automated into VS 2010.
2.> Have at least 3 environments i.e. don't send code from the developers machine straight into production. Sandboxed solutions alleviates this risk to some degree but use a UAT, pre-prod, QA environment. Your deployment environment must mimic production as closely as possible i.e. ensure there is a separate SQL DB, all versions of software are identical, load balancing is setup. Have documented change control. Try perform changes through scripts not manual changes if possible. Web.config changes need to be replicated to all servers on the farm so doing the change manually is not the best option. Change the web.config via code to ensure it is done through the configuration database so they are changed on all web.config's in the farm.
3.> Error handling, catch errors as specifically as possible, die gracefully and appropriately, log the errors, check the production error logs periodically.
4.> Deploy code using wsp solutions. Ensure code is not in debug mode when compiled, it runs slower and potentially can crash/holdup your production environment. Implement CAS, deploy to bins if possible and apply CAS security policies to custom coding. Perform peer code reviews, it ensures coding standards are being followed, developers learn from each other, bugs are often picked up pre-testing and it increases team members knowledge that reduces maintenance costs.
5.> Develop using source control no matter how smal the dev project is. Preferably TFS 2010 but VSS 2005 is even fine, failing this use CVS, IMB/rationals ClearCase for source control. Also have bug tracking with TFS the integration is excellent between the bugs and the source control. I.e. use TFS if possible.
6.> SharePoint projects are often very good candidates to SCRUM or other agile methodologies. Use them if it's appropriate. Traditional formal SDLC / waterfall approaches tend to work well on the larger SharePoint projects.
7.> Use the developer dashboard.
8.> Unit testing - don't test SharePoints API, test your custom code. In MOSS Type Mock isolator was a great product for SharePoint I presume this is still the way to go. Andrew Woodward is a good blogger on SP unit testing.

SharePoint 2010 Claims based security & Security notes

Non-Active Directory users in MOSS could support Forms Based Authentication (FBA) so can use SQL to authenticate users, or other providers.
Claims based model decouples authentication from SharePoint.  You can declaratively setup multiple providers. Using Claims Based Authentication (CBA) you can now mix multiple users from different sources in a single zone/site.
In MOSS needed a separate web.config for each set of users.
Using claims based providers can logic/meta-data to provide different users rights depending on rights.
SAML - security access markup language, used instead of Windows identity security tokens. SAM is better in that the token is extendable to give additional authority/claims. I.e. can give additional info on the security token.
CBA allows use to authenticate internal Windows users and external FBA users in the same web app.
Note: Once a claim is validated, the user is added to the SPWeb properties: Users, AllUsers & SiteCollectionUsers before they are authorised.  So as long as they have been authenticated they are added to the properties shown above.

More Info:
Claims explained on Channel 9

SharePoint 2010 simple reporting options

Overview: SSRS has it's place but I want to gather reports from a composite application where data is stored in SharePoint lists.
Solutions:
OOTB web parts - UI may be tricky to get right but useful for quick reporting that can be performed by power users for general business users. Use filter, List View (XLVWP), CQWP, data View, chart web parts.
Custom Web parts - either write or buy web parts for querying lists. Custom CAML queries provide a solution to display data. Con is that it's pretty development heavy, inflexible and requires code deployment. SPMetal has issues with joins, publish columns and hidden columns such as "Created by". Also see Ninetix reporting.
Dataviews - Displaying list data using SPD - need SPD access. Joining 2 lists.

Giles Hamson has a good chart explaining reporting options.

Thursday 29 July 2010

Custom error and call stack info is not showing on my SP dev machine

Problem: I have turned my web.config file customErrors mode to "Off" however the error is telling me to turn it off or RemoteOnly. Therefore my screen is not showing me the problem. You can debug but the feedback is not provided on the erring SP page.
Hypothesis: Changing the web.config in the IIS SharePoint 2010 web site does not take effect. Ensure the web.config is correct and ensure other related web.configs used by the site are updated.
Resolution: Update the following 3 web.configs:

  • 14\CONFIG
  • 14\TEMPALTE\LAYOUTS
  • Current IIS web.config
web.configs should read:
customErrors mode="Off" />
SafeMode MaxControls="200" CallStack="true" ... AllowPage LevelTrace="true">
compilation batch="false" debug="true" >
More Info:

http://social.msdn.microsoft.com/Forums/en-US/sharepoint2010general/thread/2673ae4e-0b26-42ba-a158-1ceb63985721
http://blogs.msdn.com/b/amitsh/archive/2007/11/01/why-i-am-not-able-turn-off-customerrors.aspx

Monday 26 July 2010

Problems with SPMetal in SharePoint 2010

Overview: I have been doing a fair amount of LINQ to SharePoint lately and I have found a couple of issues, my vitriolic rants are:
  1. SP metal can run against external content type (BCS) - external content types don't get created by SPMetal;
  2. Hidden fields are not available to the SPMetal created proxy i.e. createdby, modified. Parameters.xml can be changed to display these hidden fields;
  3. Only SharePoint Foundation field types are generated.  Column types are not picked up by SPMetal include the "Managed Metadata columns", "Publishing Html" or "Publishing Image". Additionally any custom created columns are not included by SPMetal;
  4. Anonymous LINQ needs a work around.  Update 27/11/2010, August Cumulative Update (CU) for SharePoint 2010 apparently fixes the anaonymous LINQ to SharePoint issue. Ensure you get the latest CU due to the re-release issues.
  5. Update: 08 Oct 2010 - List attachments are not picked up by SPMetal.  You will need to use the Server side object model or extend SPMetal using a partial class.
  6. Update: 14 Oct 2010 - Multiselect columns are not update-able with multiple values using LINQ to SharePoint.  You can update with 1 value only.
  7. Update 18 Oct 2010 - SPMetal does not like spaces in the url to the site that it generates off. Error the web at 'http://demo.dev/sites/my site' could not be found.
  8. Update 27 Nov 2010 - Using Linq to SharePoint across site collections.  Scope is to the current site collection.

LINQ to SharePoint Posts on this blog
Extending SPMetal for field columns no available to SPMetal by AC (Update) or AC
CAML query for retrieving Publishing HTML and Publishing image columns
Configuring SPMetal default generated code

To see the CAML generated by SPMetal:
StringBuilder sb = new StringBuilder();

System.IO.TextWriter tw = new System.IO.StringWriter(sb);
updatedataContext.Log = tw;
// CAML Query here i.e. var x from customers select customers;
string camlOut = sb.ToString();  // CAML generated.

Update: 09/10/2010 Extend SPMetal to retrieve list attachments

Friday 23 July 2010

SharePoint 2010 Ribbon for Developers

Overview: SP2010 implements the ribbon UI. Ribbon in the same as word 2007 ribbons in that it provides contextual actions that the user can use. This post looks at styling and controlling/extending the ribbons functionality.
Notes:
  • Ribbon is styled using corev4.css, this changes depending on if you apply a theme. css styling starts with "ms-cui" in the css.
  • SPD can add custom actions.
  • Ribbon is controlled by SP file 14\Template\global\xml\CMDUI.xml, this is merged with our custom xml file at run-time to result in an extended ribbon displayed to users.
  • Deploy the custom ribbon xml using a feature.
  • Buttons can be easily added or existing buttons replaced or hidden using XML declaratively to include custom ribbon actions.
  • Ribbon can also be modified programmatically (SPUserCustomAction)

Thursday 22 July 2010

Deploying to GAC vs bin folder in SP 2010

Problem: Do we deploy our to the GAC or the bin directory.

Answer: It depends on what the dll is, who needs to use it and is the SharePoint farm dedicated. You need to understand Code Access Security (CAS). Key point is dlls in the GAC (Global Assembly Cache) have full privileges. dll's in the bin have restricted privileges. You can change the level of permissions for dll's in the bin using CAS policies. SharePoint has 2 policys you can use by default: WSS_Minimal or WSS_Medium (same options as in MOSS). You can also use ASP.NET's policies, there are about 5 of these policies in .NET and the highest level is the "Full Trust" CAS policy. You can also create your own policy. Change the CAS relating to you dll's in the bin via your applications web.config.

Only code that runs in the IIS workprocess can be placed in the bin.  Deploying to the bin minimises permissios but certain tasks such as timer jobs, workflows, service applications and event receivers only work in the GAC.  Deploying to the GAC allows for multiple versions of the dll to exist in the GAC provided versioning is used.  Bin deployment can't have multiple versions.

Note on Sandboxed solutions - runs is the "Microsoft SharePoint Sandboxed Code Service", sandboxed solutions have restricted rights to what it can do. It can permorm basic SP Server side OM's unde the SPSite (Site collection) object under the current SPSite which makes sense. Sandboxed code is deployed to the solutions gallery under the current SPSite. You can also use sandboxed solutions with code proxyies to achieve higher rights operations.  So as you can see sandboxed solutions do not go into the GAC or the bin and CAS is not an issue.  Real option is between GAC + using a Sandbox solution.

Sandbox solutions are good in restricted high usage environments as they allow SharePoint Administrators to validate (manually and via solution validators) the code being uploaded.  Developers are limited in what they can do to the environment.  The counter stop inefficient code once the threshold has been passed.  Administrators can monitor sandboxed solutions to easily identify poorly performing code.

My general rule is: Deploy my custom code to the GAC except if it's not trusted i.e. 3rd party code or there is a business reason/policy not to. It makes dev easier but is not ideal in that best practice decitates that you should apply the minimal levels of security permissions to your code.
Additional Info: Microsoft SharePoint Team Blog on application development.
Great blog on sandboxed solutions