Wednesday, November 21, 2012

FIX message Debug Visualizer for Visual Studio

Recently I had the opportunity to work on an order management system which utilized QuickFIX/n as the FIX Engine. As anyone who has worked with FIX probably knows, reading raw FIX message strings is not for the faint of heart.  After struggling with it for a while, I decided to put in the time to build a Debug Visualizer. Overall, I like how far I have gotten with it.  Please check it out on GitHub.


Monday, October 8, 2012

.NET equivalent of xslproc

Recently I had to install xslproc tool on windows  for an open source project i'm contributing to.  All I can say is - annoying.  I decided to use the power of .Net to write a drop-in replacement. The main goal was not to change any of the scripts that call this tool and not to have any dependencies besides .NET Framework. My code is below. Not counting the error handling code, core logic is only 4 lines long. The miracle worker here is the XslCompiledTransform class.

 Please note that it only supports limited subset of parameters of the original tool. Use at your own risk.

static int Main(string[] args)
            if (args == null || args.Length != 4)
                Console.Error.WriteLine("Invalid arguments provided!" + args.Length);
                return -1;
            string outFile = args[1];
            string styleSheet = args[2];
            string inputFile = args[3];
                XslCompiledTransform myXslTransform = new XslCompiledTransform();
                myXslTransform.Load(Path.Combine(Environment.CurrentDirectory, styleSheet));
                myXslTransform.Transform(Path.Combine(Environment.CurrentDirectory, inputFile), Path.Combine(Environment.CurrentDirectory, outFile));
                return 0;
            catch (Exception ex)
                Console.Error.WriteLine("Error during transform: " + ex.ToString());
                return -1;

Thursday, July 14, 2011

Testing for existence of key in a .NET 4 Dynamic Dictionary

Recently I had to implement a component that recieves a dictionary filled with user settings. I decided to use C# 4's new dynamic keyword to enhance access to the dictionary. After some googling i found a basic implementation of DynamicDictionary (Thanks to Phil Haack ).

The one flaw in the implementation can be observed by looking at the code below. If key "CustomerName" is not in the dictionary an exception will be thrown.

dynamic dic = new DynamicDictionary();

string customerName = string.Empty;
customerName = dic.CustomerName; // Potential BinderException Here 

I wanted a clean approach to testing for existence of a key in my DynamicDictionary like in the code below:
dynamic dic = new DynamicDictionary();

string customerName = string.Empty;

if (dic.HasCustomerName())
  customerName = dic.CustomerName;

I extended Phil's DynamicDictionary code to support a function with signature of  "bool Has[Key]()". To implement this I had to override  TryInvokeMember method of the DynamicObject class, in which I strip out the "Has" part and simply call ContainsKey([Key]) on the dictionary.
Here is the complete code:

  public class DynamicDictionary : DynamicObject
        Dictionary<string, object>
          _dictionary = new Dictionary<string, object>();

        public override bool TrySetMember(SetMemberBinder binder, object value)
            _dictionary[binder.Name] = value;
            return true;

        public override bool TryGetMember(GetMemberBinder binder,
            out object result)
            return _dictionary.TryGetValue(binder.Name, out result);

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
            result = false;

            if (binder.Name.StartsWith("Has"))

                var propName = binder.Name.Substring(3, binder.Name.Length - 3);

                result = _dictionary.ContainsKey(propName);

                return true;

            return false;


Wednesday, June 16, 2010

"The SPPersistedObject, XXXXXXXXXXX, could not be updated because the current user is not a Farm Administrator" craziness in Sharepoint 2010

After upgrading from SharePoint 2007 to 2010 we noticed that our custom job scheduler web part started throwing the following error:

 "The SPPersistedObject, Microsoft.SharePoint.Administration.SPJobDefinition, could not be updated because the current user is not a Farm Administrator".

Since we were running the SPJobDefinition.Update() and related code under SPSecurity.RunWithElevatedPrivileges() I was under the impression that the code already ran as Farm Admin. After banging my head against the wall for a couple hours with no solution I decided to whip out my most trusted tool - Red Gate's Reflector - it never failed me before.

Upon detailed investigation of Microsoft.SharePoint.dll  I discovered that SharePoint guys added a new security feature to all objects inheriting from SPPersistedObject in the Microsoft.SharePoint.Administration namespace. This feature explicitly disallows modification of the above stated objects from content web applications, which is where our web part is running. The error message thrown is therefore very misleading. After some more tracing through the code I found a property in SharePoint API which controls this behavior:


After setting this property from PowerShell the issue went away with no code changes. The script I used is attached to this post.

Tuesday, December 8, 2009

Starting SharePoint 2010 Site Workflows from code


One of the cool new features of  SharePoint 2010 is Site Workflows. As you probably know, in SharePoint 2007 a workflow can only be associated with a list or a document library. While this functionality is useful, sometimes a “site wide” workflow is called for. This leads to us developers getting creative and producing  approaches such as creating a list called “Site Workflows” and creating items in it that have “start on create” workflows attached to them. In SharePoint 2010 Site Workflows provide an elegant solution for this common scenario.

The Code

 using (SPSite site = new SPSite("http://moss2010beta")) //get the site

           using (SPWeb web = site.OpenWeb()) // get the web
                        //find workflow to start
                        var assoc = web.WorkflowAssociations.GetAssociationByName("Demo Site Workflow", CultureInfo.InvariantCulture);

                        //this is the call to start the workflow
                        var result = site.WorkflowManager.StartWorkflow(null, assoc, string.Empty, SPWorkflowRunOptions.Synchronous);


As you probably have noticed, the API call to start a site workflow is not much different form the call to start a list workflow. A new overload was added to SPWorkflowManager.StartWorkflow() method. This is the method we call to programmatically start our site workflow. One new parameter of this overloaded method which deserves a mention is the runOptions parameter, which expects a SPWorkflowRunOptions enumerator. See MSDN page for details.

Possible uses of the code

I believe that Site Workflows in SharePoint 2010 bring even more flexibility to an already powerful workflow infrastructure that the platform currently offers. There are many examples I can think of where one would use site workflows, but one specific one is on the top of my list. Say you have an application built on top of SharePoint 2010, which, when installed, adds whole bunch of custom lists, event handlers and workflows to the site. Now imagine if some of the major “events” or “states” of that application are implemented as site workflows created in SharePoint Designer 2010, which at any given point are started from event handlers or other custom code. Say that one such site workflow is run by the application when a document of a specific content type is checked in to the system by a user in a specific SharePoint group. The default site workflow is set to notify the content steward by email. If one of the SharePoint Designer 2010 savvy users wants to change that to create a whole review process or create a task or a list item in another list, they can. The point is,  Site Workflows can be used to add extensibility points to an application build on top of SharePoint, which require only SharePoint Designer power user to take advantage of.  In conclusion, I hope that this article will help someone out there build smarter solutions to common business problems on top of the upcoming  SharePoint release.

Sample Code Download:

Tuesday, November 17, 2009

Useful SharePoint Designer Activities and SharePoint Designer 2010

It did not come as a surprise that Microsoft has added functionality into SPD 2010 that some of the activities created as a part of my open source project on CodePlex accomplished. At this year’s SharePoint Conference in Las Vegas I made it a point to go and check out some of the SPD 2010 sessions. I was pleasantly surprised by the new functionality that was added to SPD and you got to love the ribbon interface. On a sad note the most popular set of activities on the CodePlex project, the Permission Activities, are now available out of the box. There was a moment during one of the SPD 2010 demos when the guy said “and now we are going to set permissions on this item” I thought to myself “Oh, well, I’m just going to have to find another niche for the open source project”. From what I saw not all of the functionality provided by my project is in SPD 2010. For instance, “Start another workflow” is not part of the new functionality. Once I get my hands on a stable Beta of WSS and SPD 2010 I will create a roadmap for the still needed custom activities that may be implemented in the next version of the Useful SharePoint Designer Activities Project. Stay Tuned.

Tuesday, September 22, 2009

SharePoint List Query performance gotcha

As i recently discovered, there is BIG difference between calling SPList.GetItemById() and SPList.Items.GetItemById(). The latter causes all items to be loaded into memory and then filtered. This can cause severe performance issues for lists with large number of items.
Below is the code that takes 5 hours to run on a dual core box when run against a list with 5500 items.

   1:  SPList theList = GetList(); 
   3:  List<int> itemIds = new List<int>();  
   5:  foreach(SPListItem item in theList.Items)   
   6:  {  
   7:   itemIds.Add(item.ID);
   8:  } 
  10:  foreach(int itemId in itemIds)  
  11:  { 
  13:    SPListItem theItem =  theList.Items.GetItemById(itemId); //this will cause severe performance issues for large lists
  15:  }

To fix this issue we need to change the code in line 13 to:

  13:  SPListItem theItem =  theList.GetItemById(itemId);

Now the above code will run in minutes.

I wish MSDN documentation on this topic was more clear. That would save me from putting in a couple of late nights at the office.