Monday, January 11, 2010

Custom Properties In SharePoint Custom Field Type

There are quite a lot of discussions in Internet regarding how to create custom field type in SharePoint with custom properties. Some are not working and some are way more too complicated.

I found the best and the easiest way to do this is use WSPBuilder which can be downloaded at http://wspbuilder.codeplex.com. It's a free tool for SharePoint and it simplifies the SharePoint development.

Once WSPBuilder is installed, Visual Studio 2005/2008 will include WSPBuilder extension menu context. To create a custom field type, first you create a WSPBuilder project, and right click the project to add a new item of "Custom Field Type"; then all those the field control, field editor control, field type definition xml, and field type classes, are all well created in certain folder. Under the FieldTypeCode folder, there's a CustomFieldType.cs class where the custom field type is defined. This field type class also includes a custom property. In order to add a new custom property, simply add a regular .NET property and add the its names to a static string array named "CustomPropertyNames", then all done! It works like a charm.

Carsten Keutmann is the creator of WSPBuilder. He seems to have very deep understanding of SharePoint. Another very popular free SharePoint utility, SharePoint Manager 2007, is also written by him. Microsoft really should consider to hire such genius people from the community.

The default CustomeFiledTyp.cs generated by WSPBuilder:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace WSPBuilderProject1
{
public class CustomFieldType1 : SPFieldText
{
private static string[] CustomPropertyNames = new string[] { "MyCustomProperty" };

public CustomFieldType1(SPFieldCollection fields, string fieldName)
: base(fields, fieldName)
{
InitProperties();
}

public CustomFieldType1(SPFieldCollection fields, string typeName, string displayName)
: base(fields, typeName, displayName)
{
InitProperties();
}

#region Property storage and bug workarounds - do not edit

/// <summary>
/// Indicates that the field is being created rather than edited. This is necessary to
/// work around some bugs in field creation.
/// </summary>
public bool IsNew
{
get { return _IsNew; }
set { _IsNew = value; }
}
private bool _IsNew = false;

/// <summary>
/// Backing fields for custom properties. Using a dictionary to make it easier to abstract
/// details of working around SharePoint bugs.
/// </summary>
private Dictionary<string, string> CustomProperties = new Dictionary<string, string>();

/// <summary>
/// Static store to transfer custom properties between instances. This is needed to allow
/// correct saving of custom properties when a field is created - the custom property
/// implementation is not used by any out of box SharePoint features so is really buggy.
/// </summary>
private static Dictionary<string, string> CustomPropertiesForNewFields = new Dictionary<string, string>();

/// <summary>
/// Initialise backing fields from base property store
/// </summary>
private void InitProperties()
{
foreach (string propertyName in CustomPropertyNames)
{
CustomProperties[propertyName] = base.GetCustomProperty(propertyName) + "";
}
}

/// <summary>
/// Take properties from either the backing fields or the static store and
/// put them in the base property store
/// </summary>
private void SaveProperties()
{
foreach (string propertyName in CustomPropertyNames)
{
base.SetCustomProperty(propertyName, GetCustomProperty(propertyName));
}
}

/// <summary>
/// Get an identifier for the field being added/edited that will be unique even if
/// another user is editing a property of the same name.
/// </summary>
/// <param name="propertyName"></param>
/// <returns></returns>
private string GetCacheKey(string propertyName)
{
return SPContext.Current.GetHashCode() + "_"
+ (ParentList == null ? "SITE" : ParentList.ID.ToString()) + "_" + propertyName;
}

/// <summary>
/// Replace the buggy base implementation of SetCustomProperty
/// </summary>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
new public void SetCustomProperty(string propertyName, object propertyValue)
{
if (IsNew)
{
// field is being added - need to put property in cache
CustomPropertiesForNewFields[GetCacheKey(propertyName)] = propertyValue + "";
}

CustomProperties[propertyName] = propertyValue + "";
}

/// <summary>
/// Replace the buggy base implementation of GetCustomProperty
/// </summary>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
new public object GetCustomProperty(string propertyName)
{
if (!IsNew && CustomPropertiesForNewFields.ContainsKey(GetCacheKey(propertyName)))
{
string s = CustomPropertiesForNewFields[GetCacheKey(propertyName)];
CustomPropertiesForNewFields.Remove(GetCacheKey(propertyName));
CustomProperties[propertyName] = s;
return s;
}
else
{
return CustomProperties[propertyName];
}
}

/// <summary>
/// Called when a field is created. Without this, update is not called and custom properties
/// are not saved.
/// </summary>
/// <param name="op"></param>
public override void OnAdded(SPAddFieldOptions op)
{
base.OnAdded(op);
Update();
}
#endregion

public override BaseFieldControl FieldRenderingControl
{
get
{
BaseFieldControl fieldControl = new CustomFieldType1Control(this);
fieldControl.FieldName = InternalName;
return fieldControl;
}
}

public override void Update()
{
SaveProperties();
base.Update();
}

public string MyCustomProperty
{
get { return this.GetCustomProperty("MyCustomProperty") + ""; }
set { this.SetCustomProperty("MyCustomProperty", value); }
}
}
}

Saturday, December 19, 2009

WorkflowInvoker in WF 4.0

Just noticed this new and handy class in .NET 4.0 Beta 2. Following is its description on MSDN document:

"Windows Workflow Foundation (WF) provides several methods of hosting workflows. WorkflowInvoker provides a simple way for invoking a workflow as if it were a method call and can be used only for workflows that do not use persistence."

Simple enough, if we just want to invoke a workflow synchronously with current thread (WorkflowInvoker also provides asynchronous versions of the invoke method with InvokeAsync and BeginInvoke), WorkflowInvoker is your best friend, and you don't need to set up the environment for workflow runtime:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Activities;
using System.Activities.Statements;

class Program
{
static void Main(string[] args)
{
Activity activity = new WriteLine() { Text = "Workflow running at " + DateTime.Now.ToString() };
WorkflowInvoker.Invoke(activity);
Console.ReadLine();
}
}
For long running workflows or persistence scenarios, .NET 4.0 also added a new WorkflowApplication class, which provides a richer model for executing workflows that includes notification of lifecycle events, execution control, bookmark resumption, and persistence. Details refer to http://msdn.microsoft.com/en-us/library/system.activities.workflowapplication.aspx.

Friday, December 11, 2009

New DynamicObject In .NET 4.0

Microsoft has released SharePoint 2010 Beta2 and .NET 4.0 Beta2 recently (Ironically SharePoint 2010 is still based on .NET 3.5).

The new Dynamic type in .NET 4.0 looks quite interesting. Not like .NET 3.5 dynamic variable (var keyword) which is static type inference by compiler, Dynamic objects are run-time behavior. Following code example is copied from MSDN documentation, and comments are removed for brevity reason:
using System;
using System.Collections.Generic;
using System.Dynamic;

public class DynamicDictionary : DynamicObject
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
public int Count { get { return dictionary.Count; }}

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
string name = binder.Name.ToLower();
return dictionary.TryGetValue(name, out result);
}

public override bool TrySetMember(SetMemberBinder binder, object value)
{
dictionary[binder.Name.ToLower()] = value;
return true;
}
}

class Program
{
static void Main(string[] args)
{
dynamic person = new DynamicDictionary();
person.FirstName = "Ellen";
person.LastName = "Adams";

Console.WriteLine(person.firstname + " " + person.lastname);
Console.WriteLine( "Number of dynamic properties:" + person.Count);
Console.Read();
}
}
The result is:
Ellen Adams
Number of dynamic properties:2

Thursday, December 03, 2009

SharePoint Impersonation by SPUser

The SPUser class has a UserToken property that can be passing into the SPSite constructor to impersonate that particular user:
        SPSite contextSite = SPContext.Current.Site;
        SPUser user = contextSite.SystemAccount;
        using (SPSite site = new SPSite(contextSite.ID, user.UserToken))
        {
            using (SPWeb web = site.OpenWeb())
            {
                // Do stuff
            }
        }
Above code snippet impersonates the system account to open a SPSite which is equivalent to:
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    // Do stuff
                }
            }
        });

Tracing IIS 500 Error Using Failed Request Tracing Rules

After extended a SharePoint Web Application I got a 500 server error. There's not related event log and the IIS log shows:
2009-12-02 19:37:21 IP GET / - 10.10.1.11 Jakarta+Commons-HttpClient/3.1 500 19 183 0
The HTTP status code 500.19 for IIS 7.0 is "Configuration data is Invalid.". That's not very helpful and I couldn't find obvious issue in web.config. To see more detailed error message I enabled IIS Failed Request Tracing, where I was able to find out the exact error in configuration file:



So the error is caused by "cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'session'". It looks like the "Session" module has already been registered somewhere by SharePoint when the configuration entries are merged. Change the the web.config from original:
    <add name="Session" type="System.Web.SessionState.SessionStateModule" />
    <remove name="Session" />
to:
    <remove name="Session" />
    <add name="Session" type="System.Web.SessionState.SessionStateModule" />
Then the extended web application works normally.

Saturday, November 28, 2009

Word 2007 Document Processing Using OpenXML

One interesting topic is how to handle Word documents using code. I did a test to export the page content from a page in publishing site's Pages library to a Word 2007 document, and save it to a separate document library with success.

Code:
   /// <summary>
/// Export publishing page's content to Word 2007 document controls
/// Exported documents stored in a separate document library
/// </summary>
/// <param name="sourceItem">A list item from Pages' library</param>
/// <param name="targetList">A document library saves exported Word 2007 documents</param>
public static void ExportPubPageContentToWordDoc(SPListItem sourceItem, SPList targetList)
{
SPDocumentLibrary lib = targetList as SPDocumentLibrary;
if (lib == null)
{
throw new Exception("Target list is not a Document Library type");
}

foreach (SPContentType ctype in lib.ContentTypes)
{
if (ctype.Name.ToLower() != "document" && ctype.Name.ToLower() != "folder")
{
SPFile tempFile = ctype.ResourceFolder.Files[ctype.DocumentTemplate];
using (Stream fileStream = tempFile.OpenBinaryStream())
{
BinaryReader reader = new BinaryReader(fileStream);
MemoryStream memString = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memString);
writer.Write(reader.ReadBytes((int)fileStream.Length));
writer.Flush();
reader.Close();

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memString, true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
IEnumerator<CustomXmlPart> xmlPartEnumerator = mainPart.CustomXmlParts.GetEnumerator();
xmlPartEnumerator.MoveNext();
CustomXmlPart XMLPart = xmlPartEnumerator.Current;

// Create an XML document that matches our structure
XmlDocument doc = new XmlDocument();

// Create some nodes
XmlElement rootNode = doc.CreateElement("propertydata");
XmlElement titleNode = doc.CreateElement("title");
XmlElement body = doc.CreateElement("body");

titleNode.InnerText = GetFieldValueString(sourceItem, "Title");
rootNode.AppendChild(titleNode);
doc.AppendChild(rootNode);

body.InnerText = GetFieldValueString(sourceItem, "Article Body");
rootNode.AppendChild(body);
doc.AppendChild(rootNode);

MemoryStream resultStream = new MemoryStream();
doc.Save(resultStream);
resultStream.Flush();
resultStream.Position = 0;
XMLPart.FeedData(resultStream);

string fileName = sourceItem.File.Name;
if (fileName.IndexOf('.') > 0)
fileName = fileName.Substring(0, fileName.LastIndexOf('.'));
fileName += ".docx";
string docUrl = lib.RootFolder.Url + "/" + fileName;
SPFile newDoc = lib.RootFolder.Files.Add(docUrl, memString, true);
lib.Update();
}
}
}
}
}
OpenXML SKD 2.0 (http://www.microsoft.com/downloads/details.aspx?FamilyId=C6E744E5-36E9-45F5-8D8C-331DF206E0D0&displaylang=en) is required to run above code. Word 2007 Content Control tool-kit (http://dbe.codeplex.com/) is handy to manipulate Word 2007 documents'XML, and I used it to create the document library template file.

Good references on this topic:
http://blogs.msdn.com/mikeormond/archive/2008/06/20/word-2007-content-controls-databinding-and-schema-validation.aspx
http://www.craigmurphy.com/blog/?p=913
http://www.microsoft.com/uk/msdn/screencasts/screencast/236/Word-2007-Content-Controls-and-Schema-Validation.aspx

Sunday, November 22, 2009

SharePoint Content Type And Word Template

One nice feature in SharePoint is that the SharePoint content type and its Word template can be cooperating together. The content type field values could be treated as metadata and is injected to its Word 2007 document template as document properties. These document properties can be viewed in Word’s information panel (enable it by Word 2007 setting Prepare->Properties). User can update these properties directly in information panel and upload the Word document back to SharePoint Document Library. The SharePoint list item’s corresponding fields will be updated automatically. The steps are:
  1. Create an empty Word 2007 template.
  2. Create a new Content Type by “Site Actions > Site Settings > Site Content Types > Create”, select “Document Content types – Document” as parent.
  3. Add required fields to the new Content Type.
  4. Upload the Word 2007 template by “Advanced settings > Upload a new document template”.
  5. Create a new Document Library and enable the content type management by “Settings > Advanced settings > Allow management of content types? > Yes”.
  6. Add content type created in step 2 to the document library created in step 5.
  7. Add new document library item by selecting the template created in step 1.
If you don’t like working with Word information panel, you have option to use the Word content controls inside the Word document body to do similar things, and sync the metadata back to SharePoint. We can define the word template in our desire and associate document properties to Word document content controls. Following screen-shot illustrates how document properties can be tied to Word content controls inside Word document, note that Title, Title_fr, Sub_Title, Sub_Title_fr in the example are the Content Type fields inside SharePoint Document Library:


We can also create Word 2007 content controls under developer tab (Ribbon), but there is no direct association between the content controls and document properties if we do so. OpenXML and Word 2007 custom properties techniques are required for Word content automation (SharePoint/Word data binding). I will put more details about this in my next post.

Although SharePoint can generate document properties automatically, not all SharePoint fields are supported by document properties; and not all types of document property are supported by Word content controls. Following table lists mapping of common SharePoint fields and Word 2007 content control:



SharePoint Field Type

Word 2007 Content Control

Single line of text

Text (Not allow carriage returns)

Multiple lines of text

Text (Allow carriage returns)

Choice

Dropdown list

Number

Text with Schema validation

Currency

Text with Schema validation

Date and Time

Date picker

Yes/No

Dropdown list

Lookup

N/A

Person or Group

N/A

Hyperlink or Picture

N/A

Calculated

N/A

Custom filed

N/A



For those SharePoint fields missing World 2007 equivalent content control, we could create a Word content control compatible field in content type, and manually convert the original SharePoint field to that compatible field and versa vise inside list item event receiver. For example, a Text field can be used to map a custom field which is not recognized by Word 2007.

Tuesday, October 27, 2009

Update SharePoint List Column Property Programatically

In order to update a list column (field) property in SharePoint, such as the setting of required or not, we can do the change through the column's setting page from the list's setting page. But some field properties don't display in setting page, and you can't make the change via UI.

Can we update a field property programatically? The answer is yes. For those field properties exposed directly to SPField, the update is simple. Following code sets a list column named "CustomField" to be hidden:
        using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyCustomList"];
list.Fields["CustomField"].Hidden = true;
list.Update();
}
}
If the field property is not exposed to a SPField object, we can also make the change by updating the field's schema XML. SPField has a property called "ShowInNewForm" that determines whether the field shows in the NewForm page (the page to create a new list item). Following code demos how to set a site column not to display in NewForm page:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

class Program
{
static void Main(string[] args)
{
TurnOffFieldInNewForm("http://localhost", "My Custom List", "CustomField");
}


static void TurnOffFieldInNewForm(string siteName, string listName, string fieldName)
{
using (SPSite site = new SPSite(siteName))
{
using (SPWeb web = site.OpenWeb("Team"))
{
SPList list = web.Lists[listName];
string origSchemaXml = web.Fields.GetFieldByInternalName(fieldName).SchemaXml;

string schemaXml = origSchemaXml.Replace("ShowInNewForm=\"TRUE\"", "ShowInNewForm=\"FALSE\"");
if (!schemaXml.Contains("ShowInNewForm="))
{
int index = schemaXml.IndexOf("></Field>");
schemaXml = schemaXml.Substring(0, index) + " ShowInNewForm=\"FALSE\"></Field>";
}

web.Fields.GetFieldByInternalName(fieldName).SchemaXml = schemaXml;
list.Fields.GetFieldByInternalName(fieldName).SchemaXml = schemaXml;
list.Update();
web.Update();
}
}
}
}

Note: updating the site column property doesn't have impact on existing lists that are using that site column, and the update only takes effect for new lists or new referencing to that site column. Because the list column copies the site column's schema xml once when it's first created. So we need to update the list column's property in existing lists separately.

Wednesday, October 14, 2009

JQuery Auto-complete Based On SPList Items In SharePoint Environment

Step 1. Download latest jQuery and jQuery Auto-complete plugin libraries.

Step 2. Included jQuery, auto-complete plugin js and its css files in the Page. This can be done in ASP.NET page, Master page, Control or WebPart:
    if (!Page.ClientScript.IsClientScriptBlockRegistered("jQueryScript"))
{
string path = "<script type='text/javascript' language='javascript'
src='/_layouts/Autocomplete/jQuery.js'></script>"
;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jQueryScript", path);
}
if (!Page.ClientScript.IsClientScriptBlockRegistered("AutocompleteScript"))
{
string path = "<script type='text/javascript' language='javascript'
src='/_layouts/Autocomplete/jquery.autocomplete.js'></script>"
;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "AutocompleteScript", path);
}
if (!Page.ClientScript.IsClientScriptBlockRegistered("AutocompleteCss"))
{
string path = "<link rel='stylesheet' type='text/css'
href='/_layouts/Autocomplete/jquery.autocomplete.css' />"
;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "AutocompleteCss", path);
}

Step 3: Add following script on the page to enable the auto-complete on the textbox (WebUrl, ListName, FieldName need to be set in the code behind, or hard-coded in the script):
<script type="text/javascript">
$(document).ready(function () {
var handlerUrl = "/_layouts/Autocomplete/AutoCompleteHandler.ashx";
var request = handlerUrl + '?WebUrl=<%= WebUrl %>&ListName=<%= ListName %>&FieldName=<%= FieldName %>';
var options = { max: 20, multiple: true, multipleSeparator: ';' };
$("textarea[id='" + '<%= txtBox.ClientID %>' + "']").autocomplete(request, options);

});
</script>

Step 4: Add javascripts, css file, and the auto-complete HttpHandler inside the layout folder (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS\Autocomplete\). The auto-complete HttpHandler includes two parts:

AutoCompleteHandler.ashx:
<%@ Assembly Name="Project assembly fully qualified name" %>
<%@ WebHandler Language="C#" Class="AutoCompleteHandler" %>

AutoCompleteHandler.ashx.cs:
using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

public class AutoCompleteHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string prefixText = string.Empty;
string inputText = context.Request["q"];
string webUrl = context.Request["WebUrl"];
string listName = context.Request["ListName"];
string fieldName = context.Request["FieldName"];
if (!string.IsNullOrEmpty(inputText))
{
int lastDelimiter = inputText.LastIndexOf(";");
lastDelimiter = (lastDelimiter > 0) ? lastDelimiter : 0;
prefixText = inputText.Substring(lastDelimiter).TrimStart(new char[] { ',', ';', ' ' });
}
if (string.IsNullOrEmpty(prefixText) || string.IsNullOrEmpty(webUrl)
|| string.IsNullOrEmpty(listName) || string.IsNullOrEmpty(fieldName))
{
return;
}

SendAutoComplete(context, inputText, webUrl, listName, fieldName);
}

private void SendAutoComplete(
HttpContext context,
string prefixText,
string webUrl,
string listName,
string fieldName)
{
List<string> nameList = new List<string>();
try
{
SPList list = SPListHeler.GetList(webUrl, listName);
if (list != null)
{
SPQuery spQuery = new SPQuery();
string query = @"<Where><BeginsWith>
<FieldRef Name='$NAME$'/>
<Value Type='Text'>$TEXT$</Value>
</BeginsWith></Where>"
;
spQuery.Query = query.Replace("$NAME$", fieldName).Replace("$TEXT$", prefixText);
int limit;
if (int.TryParse(context.Request["limit"], out limit) && limit > 0)
spQuery.RowLimit = (uint)limit;
SPListItemCollection items = list.GetItems(spQuery);
foreach (SPListItem item in items)
{
nameList.Add(item[fieldName].ToString());
}
}

nameList.Sort();
StringBuilder sb = new StringBuilder();
foreach (string tag in nameList)
{
sb.Append(tag + Environment.NewLine);
}

context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "text/plain";
context.Response.Write(sb.ToString() + " ");
}
catch (Exception ex)
{
// Log error
}
}

public bool IsReusable
{
get { return false; }
}
}

Note: To improve the performance, we can cache all the names and query the memory objects inside the http handler instead of CAML query each time.

Wednesday, October 07, 2009

SharePoint InputFormTextBox Validation

RequiredFieldValidator can not work with SharePoint InputFormTextBox. You have to client side JavaScript validation instead. There's an out-of-box function RTE_GetRichEditTextOnly come handy to retrieve the value from InputFormTextBox when doing JavaScript validation:
function ValidateInputFormTextbox() {
    var inputText = RTE_GetRichEditTextOnly("<%= inputControl.ClientID %>");
    if (inputText)
        return true;
    else
        return false;
}