HowTo: Programmtically add SPFieldMultiLineText field to a list (SharePoint 2010)

Today I struggled when adding a field with the type “SPFieldMultiLineText” to a list.
The trick is at the line where you choose the field type:

someList.Fields.Add("SomeFieldName", SPFieldType.Note, true);

I expected something like “SPFieldType.MultiLineText”. But for some reason you have to choose “Note”. In the comments of the “Note” enum you can read this:

“Specifies a field that can contain multiple lines of text. Corresponds to the SPFieldMultiLineText class and to the Note field type that is specified on the Field element. Value = 3.”

Finally, I’m inserting it this way:

someList = currentWeb.Lists.TryGetList("SomeList");
if (someList != null)
{
    someList.Fields.Add("SomeFieldName", SPFieldType.Note, true);
    var someField = someList.Fields["SomeField"] as SPFieldMultiLineText;
    if (someField != null)
    {
        someField.NumberOfLines = 6;
        someField.Update();
    }

    someList.Update();
}

SharePoint 2010: How to duplicate a publishing page, SPFile, Pages library

It’s near the end of april and I didnt have any special theme to write about ;) That’s why I give out this snippet:

                var pagesList = SPContext.Current.Web.Lists["Pages"];

                string destUrl = SPContext.Current.Web.ServerRelativeUrl + _oldPageItem.File.ParentFolder + "/" + _oldPageItem.File.Name;
                destUrl = destUrl.Replace(".aspx", "_V2.aspx");
                SPContext.Current.Web.AllowUnsafeUpdates = true;

                _oldPageItem.File.CheckOut();
                var destFile = pagesList.RootFolder.Files.Add(destUrl, _oldPageItem.File.OpenBinary(), true, "Page Duplicator", true);
                destFile.Update();
                destFile.CheckIn("Page Duplicator");
                destFile.Publish("Page Duplicator");

Sharepoint2010: How to detect if and which ribbon button was pressed during postback

Some weeks ago I had the problem that I was not able to detect if the user’s has clicked onto the “Save & Close” button when editing a SharePoint Publishing Page. My workaround was to save the current state on every postback when SPControlMode.Edit was true.

Today I found a much simpler way:

Page.Request.Params.Get("__EVENTARGUMENT");

For example, if I hit “Save & Close” this returns “pagestategroupsaveandstop”. If I click edit I get “edit” and so on. Here I have implemented a simple method to get the state:

public class PostBackArgument
    {
        public static string Get(Page page)
        {
            var returnValue = "";
            try
            {
                returnValue = page.Request.Params.Get("__EVENTARGUMENT") ?? "";
            }
            catch (Exception ex)
            {
                //your error handling
            }
            return returnValue;
        }
    }

    ///

    /// The (currently) needed postback arguments
    /// 

    public class PostBackArgs
    {
        public const string Edit = "edit";
        public const string SaveAndClose = "PageStateGroupSaveAndStop";
        public const string SaveAndContinue = "PageStateGroupSave";
        public const string CheckIn = "PageStateGroupCheckin";
        public const string CheckOut = "PageStateGroupCheckout";
        public const string Publish = "PageStateGroupPublish";
        public const string Undefined = "";
    }

I will add a table with more arguments soon.




SharePoint 2010: Safe conflict when updating SPListItem programmtically

Actually I have to implement some kind of an WYSIWYG Editor for SharePoint Pages (SharePoint Publishing Feature). The versioning and “need to checkout file for edit” option are activated. During my test’s I ran into the issue that everytime I changed something on a page and clicked on “Save & Close”, this dialog came up:

SharePoint 2010 Save Conflict when updating SPListItem programmatically

First I thougt that is has to do with impersonation, and tried this:

            var userToken = SPContext.Current.Site.UserToken;
            using (SPSite site = new SPSite(SPContext.Current.Site.Url, userToken))
            {
                using (SPWeb authWeb = site.OpenWeb())
                {
                    var pageItem = authWeb.Lists["Pages"].GetItemById(1);
                    pageItem["MemoryTest"] = TestBox.Text;
                    pageItem.SystemUpdate(false);
                }
            }

Unfortunately this doesnt change anything, I was still getting the dialog. After this I tried to use SPListItem.SystemUpdate instead of SPListItem.Update:

            var page = SPContext.Current.Web.Lists["Pages"].GetItemById(1);
            page["MemoryTest"] = TestBox.Text;
            page.SystemUpdate();

This was also a failure. The dialog still comes up. I tried many other things, elevated privileges, different way’s of getting the page object (via SPContext, via ID, via OpenWeb) but nothing worked. After hours I found a way. To use SPListItem.SystemUpdate(false) did the trick! If you use SystemUpdate(false) you dont increment the version with your update. This leads to the behaviour that SharePoint don’t recognize that you’ve changed something.

            var page = SPContext.Current.Web.Lists["Pages"].GetItemById(1);
            page["MemoryTest"] = TestBox.Text;
            //false did the trick!
            page.SystemUpdate(false);

On the first view this looks a bit dirty, because you change something without affecting the “ModifiedBy” and “LastModified” fields. But in my case the “field to change” is a hidden-field which is never gonna seen by someone. And with the checkout-required flag every version of the page is restorable.

Edit:
After a week of testing I found out that I made a general mistake, which leads to the Save-Conflict Dialog:

I instantiated a new instance of the current page object, saved the changed data to it and called the .Update method. This leads to a save conflict because another instance of the page is already instantiated from sharepoint. The solution was quite simple: Use it :) To save my data I just have to call this:

SPContext.Current.ListItem["MemoryTest"] = TestBox.Text;

It’s very important that you DONT call update afterwards. This does SharePoint for you when the user hits “Checkin” “Save” and so on.

Maximum number of directive dependencies exceeded

Today during my work on a pagelayout I was stopped by this Exception:

The page ‘/sites/hugo/_controltemplates/blah.ascx’ allows a limit of 11 direct dependencies, and that limit has been exceeded.

After some research I found the (quite simple) solution how to solve this. In the webconfig where this entry:


I just had to change the value of “DirecteFileDependencies” from 10 to 20 and everything worked fine again.

Silverlight Exception when creating new SharePoint list

Today I Tried to create a New Custom List via the “normal” backend way: SiteActions -> SiteSettings -> View all Site Content -> Create

This worked pretty well the Last Weeks so i was very surprised when i got this:

Error
An unhandled Exception occured in the Silverlight application.

The Solution was quite simple:
Due to some other Project I had to Turn of the SecurityValidation. After Turning it on again, everything worked fine.

Here is how to activate the SecurityValidation:

  • Open your CentralAdministration
  • Navigate to Manage WebApplications
  • Select your SharePoint WebApp
  • Click on GeneralSettings
  • Scroll Down to “SecurityValidation” and Set it to “on”
  • SharePoint deployment tool

    A few weeks ago I’ve started to write a tool for sharepoint developers which should help you to deploy solutions fast on your local machine or other servers.

    I really don’t like to use the sharepoint command line or strange script-files which you have to edit every time. In my case we had over 70 solutions. Also you always have to figure out if a solution is web or site scoped – my tool does that automatically. All you have to do is to drag&drop (or add) the .wsp files you want to deploy, select the webapps you want to deploy to and click on the “Deploy” button. That’s it. Every solution gets retracted, removed, added and installed then. It’s a little bit beta yet but i’m working on it. Anyway, here you can find and download it. It’s free but i’m very happy about every little donation!

    SharePoint Deploy Tool

    Howto: Connect from iOS to a microsoft sql server

    Currently I’m working on an ontime-plugin for my iphone. One problem is that I have to “speak” with a mssql server. After some research I found this site:

    iSQL SDK

    It provides a webservice which have to be installed on a iis server. After that you can communicate to the webserver, which than communicates with the DB. You can try it out for free, for a commercial use you have to pay 35$ (which is okay in my opinion).

    Here a link to a short tutorial video:

    iSQL Demo Video

    Missing MasterPage setting after Import-SPSite

    Today we had the strange situation that after restoring a site collection using “Import-SPSite” the settingslink to change the masterpage was gone away. Simple solution to change it anyways:

    http:///_Layouts/ChangeSiteMasterPage.aspx