Category Archives: SharePoint Development

Simple Explanation: “Value does not fall within the expected range.”

UPDATE: An anonymous poster left a great comment about internal names.  Be sure to read it.

When working with event receivers and other code that references SharePoint list items via the object model, I often make mistakes that generate this error at runtime:

Error loading and running event receiver Conchango.xyzzyEventReceiver in xyzzy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0dc50a750396c3ac. Additional information is below.  : Value does not fall within the expected range.    

I think this is a fairly generic error that is potentially caused many different ways.  However, one simple explanation is that I’m referencing a field incorrectly.  If the name of the field is "Due Date", I must reference it like this in an event receiver:

properties.ListItem["Due Date"]

When I misspell or use the wrong case when referencing the field, SharePoint generates the above mentioned runtime error.  For example, this is wrong:

properties.ListItem["due Date"]

</end>

Subscribe to my blog.

Technorati Tags:

Quick & Easy: Create a Folder and Assign a Content Type (Or, Have Your KPIs and Eat Them Too)

In order to work around a KPI problem I wrote about here, I did some testing and discovered that KPI’s work against folders with meta data in the same way that they work against documents or list items.   I proved it out by creating a new content type based on the folder content type and then added a few fields.  I created some indicators and proved to myself that KPIs work as expected.  This was welcome news.  It’s not perfect, because the drill-down you get from the KPI against the folders is not exactly what you want.  This isn’t too much a drawback in my case because 1) the end users don’t know any better and 2) the drill-down goes to a folder.  They click the folder name and they are at the item.  It’s two clicks instead of one, which isn’t the end of the world.

This flowed nicely with the work I was doing.  I am creating a folder for every document that gets uploaded.  This is done via an event receiver.  As a result, it’s a piece of cake to keep the parent folder’s meta data in sync with the KPI-driven meta data from the file itself since the plumbing is already in place.  This allows me to have my KPI’s and eat them too 🙂

I modified the event receiver to add the folder and then set this new folder’s content type to my custom KPI-friendly content type.  This bit of code did the trick:

 SPFolderCollection srcFolders = targetWeb.GetFolder("Documents").SubFolders;
  SPFolder addedFolder = srcFolders.Add(properties.ListItem.ID.ToString());
  SPContentTypeId kpiCT = new SPContentTypeId("0x0120002A666CAA9176DC4AA8CBAA9DC6B4039F");
  addedFolder.Item["Content Type ID"] = kpiCT;
  addedFolder.Item.Update();

To locate the actual Content Type ID, I accessed that content type via site settings and copy/pasted it from the URL as shown:

image

</end>

Subscribe to my blog!

Technorati Tags: ,

Quick and Easy: Get the SPFolder of an SPListItem in an Event Receiver

I hate to admit it, but I struggled with this one all day.  My event receiver needs to update a field of its parent folder.  This little bit shows how to do it:

        private void UpdateParentFolder(SPItemEventProperties properties)
        {

            SPFolder thisItemFolder = properties.ListItem.File.ParentFolder;
            thisItemFolder.Item["ZZ Approval Status"] = "Good news, everyone!";
            thisItemFolder.Item.Update();
           
           
        } // UpdateParentFolder

In this case, I’m working with a document library and the properties are coming from an ItemAdded event.

The trick is that you can’t get the SPFolder of the item directly from the item itself (i.e. properties.ListItem.Folder is null).  Instead, go to the list item’s associated File and get the File’s folder.

</end>

 Subscribe to my blog!

Technorati Tags:

Yet Another Event Receiver Debug Trick

I’m sure I’m not the first person to come up with this.  However, I haven’t noticed anyone publish a trick like this since I started paying close attention to the community last July.  So, I thought I’d post it this quick and easy debug tip.

I’m working on an event receiver that started to generate this error in the 12 hive:

Error loading and running event receiver Conchango.xyzzyEventReceiver in xyzzy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=blahbalhbalh. Additional information is below.  : Object reference not set to an instance of an object.    

I didn’t know where I had introduced this bug because I had done too many things in one of my code/deploy/test cycles. 

I tried this solution to get my pdb in there with hopes that SharePoint’s 12 hive would show the stack trace, but no luck.  I don’t know if it’s possible and if someone does, please let me know 🙂

I know it’s possible to write your own log messages to the 12 hive.  Frankly, I wanted something a little less scary and quicker to implement.

It occurred to me that I could at least get some basic trace information by catching and re-throwing generic exceptions like this:

  try {
    UpdateEditionDate(properties);
  }
  catch (Exception e)
  {
    throw new Exception("Dispatcher, UpdateEditionDate(): Exception: [" + e.ToString() + "].");
  }

This showed up in the 12 hive thusly:

Error loading and running event receiver Conchango.xyzzyEventReceiver in xyzzy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=blahblahblah. Additional information is below.  : Dispatcher, UpdateEditionDate(): Exception: [System.NullReferenceException: Object reference not set to an instance of an object.     at Conchango.xyzzyManagementEventReceiver.UpdateEditionDate(SPItemEventProperties properties)     at Conchango.xyzzyManagementEventReceiver.Dispatcher(SPItemEventProperties properties, String eventDescription)].

That gave me all the detail I needed to track down that particular problem and I expect to use it a lot going forward.

</end>

Subscribe to my blog!

Solution: SPQuery Does Not Search Folders

This past week I was implementing an "evolving" solution for a client that uses BDC and SPQuery and ran into some difficulty using SPQuery against a document library containing folders.  Bottom line: assign "recursive" to the view attribute of the query.

My scenario:

  • On Monday, I upload a document and supply some meta data.
  • The following week, I upload a new document.  Much of this new document’s meta data is based on the document I uploaded on Monday (which we call the "master document").
  • We’ve created a web service façade that provides a BDC-friendly interface to the list so that users can easily locate that Monday document via a title search.
  • A BDC data column provides a friendly user interface.  (This is part of my attempt at using BDC for a more friendly Lookup column).

The final BDC façade service uses a query like this to do the lookup:

 // Used U2U tool to assist in generating this CAML query.
      oQuery.Query =
        "<Where>";

      if (titleFilter.Length > 0)
        oQuery.Query +=
          "  <And>";

      oQuery.Query +=
        "    <And>" +
        "      <Geq>" +
        "        <FieldRef Name=\"DocumentId\" />" +
        "        <Value Type=\"Text\">" + minId + "</Value>" +
        "      </Geq>" +
        "      <Leq>" +
        "        <FieldRef Name=\"DocumentId\" />" +
        "        <Value Type=\"Text\">" + maxId + "</Value>" +
        "      </Leq>" +
        "    </And>";

      if (titleFilter.Length > 0)
        oQuery.Query +=
          "    <Contains>" +
          "      <FieldRef Name=\"Title\" />" +
          "      <Value Type=\"Text\">" + titleFilter + "</Value>" +
          "    </Contains>" +
          "  </And>";
      oQuery.Query +=
        "</Where>";

During the initial stage of development, this worked great.  However, we introduced folders into the directory to solve some problems and suddenly, my BDC picker wouldn’t return any results.  I tracked this down to the fact that the SPQuery would never return any results.  We used folders primarily to allow multiple files with the same name to be uploaded but with different meta data.  When the file is uploaded, we create a folder based on the list item’s ID and then move the file there (I wrote about that here; we’ve had mixed results with this approach but on the whole, it’s working well).  The user don’t care about folders and in fact, don’t really understand that there are any folders.  We have configured all the views on the library to show items without regard to folders.

I hit this problem twice as the technical implementation evolved and solved it differently each time.  The first time, I wasn’t using the CONTAINS operator in the query.  Without a CONTAINS operator, I was able to solve the problem by specifying the view on the SPQuery’s contructor.   Instead of using the default constructor:

SPList oList = web.Lists["Documents"];

SPQuery oQuery = new SPQuery();

I instead used a constructor that specified a view:

SPList oList = web.Lists["Documents"];

SPQuery oQuery = new SPQuery(oList.Views["All Documents"]);

That solved the problem and I started to get my results.

I then added the CONTAINS operator into the mix and it broke again.  It turns out that the CONTAINS operator, so far as I can tell, does not work with the view the same way as the a simpler GEQ / LEQ operators.  I did some searching and learned that the query’s ViewAttributes should be set to "Recursive", as in:

oQuery.ViewAttributes = "Scope=\"Recursive\"";

That solved the problem for CONTAINS.  In fact, this also solved my original search problem and if I had specified the recursive attribute the first time, I would not have run into the issue again.

The fact that a view-based SPQuery works for some operators (GEQ/LEQ) and not others (CONTAINS), coupled with the fact that KPIs don’t seem to work at all with folder-containing document libraries leads me to believe that SPQuery has some orthogonality issues.

Special Thanks:

  • The good folks at U2U and their query tool.
  • Michael Hoffer’s great "learning by doing" blog post, comments and responses.

</end>

 Subscribe to my blog!

MOSS KPI bug? List Indicator Tied to Document Library With Folders

 

UPDATE 02/29/08: I solved this problem by creating a folder and then assigning a content type to the folder which has the meta data I need for the KPIs.  I described that in a little more detail here.

We have implemented a technical solution where users upload documents to a document library.  An event receiver creates a directory and moves the file to that directory (using a technique similar to what I wrote about here).  We’ve successfully navigated around the potential issues caused by event receivers that rename uploaded files (mainly because users never start their document by clicking on "New" but instead create the docs locally and then upload them).

The meta data for these documents includes a Yes/No site column called "Urgent" and another site column called "Status".  We need to meet a business requirement that shows the percentage of "Urgent" documents whose status is "Pending".

This is usually simple to do and I described something very much like this at the SharePoint Beagle with lots of screen shots if you’re interested.

In a nutshell, I did the following:

  • Create a view on the doc library called "Pending".
  • Configure the view to ignore folder structure.
  • Create a KPI List.
  • Create an indicator in the list that points to the doc lib and that "Pending" view.

This simply does not work.  The KPI shows my target (e.g. five urgent documents) but always shows the actual number of urgent documents as zero.  Paradoxically, if you drill down to the details, it shows the five urgent documents in the list.  I created a very simple scenario with two documents, one in a folder and one not.  Here is the screen shot:

image

The above screen shot clearly shows there are two documents in the view but the "value" is one.  The "CamlSchema" with blank document Id is in the root folder and the other is in a folder named "84".

It appears to me that even though you specify a view, the KPI doesn’t honor the "show all items without folders" setting and instead, confines itself to the root folder.

If I’m wrong, please drop me a line or leave a comment.

</end>

Subscribe to my blog!

 

Technorati Tags:

Solution to Problem: “FileNotFoundException” With My Feature Receiver.

I was working on a feature last week that would add some event receivers to a specific list instance.  (I blogged a bit about that list receiver here).

Using the command line, I could install the feature with no error (but see below for the hidden error).  When I tried to deploy the feature on the site, MOSS complained of a "FileNotFoundException" error.  This blog entry describes how I solved it. 

This is the error that MOSS showed me in the web browser:

Feature ‘b2cb42e3-4f0a-4380-aaba-1ef9cd526f20’ could not be installed because the loading of event receiver assembly "xyzzyFeatureReceiver_0" failed: System.IO.FileNotFoundException: Could not load file or assembly ‘xyzzyFeatureReceiver_0’ or one of its dependencies. The system cannot find the file specified.
File name: ‘xyzzyFeatureReceiver_0’
   at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
   at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   at System.Reflection.Assembly.Load(String assemblyString)
   at Microsoft.SharePoint.Administration.SPFeatureDefinition.get_ReceiverObject()
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Troubleshoot issues with Windows SharePoint Services.

I know how to deliberately cause that error: don’t install the assembly in the GAC.  But, it was in the GAC.  I normally install assemblies into the GAC by dragging them into the c:\windows\assembly folder using windows explorer.  I’ve never felt 100% comfortable doing that because I always thought that gacutil existed for a reason … so I tried that.  It made no difference.

I searched the Internets and found this post: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2243677&SiteID=1

The poster happened to be using the same root bit of code (from the Inside WSS book from this list) so that was a hopeful sign.  However, the suggestion of decorating the assembly with an [assembly: ] directive didn’t make sense to me.  I tried it anyway and I was right.  It made no difference.

Then I noticed that my class definition was not public.  I made it public and that made no difference.

Next, I went to the trouble of enabling the "assembly bind failure log" (following the helpful and accurate instructions provided) and this is where things started to get interesting.  That log shows me that the runtime is searching everywhere on that server for my assembly.  It even appears to be searching for it in my medicine cabinet.  But … it won’t search for it in the GAC.

I put on my winter jacket and go searching the Internets again and find that someone has had this problem too.  The lengthy discussion in that posting peters off into nothing and I can’t find a solution.

I move my assembly into one of the places the log claims it’s searching and I make a little more progress.  I’m rewarded with a new error in the browser when I try to activate the feature:

Failed to create feature receiver object from assembly "xyzzyFeatureReceiver_0", type "Conchango.xyzzyFeatureReceiver" for feature b2cb42e3-4f0a-4380-aaba-1ef9cd526f20: System.ArgumentNullException: Value cannot be null.
Parameter name: type
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at Microsoft.SharePoint.Administration.SPFeatureDefinition.get_ReceiverObject()

Troubleshoot issues with Windows SharePoint Services.

Time for one last trip to the Internets!

This time I find out, predictably enough, that MOSS issues this error because the assembly is not in GAC. 

I want to get something positive out of this and try to feel a little proud that I’ve created the Fugitive of MSIL assemblies, but it’s not working.  I’m just plain annoyed.  I find myself muttering "chicken or the egg" under my breath.

I finally decide to punt.  I create an entirely new project and copy/paste the code from the incredible-cloaked-from-the-GAC-assembly non-working project over to this new project.  (I look for a build flag called something like "hide from assembly binding if installed in the GAC" but can’t find one).

I install the feature and activate it and … it works!  So, after all that, I had to basically ‘reboot’ my project.  This is another reason why I hate computers.

I did learn something useful  from this.  I had been installing features using the stsadm command line all day long and been using the "-force" option out of habit.  For some reason, I did not use the -force option when I installed the new project.  This time, I did actually, truly forget to copy this new project’s assembly into the GAC.  As a result, I received that "FielNotFoundException" error.  This time, I got it from stsadm, not when I tried to activate the feature via the web browser.  So, -force actually plays two roles.  It allows you to re-install an existing feature.  It also allows you to install a buggy feature that cannot work at runtime by suppressing the error.  It probably says as much in the help somewhere but I never noticed it.

</end>

Quick & Easy: Rename Uploaded File Using SharePoint Object Model Via an Event Receiver

 

UPDATE: This works but there are significant limitations which are described in the comments.  This may still be useful in some cirumstances.

UPDATE 2: In my current project, users always upload documents.  As a result, I don’t run into a problem where MS Word is running and thinks that the file was renamed on it.  I did run into a problem, "the file was modified by someone else" and solved this via a simple semaphore type flag.  Users need to change a meta data field from its default value to something else.  The itemupdated() receiver looks for a valid value there before actually performing the rename and since then, I have not had any problems.  Your mileage may vary.

I have a client requirement to change the name of files uploaded to a specific document library to conform with a particular naming convention.  The API does not provide a "rename()" method.  Instead, we use "MoveTo(…)".  Here is a minimal bit of code to accomplish this:

 

 public override void ItemAdded(SPItemEventProperties properties)
        {
            SPFile f = properties.ListItem.File;

            f.MoveTo(properties.ListItem.ParentList.RootFolder.Url + "/xyzzy.doc");
            f.Update();

        }

The only tricky bit is the "properties.ListItem.ParentList.RootFolder.Url".  The MoveTo() method requires a URL.  That mashed up string points me to the root folder of my current document library.  This allows me to avoid any hard coding in my event receiver.

This is a more useful version that does the same thing, but assigns the name of the file to "Title":

 public override void ItemAdded(SPItemEventProperties properties)
        {
            DisableEventFiring();

            // Assign the title of this item to the name of file itself.
 // NOTE: This assignment must take place before we modify the file itself.
 // Calling update() on the SPFile seems to invalidate the properties in
 // some sense.  Updates to "Title" failed until that change (and update() call)
 // were moved in front of the change to the file name.
            properties.ListItem["Title"] = properties.ListItem.File.Name;

            properties.ListItem.Update();

            SPFile f = properties.ListItem.File;

            // Get the extension of the file.  We need that later.
 string spfileExt = new FileInfo(f.Name).Extension;

            // Rename the file to the list item's ID and use the file extension to keep
 // that part of it intact.
            f.MoveTo(properties.ListItem.ParentList.RootFolder.Url +
                "/" + properties.ListItem["ID"] + spfileExt);

            // Commit the move.
            f.Update();

            EnableEventFiring();
        }
 

Quick Tip: Content Query Web Part, Lookup Column Value and XSL

I have a column name in a content type named "Real Estate Location".

That column is of type "lookup".

I have modified <CommonViewFields> and ItemStyle.xsl to show the column.

A simple <xsl:value-of select=…> returns back an internal value that includes ordinal position data, such as:

1;#Miami

To get the human-friendly value, use xsl substring-after, as shown:

<xsl:value-of select="substring-after(@Real_x005F_x0020_Estate_x005F_x0020_Location,’#’)"></xsl:value-of>

Use this technique whenever you are working with lookup values in XSL transforms and need to get the human-friendly value.

<end/>

Technorati Tags: , ,

Quick and Easy: Determine Internal Column Name of a Site Column

UPDATE: Jeremy Thake has blogged about this and put up some code for a console application that shows internal names.

I was trying to get a content query web part to display a due date from a task and because the screen label is "Due Date", I assumed that the column name to use in <CommonViewFields> is "Due_x0020_Date".

Wrong!

The real column name in this case was "DueDate".

How did I find it?  I re-read Heather Solomon’s blog entry on modifying CQWP to show additional columns of data.  She describes this process at step #13.  Trust it.  It’s correct.  At least, it was correct for me.  I did not trust it at first for another column with a much longer name.

I say "Trust it" because I did not trust it and probably wasted near two hours butting my head up against a wall.  After I resolved the "DueDate" name, I wanted to add another field to <CommonViewFields>.  Using the Solomon technique, I was getting a column name like "XYZ_x0020_Project_x0020_Due_x00".

I thought to myself, that’s clearly a truncated name.  I went ahead and un-truncated it with no success.  I finally used the seemingly truncated name and it worked.

Bonus tip: When I was working with the CQWP, if I added a bad internal name to <CommonViewFields>, the CQWP would tell me that the query had returned no results.  But, if I added a data type to the field name, it would return a result.  Adding the data type actually masked a problem since I was referencing a non-existent field.  I could add it, but when I tried to display its value, I would always get a blank. 

This did not mask the error:

<CommonViewFields>Due_x0020_Date;</CommonViewfields>

This did mask the error:

<CommonViewFields>Due_x0020_Date,DateTime;</CommonViewfields>

</end>