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]
Using a console application to install an eventhandler
Of course a Feature is the smartest way to register an eventhandler. From the
other side it could be usefull to use a console application to intall an
eventhandler. The eventhandler dll has to be placed into the GAC
(Windows\Assembly). You can use the following code to register your
eventhandler.
namespace EventHandlerInstaller
{
class Program
{
static void Main(string[] args)
{
try
{
SPSite siteCollection = new SPSite("http://myurl/sites/mysite");
SPWeb site = siteCollection.AllWebs[0];
SPList myList;
foreach (SPList l in site.Lists)
{
Console.WriteLine(l.Title);
if (l.Title == "My List")
{
myList = l;
}
}
string assemblyName = "MyHandlers, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=6d2f9de54c53a11d";
string className = "MyHandlers.MyEventHandler";
myList.EventReceivers.Add
(SPEventReceiverType.ItemAdded, assemblyName, className);
SPEventReceiverDefinitionCollection registeredEvents =
myList.EventReceivers;
foreach (SPEventReceiverDefinition def1 in registeredEvents)
{
Console.WriteLine("Succesfully added eventhandler:" +
def1.Type.ToString());
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
[/code]
Generate an autonumber by using an eventhandler
You can generate an autonumber by using an eventhandler.
public class AutoNumberEventHandler : SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
SPListItem item = properties.ListItem;
item["Item Number"] = DateTime.Now.ToString("yyyy") + "-" + item["ID"];
item.Update();
}
}
[/code]
MSDN Event Handlers
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]
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]