Aptillon Blog

Using PowerShell to create new sites based on site-scoped WebTemplates

Posted by Maurice Prather

WebTemplates are definitely a powerful new construct in our SharePoint 2010 toolbox.  WebTemplates definitely come in handy as they can be deployed as sandbox-compatible features.

Creating a site based on a web template is pretty straightforward via the UI. Basically it just shows up as another site template option. As a user creating a site, you’d never the know the difference between a farm-scoped or site-scoped WebTemplate. However, if you want to use PowerShell, you will notice that your PS scripts will take on a slightly different shape based on how the WebTemplate is scoped.

If the WebTemplate is deployed as a farm-scoped feature, then you can easily use New-SPWeb in the following manner:

new-spweb $url –template “{GUID}#WebTemplateName”


where GUID represents the parent feature ID.

If the WebTemplate is deployed as a site-scoped feature, then your PowerShell needs to be adjusted.  Otherwise, if you attempt to use new-spweb, you’ll get the following error message: Template is not found and is not applied.  This effectively means the cmdlet could not locate a farm-level template to apply to the new site.

For example...



There are two ways to circumvent this problem:

  1. Once the site is created, call ApplyWebTemplate
  2. Before the site created, grab a reference to the appropriate WebTemplate and provide it as a value to the SPWebCollection.Add method on the parent site.


Calling ApplyWebTemplate

$url = "http://sitecollection/site1"

$w = new-spweb $url



Calling SPWebCollection.Add

$url = "http://sitecollection"

$w = get-spweb $url

$template = $w.GetAvailableWebTemplates(1033) | ? { $_.name -eq "{GUID}#WebTemplateName" }

$w.Webs.Add("site1", "sample site 1", "sample description", 1033, $template, $false, $false)


The difference between the two methods basically boils down to the language selection for the new site. With the simple call to ApplyWebTemplate, the new site uses the same language as the parent. By grabbing the reference to the web template beforehand, you have more control.



SharePoint Conference 2011 Wrap Up

Posted by Maurice Prather

This year’s SharePoint Conference was probably one of the most interesting conferences that Microsoft has hosted in the past few years.  The attendance was solid and presentations covered the spectrum from 101 fundamentals over all the way over to nitty-gritty details.

Monday morning I had a chance to present on managing the Sandboxed Code Service (SP376).  I was a little skeptical that we’d fill a room with 700 seats, but I was very pleasantly surprised to see the room fill up before we switched on the microphone.  There were a ton of good questions afterwards as well.  Thanks to everyone who attended and posted all the great messages on Twitter. If you have any questions I was unable to answer, please feel free to reach out.

The conference was also a great chance to run into folks.  I saw many old friends – some that I haven’t seen literally in years – as well as many clients and former Critical Path Training admin and dev students.  It’s always amazing to see the positive energy!

The Aptillon team also had record number of presentations at the conference.  We had 7 presentations by 6 different teammates.  As a company partner, that is definitely very cool stat however the nicer fact is that we had a chance to hang out.  Since we’re spread out all over the US and constantly on the go, it’s rare to have more than 2 people in the same room at the same time. 

There was also a record number of Microsoft Certified Masters from across the globe at the conference.  How cool is that?  I remember the days when Spence and I were the only MCMs who weren’t employed by Microsoft. :) MSL also announced a new certification – Microsoft Certified Architect.  It’s really nice to see program growing!

Great conversations all around. New projects, new ideas, confirmation of design decisions... chatting about the sandbox, helping folks get a better perspectives on PowerPivot and it’s amazing potential, the cloud, getting out of the sandbox (aka azure), Windows Phone 7, watching cloud-servicing applications such as Sharevolution hit their stride, building new partnerships... truly exciting stuff!



CKS:API Beta 3 Release Notes

Posted by David Mann

CKS Beta 3 launched this week to go along with my session at the SharePoint Conference.  I really wanted this to be a production-ready 1.0 release and I think it’s close, but I’d like to have feedback from more folks to make sure I haven’t overlooked things.  There’s still some tightening up I’d like to do and a few rough spots in the code but nothing too bad.  I’ll get them cleaned up soon, too.  I’d really like some feedback, though, so please kick the tires and let me know what you think.

What is CKS:API?

CKS:API is a library for use by developers to address the cross-cutting concerns of logging, instrumentation, exception handling and code contract support.  It is a library for use, not a standalone, fully-baked product.  Full source code is available on the Codeplex site: cksapi.codeplex.com

New Functionality

Using CKS:API hasn’t changed much since the beta 2 release.  There have been a few additions that I’ll cover here.  For information on other functionality, please see the beta 2 release notes.  I’ll also include a detailed usage walkthrough here to help you test things out.  But first, the new stuff:

  1. Logging functionality - a couple of new methods have been added to the logging classes:
    • DumpVariablesInDebug/DumpVariablesInRelease: Two similar methods, any calls to the former get removed by the compiler when you compile a Release build so they are not included in your production code.  Feel free to use it liberally.  Calls to the latter are not removed from your production code so they will execute and could slow things down if overused.  Just be careful.  In a nutshell, these two calls allow you to write information about your variables to your log (farm or sandbox) at any point in your code.  See below for a usage example.
    • WriteElapsedTimeStart/WriteElapsedTimeStop: another pair of related methods.  They allow you to log timings for arbitrary events in your code.  You call the first at the beginning of something you want to time and pass in a descriptive name.  You get back an ID.  call the second at the event of the event you want timed and pass in the ID.  The timing information will be written out to the log.
    • Monitor: This new method is related to the above two.  It gives you that ability to record timing information to the log.  The difference is that in Farm solutions, this will use SPMonitoredScope whereas in Sandbox Solutions, this will use the above two methods, since SPMonitoredScope is not available in the Sandbox.  I would expect that this would be used more often, with the above two coming into play only when you need more control or there isn’t an appropriate delegate for your needs). 
    • Sandbox Logging Configuration: You can now control the amount of information written to the sandbox log by setting a property called “CKSAPI_LogLevel” on the RootFolder of the SandboxLoggingList.  The SandBoxLogger checks this property to determine whether to add each entry to the log.  The SandboxTest project includes a rudimentary webpart that allows you to set this value.  I’d like to clean this area up a bit before the final release. It is critically important to use this efficiently to avoid using too many resources in your sandbox solutions.
  2. SPDisposeCheck Integration: I was running SPDisposeCheck against the code previously to check for Dispose problems, but now its fully integrated and I’m using the SPDisposeCheckIgnore attribute as appropriate to avoid false positives.
  3. Office365/SharePoint Online: For the first time with this release I started testing against Office 365.  Previously I was testing only in my local development sandbox.  I started using the Office 365 FxCop tools from Codeplex (http://o365fxcoprules.codeplex.com/) to validate that my code would run in Office 365 and found that there were a few items I needed to change in the code.  I came across a couple of additional situations where Office 365 would choke on the code and I’m working with Kimmo Forss (the author of the rules project) to get my updates included in the Codeplex project.
  4. NotifyAdministrators – it is now possible to create an entry in a separate SharePoint list for events that happen in your processes.  Combine this with SharePoint’s support for alerts/notifications and you now have an easy way to notify administrators (or really anyone) of an event happening in your code that they may need to know about.

Other than that, there was more cleanup and tightening of the code.  As I mentioned, there’s still more to go here.

CKS:API Usage Walkthrough

To begin working with CKS:API there are a couple of steps that you need to take.  I’ve tried to keep these as few as possible. 

  1. Include the CKS:API assemblies in your package so that they get deployed.  The CKSAPI assembly is required for all projects, you’ll also need either CKS.FarmInstrumentation.dll or CKS.SandboxInstrumentation.dll


  2. Add References to the appropriate DLLs in Visual Studio
  3. Now we need to add code to initialize our logging environment.  For all projects, add code similar to the following to a Site Collection scoped Feature:


  4. For Farm Solutions only, add code similar to the following to a Farm-scoped Feature:


  5. Add the following using statements to your code:
    • image 
  6. Now you can start using CKS:API in your code.  See the sections below for details on the various pieces of functionality and how you can use them.

Simple Logging

Writing to the logs for either Sandbox or Farm solutions is simply a matter of making a call to either of the Write overrides:


The former is obviously quicker – all you need to do is specify the actual message to be written.  It will written to the log with a category of “General” and a severity of “Information”.

The latter override allows you to specify a category and a severity.  The CKSLoggingCategory enumeration defines 58 different categories currently and you can add more if the ones I’ve provided don’t meet your needs.  Examine the CKSLoggingCategory.cs file for the existing values.  (By adding new items to the enumeration, they will be included in the Central Administration “Manage Diagnostic Logging” facility – more on that later). 

The LoggingSeverity enumeration defines 5 possible values: Information, Timings, Warning, Error, Critical Error.  They are used to control when information is written to logs, according to how the logging is configured in your environment.

Farm logging writes to either the ULS or the WIndows Event Log. Sandbox logging writes to a standard SharePoint list created in the root of the site collection.

Logging in the Sandbox

If you’re working in the Farm, there’s nothing you need to do to prepare for logging.  The above will suffice.  Sandbox logging is a bit different, though.  In order to maintain performance and reduce the Resource impact of running this code in the Sandbox, we batch the sandbox log entries in a List<string> variable and flush them out to the SharePoint list.  In order to support this, we need to tell the logger to begin and end our batch.  We do this with calls to <SandboxLogger>.BeginScope() and <SandboxLogger>.EndScope().  My recommendation is to put these calls in your page/control lifecycle events as opposed to putting them in each method:



Instrumentation sits on top of logging.  Logging is simply a facility for recording data.  Instrumentation is the capturing of data that will be meaningful when analyzing or debugging your code.  CKS:API provides several facilities for supporting instrumentation:

Dumping Variables

When debugging your application, it is often useful to know the values of some variables when an exception happened.  The two methods DumpVariablesInDebug and DumpVariablesInRelease allow us to do this.  See the beginning of this post for the difference between these tow methods.  Using them works exactly the same, though:


You make the call to the DumpVariablesInxxx method and pass in a collection of CKSVariableWrapper objects.  The CKSVariableWrapper object allows you to specify:

  • the name of the variable (
  • the current value of the variable
  • (optionally) a string collection of property names on an object variable that you want to dump.

In the code snippet above, we’re dumping three variables: AN SPList, a string and an Int.  For the SPList, we’re explicitly stating that we want to dump out the values of the Title, ItemCount and CanReceiveEMail properties.  For the string and int variables, there are no properties to dump, so we simply dump out the values of these variables.  The end result of this call is:



Another common need when debugging is to know how long certain pieces of my code are taking to run.  While most of the time, we would want to do this with our full Load Tests (and we all do load testing, right?), there are still times when we want to see some basic timing information in regular runs of our code.  CKS:API provides for this.  Begin timing by creating a GUID variable and calling the logger.WriteElapsedTimeStart method.  You pass in a string value that uniquely identifies the particular event/events you want to time.  You get back a unique identifier that identifies this timing instance.  Ending a timing requires you to call logger.WriteElapsedTimeEnd and pass in the GUID you got back previously.  CKS:API will now record the elapsed time between your start call and your end call.

Here’s the code:


And here’s the end result in my logger (the ULS log is shown, the sandbox log would be similar):


Debug Logging

We’re interested in different information when we’re actively coding and debugging our code than when we’re running that code in production.  We potentially want to see a lot more detail about our running processes than what we want to have logged in production.  However, we don’t want to have to go through and rip out all of that extra logging before compiling a Release build.  Instead, we take advantage of Visual Studio’s conditional compilation functionality to have the code excluded when we compile in Release mode. The following methods make use of this:

  1. Logging Method details: WriteDebugMethodStart and WriteDebugMethodEnd work in conjunction to log when we entered and exited a method.  Using them is simple:


    And results in logging entries like these:


  2. Logging Debug messages: The WriteDebug method allows you to add messages to the log in a Debug build but the call is stripped out in Release build so the code never executes:


One comment about all of the debug methods – it is possible to use the normal Debug.Write calls in Visual Studio to achieve a similar end.  The reason this functionality exists in CKS:API is that it allows you to have all of your logging in one place, along with the out of the box SharePoint log entries (in the case of the Farm logger).  I find that a little easier than having some information in my log and some in the Visual Studio debug window.

Exception Handling

The Exception Handling in CKS:API hasn’t changed at its core, but the approach developers take to it has changed a bit in this release.  Before looking at the developer experience, here’s a quick refresher on the user experience:

Users will either see this:


or this:


depending on what the developer does.  In the background, a much more detailed error message is written to the logs.

New in this release is that developers can now override the color of the status bar and the text that shows up on the status bar.  If they don’t provide values for them, defaults are used.

Developers can make use of the Exception library in CKS:API as follows:


They can catch any type of Exception and process it via this mechanism.  In the initialization code for the CKSExceptionDetails object, the developer can specify:

  • The Display (shown): can be Dialog, StatusBar or None
  • The control that threw the exception
  • The category with which to classify the error – using the CKSLoggingCategory enumeration discussed above
  • The severity of the exception – using the LoggingSeverity enumeration discussed above
  • The StatusBarColor – using the CKSStatusBarColor enumeration
  • The User Text – override the default friendly error message shown to the user.

Code Contracts

CKS:API includes a rudimentary implementation of code contracts. It is not nearly as robust as what is available in .NET4, but it will help get you to start thinking that way.  The implementation of Code Contracts didn’t change in this release.  One thing I would like to do before releasing a 1.0 release is to use the Code Contracts more throughout CKS:API.  Right now, usage is a little spotty.

Code Contracts allow you to explicitly state what your software requires in order to operate properly. For CKS:API, this integrates with the Exception handling functionality to throw a specific error if the contract requirements are not met. This is implemented as a control class along with a bunch of validations, which are implemented as extension methods on various objects in the .Net framework.

In general, using a code contract consists of calling the RequiresThat method of the CodeContract class and supplying a condition to be checked. For example, the following code will ensure that the variable pageName is not null or an empty string:


    The comparison is functionally equivalent to


    but by using the code contract, we also get the exception handling built in as well as opportunities for additional logging if we so desire. Preliminary performance testing indicates that the first usage of a code contract is marginally slower than the equivalent code (due to the loading of the additional assembly?) but subsequent usage in a request incurs no performance hit.

    If the contract is not satisfied, we will get a log entry similar to the following (in a Farm Solution):


    (You would get a similar log entry in a Sandbox solution.) Because we’re using the exception framework in CKS:API, the user sees a nice user-friendly message as we saw previously.

    Currently, the following validations are supported as extensions to specific objects:

    String Double & Float Int
    ValidateHasAValue ValidateIsGreaterThanOrEqualTo ValidateIsOdd
    ValidateIsShorterThanOrEqualTo ValidateIsLessThanOrEqualTo ValidateIsEven
    ValidateIsLongerThanOrEqualTo ValidateIsGreaterThan ValidateIsGreaterThanOrEqualTo
    ValidateIsLongerThan ValidateIsLessThan ValidateIsLessThanOrEqualTo
    ValidateDoesNotContain ValidateIsEqualTo ValidateIsGreaterThan
    ValidateContains ValidateIsNotEqualTo ValidateIsLessThan
    ValidateDoesNotEndWith   ValidateIsEqualTo
    ValidateEndsWith Object ValidateIsNotEqualTo
    ValidateDoesNotBeginWith ValidateIsNotType<T>  
    ValidateBeginsWith ValidateIsType<T> IEnumerable
    ValidateIsExactLength ValidateIsNull ValidateAllAreNotNull
    ValidateIsShorterThan ValidateIsEqualTo ValidateAnyAreNull
    ValidateIsNotExactLength ValidateIsNotEqualTo  

    Question: Each validation currently begins with the prefix “Validation” which makes them easily discoverable, but personally I don’t like what it does to the code readability – it makes the code stilted. What do you think – keep the prefix or drop it?

    There is also a related piece of functionality in the Code Contract part of CKS:API – the ability to simply perform a check of a validation without throwing the error:

    Check.ThatAllAreNotNull(SPContext.Current, myVar, myVar2)

    This makes use of the same contract framework, but instead of throwing an error, it simply returns a boolean true if the check passes, or false if it fails. All of the same validations are supported.


    That pretty much closes out the CKS:API Beta 3 Release notes.  I would like to publish a 1.0 production-ready release by the end of October, so please give it a whirl and let me know any feedback – good or bad.


    Remember that this is a beta, but please post any issues to the Issue Tracker on Codeplex, or any questions to the Discussion forum


    Various pieces of the CKS:API functionality would not have been possible if various members of the SharePoint community had not shared their work.  Thanks to the following folks for their help, it really helped me to finalize a couple of the tricky bits, especially related to some of the intricacies of the SPDiagnosticsServiceBase:

    1. Andrew Connell

    2. Todd Carter

    4. Jürgen Bäurle

    5. Andy Burns

    I need to dig up the links to their blogs/articles and will get them posted here in a quick edit soon (I’m trying to get this post pushed out before my SPC session so I’m a little short on time Sad smile ).

    Filed under: Uncategorized
    To post a comment, view the original posting.