Problem: Creating a site column using the SharePoint API (Object Model) with incorrect case in the URL for the SPSite or SPWeb object will cause the new column to throw an exception if an attempt to edit it is made through the Site Columns Gallery.
SharePoint is generally very tolerant of accepting a URL in a case-insensitive fashion, however there are a few cases where it completely breaks down. For example, when creating a site column it somehow stores and uses the URL when it was created, and when trying to edit the field definition through the Site Column Gallery (fldedit.aspx page in the LAYOUTS) you end up throwing the error below.
Value does not fall within the expected range.
at Microsoft.SharePoint.SPFieldCollection.GetFieldByInternalName(String strName, Boolean bThrowException)
at Microsoft.SharePoint.SPFieldCollection.GetFieldByInternalName(String strName)
at Microsoft.SharePoint.ApplicationPages.BasicFieldEditPage.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
How can I reliably get the correct URL for a site/web? The SPSite.Url and SPWeb.Url properties seem to return back whatever case they are instantiated with.
In other words, the site collection is provisioned using the following URL: http://server/Path/Site
Then, if I create a new Site Column using the SharePoint object model and happen to use http://server/path/site when instantiating the SPSite and SPWeb objects, the site column will be made available but when trying to access it through the gallery the error above is generated. If I correct the URL in the address bar, I can still view/modify the definition for the SPField in question, but the default URL that is generated is bogus.
Clear as mud?
Example code: (this is a bad example because of the case sensitivity issue)
// note: site should be partially caps: http://server/Path/Site
using (SPSite site = new SPSite("http://server/path/site")) {
using (SPWeb web = site.OpenWeb()) {
web.Fields.AddFieldAsXml("..."); // correct XML really here
}
}