May 27 2010

Creating a Custom Metadata Editor Plugin for Colligo for SharePoint

Category: SharePoint, TechnologyAdam Toth @ 2:07 pm

Just wrapped up a project developing a custom metadata editor to plugin to the Colligo Contributor for SharePoint client.

If you aren’t familiar with Colligo, it’s a desktop client application/outlook add-in/explorer file manager, that enables users to save documents or emails directly to SharePoint, and be prompted for metadata at the time of saving.

Colligo reads the content type of the target lists/libraries, and generates a default form very similar to what SharePoint does with the default EditForm.aspx ListForm web part. If you don’t like the default form, or need to customize the metadata entry experience (for example custom validation, pulling from external data sources, inter-dependent controls), you can develop a custom editor and show your own Windows Forms-based form to the user.

Colligo default editor form
The default Colligo Editor form, shown here when adding a new Announcement.

How to Start

To start developing a custom editor, begin by installing Colligo Contributor, and obtaining your product and sdk keys from Colligo.

Create a new Visual Studio Class Library project, and add a reference to the Colligo dlls in the GAC.

Add the necessary using statements:

using Colligo;

using Colligo.Properties;

using Colligo.Util;

using Colligo.WML.MetaData;

Change your class to inherit from the ICustomEditor class:

namespace MyNamespace

{

    public class MyCustomEditor : ICustomEditor

    {

 

    }

}

Implement the Interface methods:

namespace MyNamespace

{

    public class MyCustomEditor : ICustomEditor

    {

 

        // SDK Key

        private const string SDK_KEY = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX";

 

        #region ICustomEditor Members

 

        public string GetSdkKey()

        {

            return SDK_KEY;

        }

 

        public EditorResult ShowEditor(IEditContext context)

        {

            // Show your form here

 

        }

 

        public ResolveConflictResult ShowResolveConflictDialog(IResolveConflictContext context)

        {

            return ResolveConflictResult.UseDefaultResolveDialog;

        }

 

        #endregion

 

    }

}

In the ShowEditor method, this is where you can create an instance of a Windows Form, and call the ShowDialog method on it. You can also pre-validate and avoid showing your form for situations that are not appropriate.

public EditorResult ShowEditor(IEditContext context)

{

 

    // Check if this is something we care about

    if (!context.List.IsDocumentLibrary)

    {

        return EditorResult.UseDefaultEditor;

    }

    if (!string.Equals(context.List.Name, "Private Documents", StringComparison.CurrentCultureIgnoreCase) &&

        !string.Equals(context.List.Name, "Public Documents", StringComparison.CurrentCultureIgnoreCase))

    {

        return EditorResult.UseDefaultEditor;

    }

 

    // Only show for Create/Edit (use the default Colligo form for Viewing)

    if (context.EditorMode == EditorMode.Create || context.EditorMode == EditorMode.Edit)

    {

        using (myCustomWindowsForm myForm = new myCustomWindowsForm(context))

        {

            DialogResult createResult = DialogResult.None;

 

            createResult = myForm.ShowDialog(context.Parent);

 

            switch (createResult)

            {

                case DialogResult.Cancel:

                    return EditorResult.Cancel;

                case DialogResult.OK:

                    return EditorResult.OK;

                case DialogResult.No:

                    return EditorResult.UseDefaultEditor;

            }

        }

    }

    else

    {

        // View - Show the default editor

        return EditorResult.UseDefaultEditor;

    }

 

    // Fall through

    return EditorResult.OK;

 

}

Notice I am passing in the IEditContext instance into my form’s constructor. The IEditContext object has all the goodies in it, and will give you access to the list, the web, the content types, list item metadata, etc.).

What to Consider

Some basic things to consider are:

  • Which scenarios will your editor cover? View, Create, Edit?
  • Is this only for documents, or list items, or both?
  • Will you support content types? A list/library can be configured with multiple content types, which you will need to create a UI for selecting/changing if you decide to support that.
  • How will you handle multiple files? Will you enable setting different data for each item, or will you force all items to use the same entered metadata? Think carefully about the “Name” field for documents in document libraries. You want to make sure that the same name is not used for multiple documents.
  • Will you allow changing folders (for document libraries with folders enabled)? If so, you’ll need to build this UI.

There are a number of ways/methods that may kick off the display of your form, and you need to consider each of these:

  • User selects New > Item from within Colligo Contributor
    • This is similar to the New > [Content Type] menu directly in SharePoint. You can expect that EditorContext.ContentType and EditorContext.ListItems[0].ContentType will not be null.
  • User selects Upload from within Colligo Contributor
    • This is similar to Upload Document from within SharePoint. EditorContext.ContentType and EditorContext.ListItems[0].ContentType may be null.
  • User drags/drops a single file onto Colligo Contributor
    • EditorContext.ContentType and EditorContext.ListItems[0].ContentType may be null.
  • User drags/drops multiple files onto Colligo Contributor
    • EditorContext.ContentType and EditorContext.ListItems[0].ContentType may be null.
  • User performs a single File > Save As from within an application
    • EditorContext.ContentType and EditorContext.ListItems[0].ContentType may be null.
  • User drags/drops multiple files onto the Colligo area in Windows Explorer
    • EditorContext.ContentType and EditorContext.ListItems[0].ContentType may be null.
  • User selects Edit Properties from within Colligo Contributor
    • Need to grab existing values and prepopulate your controls. EditorContext.ContentType and EditorContext.ListItems[0].ContentType will not be null.


Some Gotchas

Following are some gotchas to be aware of:

Check for Null

Don’t make any assumptions about any of the items in the IEditContext object. ContentTypes may be null, Fields may not exist or be null, other relevant ILists in the Web may not be synchronized locally, and will be null, etc., etc., etc. Check everything for null first, and test everything that returns a collection/array for Count and Length > 0. If there are fields/lists/lookup column values that your form expects, check for the existence of these things right away, and exit if you don’t find them.

Parent Windows

If your form is called via the Save As dialog from an application (or via the FileManager), the ParentWindow handle may not be valid, so be careful with the ShowDialog(IWin32Window) overload, which threw a System.ComponentModel.Win32Exception for me. I had to wrap my ShowDialog(context.Parent) in a try>catch, and then try it without any parameters (ShowDialog() ).

Custom Field Types

If you are using any custom field types, be really careful to make sure and store the data in the proper format. My customer was using a couple of custom field types found on CodePlex, and one of them extended the Lookup field, and it took me a few traces with Fiddler to figure out that it wanted its values in lookup column format (“52;#ItemName”);

Site Lookup Columns

If you have any lookup columns that are defined in higher-level sites, and you are using those site columns in lists located in subsites, then Colligo will not be able to see the lookup values. In order to implement these scenarios, you will have to force your users to synchronize the higher level sites as well as the subsites.

Tags: ,


May 26 2010

Filtering XML output of SPListItemCollection using Linq to XML

Category: SharePoint, TechnologyAdam Toth @ 1:57 pm

I’ve been writing a slurry of code to return list item XML so that it can be parsed and consumed by AJAX components on the client side. Since Lists.asmx does not work in anonymous access scenarios, I’ve been creating many proxy .ashx Http Handlers installed in the LAYOUTS directory, to query via the object model and return the XML of the list items, using the .Xml property of a SPListItemCollection.

I had one particular scenario where I couldn’t pre-filter the items in the collection with an SPQuery object (too complicated a query for CAML), so I needed a way to filter the SPListItemCollection afterwards using C#, before returning the XML.

The SPListItemCollection offers the .Delete() and .DeleteItemById() methods, however they will commit the deletion back to SharePoint. I wanted to simply remove some items from the in-memory collection, not delete the items from the server. There was no way that I could see to remove items from an SPListItemCollection in memory only.

I looked into sub-classing or extending the SPListItemCollection class, but there is no public constructor in the base class, and no way to get at the logic behind the .Xml property without nasty reflection.

I ultimately ended up resorting to using Linq to XML to delete the rows directly from the returned XML, and then adjusted the ItemCount accordingly.

Here’s the code:

// Get the list items from a list

SPListItemCollection items = myList.GetItems(mySPQuery);


// Get the xml of the list items

itemXml = surveyItems.Xml;


XNamespace z = "#RowsetSchema";

XDocument xdoc = XDocument.Parse(itemXml);


IEnumerable<XElement> rows = xdoc.Root.Descendants(z + "row");

List<XElement> rowsToDelete = new List<XElement>();


foreach (XElement row in rows)

{

    // Here is where you can test for a condition, and decide to remove a row

    if (row.Attribute("ows_Title").Value.Contains("Some string to filter on"))

    {

        rowsToDelete.Add(row);

    }

}


while (rowsToDelete.Count > 0)

{

    // Update the parent row count

    int rowCount = Convert.ToInt32(rowsToDelete[0].Parent.Attribute("ItemCount").Value);

    rowsToDelete[0].Parent.Attribute("ItemCount").Value = (rowCount - 1).ToString();

    rowsToDelete[0].Remove();

    rowsToDelete.RemoveAt(0);

}


// Get the newly filtered xml

itemXml = xdoc.ToString()

Tags: , , , ,


Jun 25 2009

Review – Accessibility Kit for SharePoint – Half Finished Product?

Category: SharePoint, TechnologyAdam Toth @ 3:29 pm

Rating: ★★☆☆☆

I’m implementing the AKS for a customer, and I’m having a hard time understanding how this product actually made it to a public release. It feels like a product that is half finished, that was used as a springboard to creating a commercial product, while leaving the original free version to the wayside. If you are considering working with this, you might want to read about the frustrations I encountered below:

Installation experience – Where are those .bat files?

When you download the AKS, you’ll get a zip file, which contains a folder and a single EXE installer.

Running the installer will perform the following tasks:

  1. Installs control adapters and reference files into an AKS folder in your Program Files directory.
  2. Copies a feature and master pages/css styles to the /12/Templates/Features folder in your SharePoint installation (if you are running 32 bit).
  3. Creates a Start Menu icon group for AKS tasks and links.

After running through the installer, a quick look at the “Welcome to the Accessibility Kit…” PDF informs you that you need to install and activate the feature:

The AKS Feature
The AKS Feature is not the AKS Kit but a part of the Kit that works as a feature in MOSS. The AKS
Feature installs the Example Master pages and the Modified CSS. You must install this by
selecting Install AKS Feature from the Start Menu:  Start | All Programs | AKS by HiSoftware |
AKS Feature install.  Once the feature is installed, you will still need to activate it within your
SharePoint application through: Site Settings | Site Collection Features. Please note if you are
on a 64 Bit server please follow the 64 Bit instructions.

I looked all over for those “64 bit instructions”, but there was nothing. There was a “64bit Feature Install” icon in the Start Menu, but no text anywhere instructing me to click on it.

I figured out that to install the feature, you need to click on either the 64bit Feature Install icon or the AKS Feature Install icon in the Start menu (note that the shortcuts are only created for the current user, and there is no way to tell the installer to install for everyone). If you run these shortcuts from the Start menu, the command window will flash, execute, and then immediately disappear, before you can check if it finished successfully or not. On a 64 bit server, you’ll see a flash of xcopy commands that copy styles and master pages into the /12 folders.

I wanted to be sure that it installed, so I tried to find the location of the batch file so I could run it again in a command prompt and actually see the result. I right-clicked the shortcut and went to Properties to figure out the target location, and it was greyed out:

image

I looked for the bat file in the Program Files directory, but no luck. Yuck! A .bat file that I can’t see or easily get to?

I figured out that it installed, because I then saw the feature in my Site Collection Features page. I activated it, and then tried to take a look at the master pages and styles.

Control Adapters – Incorrect C#

The AKS comes with several control adapters that rewrite some of the out-of-box control html to make it more compliant. Some of the C# adapter files have mistakes in the C# code that make them not able to compile. For example, in the Web Part Zone Smart Adapter for WCAG2.0, there is an extra curly brace, and even a reference to a variable that is not even declared in the file anywhere:

   1: else

   2: {

   3:

   4:     } // <-- Extra brace?

   5:

   6:     //Output sOutputBuilder to be rendered

   7:     oOutput.Write(sOutputBuilder.ToString()); // <-- sOutputBuilder is never declared in this file!

   8: }

“Smart Adapters” (not too bright)

The AKS comes with several “Smart” control adapters (adapters that do not need a lot of configuration). The Web Part Zone Smart Adapter sounded like it had some promise, as it would convert a web part zone to use divs instead of tables.

However, when you install it, it has the side effect of not rendering any of your web part’s “Titles”. If you want to use the headers that come with the web parts, then this control will not work for you. It also prevented viewing web parts in Design mode, they would just disappear from the page.

Finally, it was hard to see the point of using the adapters at all, as all they appeared to do was add some labels to blogs, wikis, and search boxes. They will certainly not do anything at all if you use the CKS EBE or Wiki versions, or if you have customized/branded the search controls.

Master pages and styles do not exist!

Once you install the feature, a set of master pages and css styles will get installed to the master page and style library galleries for your site collection. I cracked open SharePoint designer, tried to open a master page, and got a nasty error message that the file did not exist and could not be opened.

In order to open the file, I had to run through the SharePoint UI, and “Publish” each master page and CSS style before I could access it via SharePoint designer. There was no mention of this anywhere in the documentation.

Relative font sizes? Good luck!

The AKS stylesheets attempt to change all SharePoint font size declarations into relative sizes in ems, rather than fixed pixel/point sizes. This might work fine for anonymous internet site pages, but if you will ever let your visitors view any of the system pages like list new/edit/upload pages or use out-of-box web parts, good luck tweaking styles for a month to get things right.

Woops, what about default.master?

The AKS installs alternate versions of the out-of-box publishing master pages, such as BlueBand.master, BlackBand.master, etc. I don’t know about you, but none of my customers have ever started from those master pages on internet sites, and all my intranet applications make heavy use of default.master. I was really disappointed to see that there was no alternate version of default.master.

HCCE – Nothing but trouble

The HiSoftware Code Compliance Kit (HCCE) is a SharePoint event handler that will look for a certain string of text in your SharePoint web pages, and replace it with different (possibly more accessible) text. You use a text file in which you specify pipe-delimited lines of text to find and replace (e.g. “Text to find|Text to replace with”). The HCCE has the following problems when implemented:

  • There is only a debug build provided (no release version).
  • There is no source code (you cannot recompile).
  • There is no regex option for pattern matching. All strings must be matched and replaced exactly.
  • The DLL looks for a hard-coded path to the configuration text file in C:\Program Files\HiSoftware… This doesn’t work on 64bit systems because the installer installs to Program Files (x86). Since you can’t recompile the DLL, your only option is to copy the text file to the Program Files directory.
  • Once you implement the feature, your SharePoint Welcome menu will get rendered above the <html> tag, causing it to appear at the top of your screen and out of place. Several posts about this, and no response at all from HiSoftware.
  • The install/uninstall .bat files do not work, and need to be adjusted for 64bit machines. Why no WSP?

Conclusion

Poorly documented, sloppily put together, and full of holes and mistakes, I was very disappointed in the AKS. Coupled with a total lack of support and responsiveness to issues on their web site, I think it reflects poorly on HiSoftware as a company.

Tags: , , ,


Jun 15 2009

BDC Picker.aspx QueryString Triggers Firewall Security

Category: SharePoint, TechnologyAdam Toth @ 10:00 am

The implementation of the BDC entity picker dialog (opened with the Browse button) can cause some firewall and security software to think a worm or sql injection attack is happening and block the traffic.

The manner in which properties and entity IDs are encoded into long query string values makes the urls appear to be injection attacks. On a particular client’s BDC application, the picker dialog used a url similar to the following:

http://domainname.org/_layouts/Picker.aspx?MultiSelect=False&CustomProperty=uU2hhcmVQb2ludC5Qb3J0YWwsIFZlcnNpb249MTIuMC4wLAF%2F%2FAQAAAAAAAA9QcmltYXJ5Q29sdW1uSWQQU3lzdGVtSW5zdGFuY2VAAA
AAAMAgAAAF9NaWNyb3NvZnQjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibG
ljS2V5VG9rZW49NzFlOWJjZTExMWU5NDI5YwUBAAAAPk1pYAEAAAD%2F%2F%23Jvc29mdC5TaGFyZVBvaW50LlBvcnRhbC5XZWJDb250cm9scy5JdGVtUGlja2
VyRXh0ZW5kZWREYXRhB
JZAhFbnRpdHlJZBNTZWNvbmRhcnlDb2×1bW
5zSWRzAAAABw8PDw8CAAAANw4AAAcOAAAIDgAACQMAAAAPAwAAAAAAA
AAPCwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
3D&EntitySeparator=%00&DialogTitle=Choose%20User&DialogImage=%2F_layouts%2Fimages%2Fbizpicker.gif&PickerDialogType=Microsoft.SharePoint.Portal.WebControls.ItemPickerDialog%2C%20Microsoft.SharePoint.Portal%2C%20Version%3D12.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3D71e9bce111e9429c&DefaultSearch=

Using the HTTP GET for this kind of thing is a bad idea, and I hope that Microsoft fixes this in the future.

Tags: ,


Apr 23 2009

WSS Script for non-AD Installation

Category: SharePoint, TechnologyAdam Toth @ 9:48 am

Here is a script for configuring WSS 3.0 installation without Active Directory, where SQL Server resides on a separate box:

psconfig -cmd -configdb -create -server DBSERVERNAME -database wss_admin_config -user WSSSERVER\AppPoolAccountName -password p@ssword -dbuser SQLDBUSERNAME -dbpassword p@ssword -admincontentdatabase wss_admin_content

Based on the post here:

http://blogs.msdn.com/fooshen/archive/2007/02/01/installing-moss-without-ad.aspx

Tags: , ,


Apr 15 2009

Spam your own Blog so you can be a SharePoint MVP!

Category: SharePoint, TechnologyAdam Toth @ 9:10 am

Ahh, my rant for today.

With the announcement of the name for the next version of SharePoint on the OFFICIAL SharePoint team blog, I am waiting for the inevitable flood of pingbacks, trackbacks, and reposts about this in my RSS reader. This will be similar to the flood of reposts about “SharePoint Designer is now Free!” I got a week ago. Same goes for the endless stream of tweets and retweets.

Is it really necessary to repost items from the official SharePoint team blog? If you are interested in SharePoint, you should be following this blog already, no?

I think much of this is a direct result of the MVP system and its requirements. When considering candidates for MVP, the quantity of blog posts, page hits, and comments are a big factor. I’ve seen some bloggers with high-quality posts get passed on as MVPs due to low numbers in their web stats. Are some bloggers trying to up their post counts? Is anybody monitoring quality as well as quantity?

I just can’t help but feel that this race to MVP status is encouraging this. Same goes for the MSDN SharePoint forums, where people seem to be falling all over themselves to answer questions as quickly as possible, without providing quality answers or even understanding the questions.

Tags: , ,


Apr 13 2009

SharePoint Field Names have 32 Character Limit – So Do Replicated Profile Property Names

Category: SharePoint, TechnologyAdam Toth @ 9:14 am

I ran into a situation where I created a User Profile Property with the Replicable checkbox set, which had a really long name. There were no errors when saving the profile property, however later on I started receiving errors in the Event Log:

failure trying to synch site [guid] for ContentDB [guid] WebApp [guid].  Exception message was A WSS internal name for profile property ‘ProfilePropertyWithReallyLongName’ could not be found..

Apparently SharePoint has a limit of 32 characters for Internal Field Names. This will also apply to Replicable User Profile Properties since they will get synced down to the WSS Content DB in the UserInfo list.

Tags:


Apr 09 2009

SharePoint May Break Hyperlinks in Workflow Task Emails

Category: SharePoint, TechnologyAdam Toth @ 11:54 am

I ran into an issue where hyperlinks in workflow task emails where being automatically changed by SharePoint from absolute hyperlinks to relative ones.

Scenario:

  1. You create a custom Visual Studio workflow and use the CreateTask activity.
  2. You set your SPWorkflowTaskProperties.Description property to some HTML text.
  3. In your Description HTML text, you have an html hyperlink <a> tag whose href=”” attribute contains an absolute hyperlink to a resource in the same SharePoint farm (i.e. a list item).
  4. Example: “Please review <a href=”http://yourserver/site/lists/yourlist/dispform.aspx?ID=1”>contract #12345</a>”.

Goal:

Users will receive the task email, and be able to click on the absolute URL in the email body to navigate to the SharePoint resource.

Problem:

It appears that SharePoint parses this HTML and readjusts the hyperlink and makes it relative.

Example: “Please review <a href=”/lists/yourlist/dispform.aspx?ID=1”>contract #12345</a>”

This effectively breaks the hyperlink in the email client.

The only workaround was to get rid of the <a> tag and write out the hyperlink in full. For example:

“Please review contract #12345 (http://yourserver/site/lists/yourlist/dispform.aspx?ID=1)”.

In this manner, SharePoint did not adjust the hyperlink at all.

Tags: , ,


Apr 09 2009

BDC Error – Type does not match DotNet type of TypeDescriptor

Category: SharePoint, TechnologyAdam Toth @ 10:36 am

I ran into a BDC error, “Type does not match DotNet type of TypeDescriptor”, with a particular application definition I wrote. In this case, I had a specific finder method that took one input parameter (the identifier) that was of type System.Decimal. It turns out I didn’t specify a default value in the TypeDescriptor for this input parameter in my XML definition. It looks like when you don’t set a default value, it will automatically set one for you and assign it a type of System.String. I was able to see this when I exported the BDC definition fresh, and noticed that SharePoint automatically added this default value and type for me.

Rule of thumb, always specify a default value for each input parameter.

Tags: ,


Apr 03 2009

Workflow Task Locked when AssignedTo Changed to Support Multiple Selections

Category: SharePoint, TechnologyAdam Toth @ 9:53 am

This is an old one, but some co-workers ran into this again recently on a project.

When you have a SharePoint workflow that assigns tasks (either Designer or Visual Studio workflow), when you change the Assigned To column on the task list to allow Multiple Selections, your workflow will hang and become unresponsive when a user edits the task. You’ll receive a message about the task being locked (“This task is currently locked by a running workflow and cannot be edited”). OnTaskChanged events will no longer fire and your workflow will be stuck and unrecoverable.

There is no hotfix or workaround for this, so you simply cannot have the assigned to column support multiple users or groups. Just use a single group instead.

Following are some other resources discussing this:

Tags: , , ,


Next Page »