SPList: Sharepoint Object Model Considerations (Update list properties)

I noticed a weird behavior of the Sharepoint Object Model when trying to set the attributes of an existing list of a Sharepoint site.

 The following code works as you expect:  

spList = web.Lists[“MyList”];
spList.OnQuickLaunch=true;

spList.Update();


but not this one:    


web.Lists[“MyList”].OnQuickLaunch=true;

web.Lists[“MyList”].Update();

 It is a “by design” behavior even if most of you considered it a bug. I had to use the reflactor in order to demonstrate my affirmation.

 The code statements that are important for us were highlighted.

 The following code is the indexer implementation of the SPListCollection class (including the other methods used by the indexer):

 public SPList this[string strListName]

{

    get

    {

        return this.GetListByName(strListName, true);

    }

}

 internal SPList GetListByName(string strListName, bool bThrowException)

{

    this.EnsureListsData(null);

    int num = 0;

    while (num < this.m_dwCount)

    {

        if (!SPUtility.StsCompareStrings(strListName, (string) this.m_arrListsData[(int) ((IntPtr) 4L), (int) ((IntPtr) num)]))

        {

            num++;

            continue;

        }

        return this.CreateSPList((uint) num);

    }

    if (bThrowException)

    {

        throw new ArgumentException();

    }

    return null;

}

 private SPList CreateSPList(uint index)

{

    SPBaseType type2 = (SPBaseType) Convert.ToUInt32(this.m_arrListsData[8, index]);

    if (type2 == SPBaseType.DocumentLibrary)

    {

        SPListTemplateType type = (SPListTemplateType) this.m_arrListsData[10, index];

        switch (type)

        {

            case SPListTemplateType.PictureLibrary:

                return new SPDocumentLibrary(this, this.m_arrListsData, index);

        }

        return new SPPictureLibrary(this, this.m_arrListsData, index);

    }

    if (type2 != SPBaseType.Issue)

    {

        return new SPList(this, this.m_arrListsData, index);

    }

    return new SPIssueList(this, this.m_arrListsData, index);

}

 SPList class:

 internal SPList(SPListCollection lists, object[,] arrListProps, uint iRow)

{

    this.m_Lists = lists;

    this.m_arrListProps = arrListProps;

    this.m_iRow = iRow;

    this.m_ListAttributesDict = new ListDictionary();

}

 As you can see, the indexer creates a SPList every time the indexer is called.

If you analyze the non-working code again it will be clear enough:

 A new SPList is created and its OnQuickLaunch property is set to true:

 web.Lists[“MyList”].OnQuickLaunch=true;

 A new SPList is created and the Update method is called, but nothing special happens because the OnQuickLaunch property was set on other SPList instance:  

 web.Lists[“MyList”].Update();

 The same behavior was observed also when working with the DefaultView (please see my previous post about that). I’m convinced that this behavior is applicable as well to other sharepoint objects.

Design Patterns Comparison

There are tons of interminable debates and controversies around design patterns. The current post doesn’t intend to add a new one or to create waves. It just relates to a few mistakes that are done when comparing “similar” patterns.

 From time to time, we organize internal design patterns presentations. Most of the time the presentation format is like this: a guy picks a pattern and presents it, during presentation we ask questions and discuss about it, at the end we compare it with other “similar” patterns and underline the advantages (testing, reusability etc.).

 The presenters choose to show real code in order to convince the audience about the pattern and the similarities with other patterns. Even if it is a good practice, the real problem addressed by the pattern will be overlooked if you consider only the code.

 When comparing two patterns the audience falls into the sin of analyzing them in terms of classes and responsibilities. This happens because the pattern code was written a few months ago and it’s hard to remember why you decided to use the pattern. Often the pattern intention is in the shadow of the testability and reusability arguments. In this case you might end up with implementing a particular pattern even if the problem claims for another. Therefore in such discussions the focus should be on the intention of the pattern and the problems it resolves.

 For instance it is very easy to confuse the Adapter with the Bridge if you are looking only to the code and you don’t know the real intention of such an implementation decision. The purpose of the adapter is to adapt the interface of an existing component in order to simplify or to meet your requirements. The consequence of this is that you don’t access the component directly in the client. On the other hand the role of a Bridge is to vary the implementation. This makes it suitable for plugging specific implementation at runtime.  Again the result is the isolation from the client. This obvious consequence makes them easy to confuse. The Adapter is a decision made most of the time during the low level design in order to simplify the integration of third party components. The Bridge pattern is considered up-front (high level design) because you will need it in order to impress a specific behavior to the system more than to simplify the implementation (component integration and isolation).

 Here are two scenarios that give you a flavor of how things influence the decision:

 1. Let’s suppose that a development team decide to use an existing open-source component with some functionality that will take them too much time to develop. That component has a lot of additional functionality that is not needed and the interface is too complex for using directly. The good decision is to add an adapter between the application and the third party component. This will simplify the interface and will isolate the client code from accessing directly the component. In this case the component already exists and the only concern is how to manipulate it in an easy way.

 2. A customer asked to develop a client application for 2 platforms: Windows XP and WinCE. The software company has 3 teams: one that develops agnostic-platform functionality and a team for each specific platforms. During the high level design the architect decided to use the bridge pattern. Each platform team develops a component that is platform specific and which conforms to an interface contract. The common functionality will be developed making the assumption that at some point the specific platform functionality will be provided. The bridge shouldn’t be thought as a middle man because it can mix the interface operations and maybe custom functionality to provide consistent services to higher levels.

 As a conclusion when comparing similar patterns first consider the purpose of the pattern before drilling into implementation details. It will be very hard to make a clear distinction using only code samples and ignoring the intention behind that.

SPList: add columns to the DefaultView

I came across some strange behavior of the Sharepoint Object Model (OM) when adding a new column (field) to the default view of an existing list.

Surprisingly (or not :) ) the following code snippet doesn’t seem to work:

list.DefaultView.ViewFields.Add(ACCOUNT);
list.DefaultView.Update();

But what you say if the following one is working:

SPView defaultView = list.DefaultView;
defaultView.ViewFields.Add(ACCOUNT);
defaultView.Update();

Let’s take a closer look in debugger to see what happens when running this code:

The first print-screen displays the current properties of the default view object:

SPList - add columns to the DefaultView 1

The following image display the properties of the defaultView object :

SPList - add columns to the DefaultView 2

Looks like the SPView defaultView = list.DefaultView code line makes a copy of the default view. The defaultView has different fields after this step:

SPList - add columns to the DefaultView 3

Update method seems to synchronize the information with the real view object (tried to see Update method with the reflactor but it is obfuscated):

SPList - add columns to the DefaultView 4

Managed Custom Action (Wix) Error

I had to write a few custom actions for a wix installer. I didn’t have any experience with using managed custom actions in wix so I started with a good article about this.

I implemented all the steps described in the article and ensured that everything is ok but I was still getting the error: “InstallUtilLib.dll: Unknown error.”

CAError

After some investigation (tests and internet search) I understood that you have to specify the supported .net framework in the configuration file in case you have installed more than one framework:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
 <startup>
  <supportedRuntime version=”v2.0.50727″/>
 </startup>
</configuration>

Biztalk Direct Binding Messaging Error

Biztalk Direct Binding Messaging error
A few months ago I worked on a medium-size Biztalk project. I’ll depict in a few words the big picture of the application architecture in order to understand the context. The application backend was based entirely on Biztalk. The reason was all the Biztalk “poetry”: reliability, scalability, availability, asynchronous processing… the rich customer ready to pay for a Biztalk solution. The backend was designed to have two layers: one that exposes common and granular services specific to the business domain, the other one was thought to be specific to the applications that will consume the services. The services layer has an orchestration for each service it exposes.
The communication between the two layers was implemented with the Direct Binding mechanism to have a low coupling between layers. So the application specific layer is publishing a message into the MessageBox and the services layer consumes the message basing on its orchestrations subscriptions. The response path was designed in the same way.
The other thing that should be mentioned is that our team was involved only in the development of the services layer.
We deployed the application in the production environment and after a while we started to receive from time to time the following strange and meaningless error in the event viewer:

Event Type: Error
Event Source: XLANG/s
Event Category: None
Event ID: 10008
Date: 27/10/2007
Time: 04:33:29
User: N/A
Computer: Computer
Description:
Uncaught exception (see the ‘inner exception’ below) has suspended an instance of service ‘ServiceLayer.Service1(92cac9e7-dbe2-d8dd-515b-6805d86d001d)’.
The service instance will remain suspended until administratively resumed or terminated.
If resumed the instance will continue from its last persisted state and may re-throw the same unexpected exception.
InstanceId: 5789b48b-6297-452f-8b41-ff9a6b1090ec
Shape name: Send Service1Msg
ShapeId: 82d935e6-6c3d-4f4e-86e0-1c8ddb679ea3
Exception thrown from: segment 1, progress 59
Inner exception: Exception occurred when persisting state to the database.

Exception type: PersistenceException
Source: Microsoft.XLANGs.BizTalk.Engine
Target Site: Void Commit()
The following is a stack trace that identifies the location where the exception occured

at Microsoft.BizTalk.XLANGs.BTXEngine.BTXXlangStore.Commit()
at Microsoft.XLANGs.Core.Service.Persist(Boolean dehydrate, Context ctx, Boolean idleRequired, Boolean finalPersist, Boolean bypassCommit, Boolean terminate)
at Microsoft.XLANGs.Core.LongRunningTransaction.PendingCommit(Boolean ignore, XMessage msg)
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXPortBase.SendMessage(Int32 iOperation, XLANGMessage msg, Correlation[] initCorrelations, Correlation[] followCorrelations, Context cxt, Segment seg, ActivityFlags flags)
at ServiceLayer.Service1.segment1(StopConditions stopOn)
at Microsoft.XLANGs.Core.SegmentScheduler.RunASegment(Segment s, StopConditions stopCond, Exception& exp)
Additional error information:

A batch item failed persistence Item-ID d3057a06-4e67-45b8-99ce-4c2b4e3c79ac OperationType MAIO_CommitBatch Status -1061151998 ErrorInfo The published message could not be routed because no subscribers were found. .

Exception type: PersistenceItemException
Additional error information:

Failed to publish (send) a message in the batch. This is usually because there is no one expecting to receive this message. The error was The published message could not be routed because no subscribers were found. with status -1061151998.

Exception type: PublishMessageException

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

After some investigation we observed that the issue is manifesting under high load of the services layer. In that scenario the service response time increased considerable so we decided to ask the guys that implemented the specific application layer how they deal with such a scenario. We found out that they had implemented a timeout mechanism that signal the front-end application about the timeout and terminate the orchestration.
It was clear for us that the problem has something to do with the Direct Binding and with the fact that the consumer orchestration is closed before receiving its response. The service orchestration publishes a message that doesn’t have any subscriber because the consumer orchestration is terminated meanwhile.
In order to reproduce this behavior we created a test application with two orchestrations: a consumer orchestration and a service orchestration. The consumer application publishes a message and waits for the response for a given time… if the time expires it will terminate. The service orchestration has some delay activity that will let enough time to the consumer to terminate before sending the response. The same error is received with the test application.
In conclusion, you should pay attention and not terminate the consumer orchestrations that are involved into Direct Binding communication pattern before receiving the response, otherwise the administration work will become interesting or the application will remain in an inconsistent state.