Log Exceptions to Default SharePoint LogFile
It's possible to log exceptions using the next codesnippet (MOSS Only). Advantage: exceptions are logged to a single file (i.e. in the 12 hive under the LOGS directory). No extra dll’s are needed to be installed. The only limitation to using the MOSS logger is that you cannot set the log event level e.g. critical, high, medium, low it will always display the error level as high.
catch(Exception myException)
{
Microsoft.Office.Server.Diagnostics.PortalLog.LogString(”Exception
Occurred: {0} || {1}”, myException.Message, myException.StackTrace);
}
The MOSS logger is located in the Microsoft.Office.Server.dll and therefore it is only available with the MOSS install, not WSS 3.0. For more control and flexibility use the Enterprise library logger.
Creating a Publishing page from code
In some cases it could be necessary to create a page from code. Because
the publishing page is the hardest way to create from code (checkin /
approval) the next code example will help you completing this job.
Notice that I skipped complete error handling.
/// <summary>
/// Create a Publishing page based on an excisting Page Layout
/// Remember that a SPSite is a top-level site (collection) and
/// a SPWeb is the current site
/// </summary>
/// <param name="site">Current Site</param>
/// <param name="pageName">Name of the new page to create including .aspx</param>
/// <param name="pageLayoutName">Name of the Page Layout</param>
private void CreatePublishingPage(SPWeb site, string pageName, string pageLayoutName)
{
PublishingSite pubSiteCollection = new PublishingSite(site.Site);
PublishingWeb pubSite = null;
if (pubSiteCollection != null)
{
// Assign an object to the pubSite variable
if (PublishingWeb.IsPublishingWeb(site))
{
pubSite = PublishingWeb.GetPublishingWeb(site);
}
}
// Search for the page layout for creating the new page
PageLayout currentPageLayout = FindPageLayout(pubSiteCollection, pageLayoutName);
// Check or the Page Layout could be found in the collection
// if not (== null, return because the page has to be based on
// an excisting Page Layout
if (currentPageLayout == null)
{
return;
}
PublishingPageCollection pages = pubSite.GetPublishingPages();
PublishingPage newPage = pages.Add(pageName, currentPageLayout);
newPage.Description = pageName.Replace(".aspx", "");
// Here you can set some properties like:
newPage.IncludeInCurrentNavigation = true;
newPage.IncludeInGlobalNavigation = true;
// End of setting properties
SPFile publishFile = newPage.ListItem.File;
publishFile.Update();
newPage.Update();
// Check the file in (a major version)
publishFile.CheckIn("Initial", SPCheckinType.MajorCheckIn);
publishFile.Publish("Initial");
// In case of content approval, approve the file
if (pubSite.PagesList.EnableModeration)
{
publishFile.Approve("Initial");
}
}
/// <summary>
/// Find a page layout in the layoutcollection based on the templatename
/// </summary>
/// <param name="pubSiteCollection">The toplevel publishing site</param>
/// <param name="templateName">Name of the pagelayout</param>
/// <returns>Pagelayout if excists or null</returns>
private PageLayout FindPageLayout(PublishingSite pubSiteCollection, string templateName)
{
PageLayoutCollection plCollection = pubSiteCollection.GetPageLayouts(true);
foreach (Microsoft.SharePoint.Publishing.PageLayout layout in plCollection)
{
// String Comparison based on the Page Layout Name
if (layout.Name.Equals(templateName, StringComparison.InvariantCultureIgnoreCase))
{
return layout;
}
}
return null;
}
[/code]
SharePoint desinger workflow or Visual Studio workflow?
Microsoft developed SharePoint designer original for powerusers and not especially for developers. In SharePoint designer you could easily create a workflow and add them to e.g. a SharePoint library from within the tool. Pretty easy! A lot of developers see this a chance to easy develop a workflow in all situations and don't use VIsual Studio to write all that code. The problem exist by trying to put your solution to another environment (e.g. from development to staging). Since SP Designer directly connects a workflow to a list, it is not easy to deploy it to another environment. You can find some tricks on the internet for changing the id's in the XOML file. But we are professional developers, aren't we? So please think carefully about your decission using SharePoint designer or Visual Studio. Visual Studio gives you the ability to deploy your workflow by a feature. Use SharePoint designer for easy to configure workflows. Use Visual Studio for more complex workflows or solutions which you have to put on different environments.
Adding a List - ListFields and Items from code
Often it is required to insert a list, listitem and listitems from code. An
example is creating a list if it not exists from a Feature or WebPart. By
creating a list we out of the box get the Title field. The next code shows the
process of creating a custom list, columns and items from code. It also shows
how you can change to out-of-the-box Title column.
// Option 1) Inside SharePoint
SPSite siteCollection = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
// Option 2) From an external tool
SPSite siteCollection = new SPSite("http://myurl");
SPWeb site = siteCollection.RootWeb;
// Get a ListCollection from the current site
SPListCollection lists = site.Lists;
// Add a custom List to the SharePoint site
lists.Add("Employee", "List containing employees", SPListTemplateType.GenericList);
// Put the new list in a variable
SPList employeeList = lists["Employee"];
// Get the out of the box fields (Title, Attachment etc)
SPFieldCollection fields = employeeList.Fields;
// Change the default title column
SPField field = fields["Title"];
field.Title = "Name";
// Don't forget the update to commit changes
field.Update();
// Add a new field
SPField fieldAdd = fields[fields.Add("Address", SPFieldType.Text, true)];
SPView view = employeeList.DefaultView;
SPViewFieldCollection viewFields = view.ViewFields;
// Add the field to the defaultview (all items)
viewFields.Add(fieldAdd);
view.Update();
// Add a record to the new list
SPListItem item = employeeList.Items.Add();
item["Name"] = "Name of the Employee";
item["Address"] = "Address of the employee";
item.Update();
[/code]
Sending and Receiving mail in your local development environment
Most developers use a local development environment, often a vpc. Most of them
have trouble sending and receiving mail in Outlook (often used in workflows).
hMailServer is a free Windows emailserver you can install in your local
development environment. Nice to give a demo and have 5 different email accounts
in your Outlook and exciting to see or the workflow sends the email to the right
account. Installed and configured in some easy steps.
Download HMail Server
Find the public key token of an assembly using Strong Name Tool in Visual Studio
- In Visual Studio 2005/2008, click Tools -> External Tools
- Click Add and enter the following fields
- Title: Get Public Key
- Command: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe
- Arguments: -Tp "$(TargetPath)"
- Uncheck all options, except Use Output window
After building the assembly you can get the public key (if signed) by clicking Tools -> Get Public Key
MSDN SN.EXE
Note: On some systems I found the sn.exe tool at the location: C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
Starting a Workflow from an Event Receiver
Out of the Box there are only a few options to start a (custom) workflow. E.g.
when an item is created or changed. This means that there are a lot of
situations that a workflow is fired where it is not needed (often a workflow
only needs to be started if a field has a specific value). Therefore we can
write an event receiver to time better when a workflow is started. Below you
find the code to start a workflow from your event receiver.
[code:c#]
public override void ItemUpdated(SPItemEventProperties properties)
{
if(YourCondition)
{
SPList parentList = properties.ListItem.ParentList;
SPWorkflowAssociation associationTemplate =
parentList.WorkflowAssociations.GetAssociationByName("Workflow Name",
new CultureInfo
(Convert.ToInt32(parentList.ParentWeb.RegionalSettings.LocaleId)));
SPSite siteCollection = properties.ListItem.ParentList.ParentWeb.Site;
siteCollection.WorkflowManager.StartWorkflow(properties.ListItem,
associationTemplate, String.Empty);
}
}
[/code]