Archive

Posts Tagged ‘C#’

WebLoading Library: Downloading data from RESTful sources

July 23rd, 2012
No comments

    I often run into necessity to load data from sources published in the Internet. In most cases the sources are RESTful web-services, thus the data they emit is in xml or json formats. More and more web-services providers prefer spreading their data in an easier-to-use REST formats as a simpler alternative to SOAP and WSDL based web-services.

WebLoading Library Overview

For downloading data via the Http protocol I implemented a set of generic classes, let’s call it WebLoading Library. Almost every class in the library is a loader, which operates at a certain level of abstraction. The library allows to easily derive a new class from one of the exposed loaders, defining a type of the data to be loaded and the type of the ready-to-use data to be returned out of the loader. See the class diagram below.

Class Diagram of WebLoading Library

I single out such basic steps of getting data as raw data loading, verification and conversion into a ready-to-use view. All loaders exposes the LoadData method aimed at performing these steps.The listing below demonstrates the LoadData‘s base implementation in the BaseLoader class. BaseLoader is a root base class for all loaders in the WebLoading Library hierarchy.

BaseLoader abstracts the loading from any source. Unlike BaseLoader, its direct descendant, HttpLoader, implies loading from a source supporting the Http protocol. See the listing of the HttpLoader class below.

The next level in the hierarchy comprises such loaders as ImageLoader, XmlLoader and JsonLoader. I’ll dwell upon the last two a bit later. As regards the first one, ImageLoader is a quite simple class derived from HttpLoader that downloads an image from a specified source via Http. Being initially intended for dealing with REST formats, the loaders family can be easily extended to any data formats. So, the ImageLoader is a good example to that. The class is shown below:

WebLoading Library Overview: XmlLoader

XmlLoader is an abstract class derived from HttpLoader and intended for xml data downloading. The downloaded raw xml is presented as a XDocument object. Create a descendent of the XmlLoader class to verify and turn the XDocument into any another desired view-object. The XmlLoader looks as follows:

As a simple example, below is a class-descendent demonstrating how to get the expected maximum temperatures for the next 7 days. The data source is http://graphical.weather.gov, which provides with xml data like the following:

The GraphicalWeatherLoader class accepts a zip code of the region you need to get forecast for. See the next listing:

WebLoading Library Overview: JsonLoader

Like XmlLoader, the JsonLoader class is abstract and derived from HttpLoader too. It’s dedicated for downloading json data. The downloaded json is processed by the JsonParser borrowed from the fastJSON project by Mehdi Gholam. Undoubtedly it’s the fastest json parser I’ve ever met. So, many thanks to Mehdi. The parsed json data is presented as a Dictionary<string, object>, which, besides simple objects, may contain arrays and other dictionaries nested on different levels. To have an ability to verify and transform the dictionary into something different, just create a descendent of the JsonLoader. Below is the listing of the JsonLoader:

Pay attention to the SelectObjects methods that obtain an specified object(s) from a tree of arrays and dictionaries using a xpath-like path (for example, “set/items/item”).

Let’s take a look at yet another example, this time it’s a descendent of JsonLoader. The derived class is quite pointless and just gets names of some capital-cities. The http://api.geonames.org service returns the json data in the following form:

The next listing is the GeoNamesCitiesLoader class:

The source code and examples are available to download here.

Categories: C#, JSON, XML Tags: , ,

SharePoint: Working with BDC Secondary Fields

April 17th, 2012
No comments

    As you probably know, in SharePoint 2010 Business Data Connectivity replaced Business Data Catalog of SharePoint 2007. Some changes affects how Business Data Columns are presented in a list’s schema. In SP 2007 a declaration of a Business Data Column in a schema.xml may look like the following:

<Field Type="BusinessData" DisplayName="Product"
Required="FALSE" ID="{bc203358-6113-470f-9b08-f6100cc034f2}"
StaticName="Product" BaseRenderingType="Text" Name="Product"
SystemInstance="ExternalProductDB_Instance" Entity="Products"
BdcField="Name" Profile="" HasActions="False"
RelatedField="Products_ID"
RelatedFieldBDCField="" RelatedFieldWssStaticName="Products_ID"

SecondaryFieldBdcNames="Price:Producer"
SecondaryFieldWssNames="Product_x003a__x0020_Price:Product_x003a__x0020_Producer"
SecondaryFieldsWssStaticNames="Product_x003a__x0020_Price:Product_x003a__x0020_Producer" />

In contrast, in SP 2010 it looks like

<Field Type="BusinessData" DisplayName="Product"
Required="FALSE" ID="{bc203358-6113-470f-9b08-f6100cc034f2}"
StaticName="Product" BaseRenderingType="Text" Name="Product"
SystemInstance="ExternalProductDB_Instance" Entity="Products"
BdcField="Name" Profile="" HasActions="False"
RelatedField="Products_ID"
RelatedFieldBDCField="" RelatedFieldWssStaticName="Products_ID"

SecondaryFieldBdcNames="6%209%20Price%20Producer%204"
SecondaryFieldWssNames="27%2030%20Product%5Fx003a%5F%5Fx0020%5FPrice%20Product%5Fx003a%5F%5Fx0020%5FProducer%206"
SecondaryFieldsWssStaticNames="27%2030%20Product%5Fx003a%5F%5Fx0020%5FPrice%20Product%5Fx003a%5F%5Fx0020%5FProducer%206" />

Undoubtedly, in SP 2010 the secondary fields became practically unreadable. Indeed, the format of secondary fields‘ presentation is revised. Moreover some kind of URL encoding are applied to them. Let’s examine how these secondary fields could look before the URL encoding is applied:

<Field
...
SecondaryFieldBdcNames="6 9 Price Producer 4"
SecondaryFieldWssNames="27 30 Product_x003a__x0020_Price Product_x003a__x0020_Producer 6"
SecondaryFieldsWssStaticNames="27 30 Product_x003a__x0020_Price Product_x003a__x0020_Producer 6" />

Now it’s pretty easy to figure out the new format. Take a look at the SecondaryFieldBdcNames attribute. It contains names of two secondary bdc fields: ‘Price’ and ‘Producer’. 6 is the length of the ‘Price’ name + 1 for a space character right after the name. 9 is the length of the ‘Procuder’ name + 1 for a space character after the name. 4 is the length of the sub-string ‘6 9 ‘ (including spaces), which contains the lengths of the fields’ names. See a picture below:

Format of Secondary Fields

Note that the SecondaryFieldBdcNames, SecondaryFieldWssNames and SecondaryFieldsWssStaticNames have the same format.

We have a lot of code interacting with Business Data Columns, thus we were interested in means allowing easily to decode, encode and parse Secondary Fields attributes. In the Microsoft.SharePoint.dll, there is the internal BdcClientUtil class containing the basic methods to work with Secondary Fields:

internal class BdcClientUtil
{
    ...
    string[] SplitStrings(string combinedEncoded);
    string   CombineStrings(string[] strings);
    ...
}

So, using .Net Reflector I’ve extracted these methods along with several others auxiliary ones and put them into the helper-class called SecondaryFieldNamesHelper. All internal methods and properties were honestly stolen from Microsoft.SharePoint.dll, the public ones were added by me and described below:

  • string Encode(string[] secondaryFieldNames) – accepts an array of field names and returns the string formatted and encoded according to the SharePoint 2010 requirements;
  • string[] Decode(string str) – accepts an encoded string, decodes it and returns a resultant array of field names;
  • bool IsEncodedString(string str) – checks whether a passed string is encoded;
  • string ConvertToSP2010(string str) – converts a SP 2007 colon-separated string of secondary fields into another one formatted and encoded according to the SharePoint 2010 requirements;

Below is the source code of the SecondaryFieldNamesHelper:

The SecondaryFieldNamesHelper can be used as shown below:

SPBusinessDataField bdcField = ...

string secondaryFieldWssNamesProperty = bdcField.GetProperty("SecondaryFieldWssNames");
string[] secondaryWssFieldNames = SecondaryFieldNamesHelper.Decode(property);

string secondaryFieldBdcNamesProperty = bdcField.GetProperty("SecondaryFieldBdcNames");
string[] secondaryFieldBdcNames = SecondaryFieldNamesHelper.Decode(secondaryFieldBdcNamesProperty);

string sp2010WssStaticNames = 
   SecondaryFieldNamesHelper.ConvertToSP2010("Product_x003a__x0020_Price:Product_x003a__x0020_Producer");

As a .cs file the SecondaryFieldNamesHelper class is available here.

C#: Simple Command Line Arguments Parser

March 22nd, 2012
5 comments

    Working with SharePoint applications I very often develop small console applications for adjusting lists, list items, content types and so on. To pass some parameters into those utilities I employ the command line arguments. Then inside applications I deal with an array of arguments – string[] args:

class Program
{
    static void Main(string[] args)
    {
        // get passed parameters from args
    }
}

I usually use the following notation: -paramName paramValue. Here a parameter name with the leading minus sign (‘-‘) is followed by a parameter value. If the presence of value isn’t assumed, only -paramName is used. For example, the following command line

-url "http://dotnetfollower.com" -useElevatedPrivileges

directs an utility to “process the web site http://dotnetfollower.com and use the elevated objects for that”.

To simplify parameters fetching from the args array I’ve implemented an auxiliary class – InputArguments, which parses the arguments and fills a dictionary out with proper key-value pairs. The dictionary allows accessing a parameter value in the way like this: InputArguments[“-url”] or InputArguments[“url”]. The source code of the InputArguments class is listed below:

using System;
using System.Collections.Generic;

namespace Common
{
    public class InputArguments
    {
        #region fields & properties
        public const string DEFAULT_KEY_LEADING_PATTERN = "-";

        protected Dictionary<string, string> _parsedArguments   = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        protected readonly string            _keyLeadingPattern;

        public string this [string key]
        {
            get { return GetValue(key); }
            set
            {
                if (key != null)
                    _parsedArguments[key] = value;
            }
        }
        public string KeyLeadingPattern
        {
            get { return _keyLeadingPattern; }
        }
        #endregion

        #region public methods
        public InputArguments(string[] args, string keyLeadingPattern)
        {
            _keyLeadingPattern = !string.IsNullOrEmpty(keyLeadingPattern) ? keyLeadingPattern : DEFAULT_KEY_LEADING_PATTERN;

            if (args != null && args.Length > 0)
                Parse(args);
        }
        public InputArguments(string[] args) : this(args, null)
        {
        }

        public bool Contains(string key)
        {
            string adjustedKey;
            return ContainsKey(key, out adjustedKey);
        }

        public virtual string GetPeeledKey(string key)
        {
            return IsKey(key) ? key.Substring(_keyLeadingPattern.Length) : key;
        }
        public virtual string GetDecoratedKey(string key)
        {
            return !IsKey(key) ? (_keyLeadingPattern + key) : key;
        }
        public virtual bool IsKey(string str)
        {
            return str.StartsWith(_keyLeadingPattern);
        }
        #endregion

        #region internal methods
        protected virtual void Parse(string[] args)
        {
            for (int i = 0; i < args.Length; i ++)
            {
                if(args[i] == null) continue;
                
                string key = null;
                string val = null;

                if(IsKey(args[i])) 
                {
                    key = args[i];

                    if(i + 1 < args.Length && !IsKey(args[i + 1]))
                    {
                        val = args[i + 1];
                        i ++;
                    }
                }
                else
                    val = args[i];

                // adjustment
                if (key == null)
                {
                    key = val;
                    val = null;
                }
                _parsedArguments[key] = val;
            }
        }

        protected virtual string GetValue(string key)
        {
            string adjustedKey;
            if(ContainsKey(key, out adjustedKey))
                return _parsedArguments[adjustedKey];

            return null;
        }

        protected virtual bool ContainsKey(string key, out string adjustedKey)
        {
            adjustedKey = key;

            if (_parsedArguments.ContainsKey(key))
                return true;

            if (IsKey(key))
            {
                string peeledKey = GetPeeledKey(key);
                if(_parsedArguments.ContainsKey(peeledKey))
                {
                    adjustedKey = peeledKey;
                    return true;
                }
                return false;
            }

            string decoratedKey = GetDecoratedKey(key);
            if(_parsedArguments.ContainsKey(decoratedKey))
            {
                adjustedKey = decoratedKey;
                return true;
            }
            return false;
        }
        #endregion
    }
}

As you can see, the InputArguments stores the parsed parameters and theirs values in the _parsedArguments dictionary, which is accessible through the special indexer. Pay attention to the ContainsKey methods, which attempts different variations (with or without leading symbols) of parameter name in case the passed name isn’t presented among the stored arguments. So, passing the

-url "http://dotnetfollower.com" -useElevatedPrivileges

arguments into an application, the InputArguments can be used as follows:

static void Main(string[] args)
{
    InputArguments arguments = new InputArguments(args);

    Console.WriteLine(arguments["-url"]);
    if (arguments.Contains("useElevatedPrivileges"))
        Console.WriteLine("useElevatedPrivileges is set");
}

The above mentioned command line arguments will be turned into the following key-value pairs:

{["-url", "http://dotnetfollower.com"]}
{["-useElevatedPrivileges", null]}

Below is the more complex command line borrowed from the WSPBuilder and slightly modified to have orphaned values without a foregoing parameter name:

"some orphaned value" -ExpandTypes false -BuildSafeControls true  
-WSPName mySPSolution.wsp  -Outputpath "C:\WSPDeployment\myApp" 
-SolutionId d403bb18-c5f2-4b43-9d55-12b256a6295a 
-SolutionPath "C:\WSPDeployment\myApp" -TraceLevel Verbose 
-DLLReferencePath "C:\WSPDeployment\ReferencedAssemblies"

This arguments will be turned into the following:

{["some orphaned value", null]}
{["-ExpandTypes", "false"]}
{["-BuildSafeControls", "true"]}
{["-WSPName", "mySPSolution.wsp"]}
{["-Outputpath", "C:\WSPDeployment\myApp"]}
{["-SolutionId", "d403bb18-c5f2-4b43-9d55-12b256a6295a"]}
{["-SolutionPath", "C:\WSPDeployment\myApp"]}
{["-TraceLevel", "Verbose"]}
{["-DLLReferencePath", "C:\WSPDeployment\ReferencedAssemblies"]}

Frankly speaking, I don’t use the InputArguments class directly. For every utility I create a derived class to provide an easy access to the values of parameters specific for that particular application. For example, the derived class employing the -url and -useElevatedPrivileges may look like the following:

public class UtilityArguments : InputArguments
{
    public bool UseElevatedPrivileges
    {
        get { return GetBoolValue("-useElevatedPrivileges"); }
    }

    public string Url
    {
        get { return GetValue("url"); }
    }

    public UtilityArguments(string[] args) : base(args)
    {
    }

    protected bool GetBoolValue(string key)
    {
        string adjustedKey;
        if (ContainsKey(key, out adjustedKey))
        {
            bool res;
            bool.TryParse(_parsedArguments[adjustedKey], out res);
            return res;
        }
        return false;
    }
}

It can be used as follows:

static void Main(string[] args)
{
    UtilityArguments arguments = new UtilityArguments(args);

    Console.WriteLine("Url: " + arguments.Url);
    Console.WriteLine("UseElevatedPrivileges: " + arguments.UseElevatedPrivileges);
}

If you prefer using another sign or group of signs before parameter name in command line, use the proper constructor of the InputArguments class

static void Main(string[] args)
{
    InputArguments arguments = new InputArguments(args, "/");
    // ...
}

or

public class MyArguments : InputArguments
{
    // ...
    public MyArguments(string[] args) : base(args, "--")
    {
    }
    // ...
}

Categories: C# Tags: ,

SharePoint: Manually Upgrade Business Data Catalog Application Definitions to Business Data Connectivity Models

March 13th, 2012
No comments

    Trying to import a legacy Application Definition File of SharePoint 2007 into Business Data Connectivity Service of SharePoint 2010, you apparently got at least one of the errors shown below:

  • Application definition import failed. The following error occurred: The root element of a valid Metadata package must be ‘Model’ in namespace ‘http://schemas.microsoft.com/windows/2007/BusinessDataCatalog’. The root in the given package is ‘LobSystem’ in namespace ‘http://schemas.microsoft.com/office/2006/03/BusinessDataCatalog’. Error was encountered at or just before Line: ‘2’ and Position: ‘2’;
  • Application definition import failed. The following error occurred: BDC Model does not correctly match the schema. The required attribute ‘Namespace’ is missing. Error was encountered at or just before Line: ’20’ and Position: ’10’;
  • Application definition import failed. The following error occurred: ReturnTypeDescriptor of MethodInstance with Name ‘ProductSpecificFinderInstance’ on Entity (External Content Type) with Name ‘Product’ in Namespace ‘ExternalProductDB’ should not be a Collection TypeDescriptor for MethodInstances of Type ‘SpecificFinder’. Parameter name: rawValues.ReturnTypeDescriptorId Error was encountered at or just before Line: ‘171’ and Position: ’18’;
  • and so on

As it’s known, in SharePoint 2010, Business Data Catalog (BDC) was replaced with Business Data Connectivity with the same abbreviation. One of the changed things is the format of xml-based Application Definition Files. If you make an in-place upgrade of a live SharePoint 2007 application to SharePoint 2010, bdc metadata will be automatically upgraded as well and will become usable with the Business Data Connectivity. But if the in-place upgrade isn’t an option for you, you can upgrade your xml-based Application Definition Files manually. The manual algorithm step by step is described here – How to: Manually Upgrade Business Data Catalog Application Definitions to Business Data Connectivity Models.

For one of our applications we settled on the manual upgrade of its metadata files. But If I call myself a programmer, I have to try to automate the algorithm, especially taking into account 20+ files required to upgrade. So, I’ve developed a simple application for alteration of the legacy xml-based Application Definition Files to make them compatible with SharePoint 2010. However I’d like to notice that the given converter doesn’t follow entirely the procedure described by Microsoft, but performs only steps allowing our particular metadata files to be successfully imported into the Business Data Connectivity Service. For example, our files don’t comprise actions and associations, thus the application does nothing at all with <Action> and <Association> elements. So, consider this converter as a start point of developing the new one satisfying your own conditions and requirements.

Below I enumerated the necessary and sufficient changes to be applied to our particular metadata files so that it enables us to make them compatible with SharePoint 2010. Exactly these very steps and a few less important I’ve implemented in the converter.

  • the root element in the Application Definition File must be a <Model>;
  • the <Model> must contain <LobSystems> element, which in turn must wrap the former root node – <LobSystem>;
  • the <LobSystem> element mustn’t contain the Version-attribute;
  • the <Entity> element must contain the new attributes – Namespace and Version;
  • the <Identifier> element mustn’t contain an assembly name in its TypeName-attribute; For example, TypeName=”System.String, mscorlib” has to turn into TypeName=”System.String”;
  • the <MethodInstance> element with Type-attribute value of SpecificFinder should include the Default-attribute with value of true;
  • if the <TypeDescriptor> element has the IsCollection attribute set to true, the MethodInstance return TypeDescriptor should be updated to be an element of the collection. In practice, that means the ReturnTypeDescriptorPath-attribute with an appropriate value should be added to <MethodInstance> element, and the obsolete ReturnTypeDescriptorLevel and ReturnTypeDescriptorName attributes should be deleted;

Note that when modifying a <Entity> element, the values of the Namespace and Version attributes are copied respectively from the values of Name and Version attributes of the <LobSystem> element, which wraps the <Entity> element. The same approach is used while the in-place upgrade takes place.

After the changes are applied, and if they are sufficient for your metadata, the result files can be imported into Business Data Connectivity Service. During the import process, you may get the warnings. Consider fixing them in the future, but at the present stage you can simply ignore them. The most popular warnings are listed below:

  • This Model contains LobSystem (External System) of Type ‘WebService’ which is deprecated and may be removed in future releases.
  • The MethodInstance of type ‘Finder’ with Name ‘FindProducts’ does not have a Limit Filter.
  • The TypeDescriptor ‘From’ on Parameter ‘GetProductsFiltered’ on Method ‘GetItems’ of Entity (External Content Type) ‘Product’ with Namespace ‘ExternalProductDB’ has a DateTime value, but there is no Interpretation describing what the External System expects and returns as the DateTimeKind. The DateTime value is assumed to be UTC.
  • Note: I made the converter-application fix the warnings regarding the DateTime type and UTC, so they won’t bother you.

    The converter is very straightforward to use. Using the button ‘+’, simply add to the left section the files to be upgraded. Then click the button ‘>>’, and you’ll get the upgraded ones in the right section. Double click on file name opens an overview form to browse the input or result xml. Physically, the result files are located in c:\output folder. The application doesn’t use any SharePoint-related libraries.

    Upgrade 2007 BDC model to SP2010

    You can download the application from this page or by using the direct link. The Visual Studio 2010 solution and appropriate executable file are in the archive.

SharePoint: Migration of custom upload page derived from UploadPage to SP 2010

March 5th, 2012
No comments

    In our SharePoint 2007 application, there was a custom upload page for a document library. The custom upload page was derived from the Microsoft.SharePoint.ApplicationPages.UploadPage defined in the Microsoft.SharePoint.ApplicationPages.dll. Within application web pages, all links to the upload page were direct, while the page itself was located in the _layouts folder. After migration to the SharePoint 2010, I’ve found out that every request to the custom upload page is transferred to the Uploadex.aspx (located in the _layouts folder as well): the URL in browser corresponds to our upload page, but the content corresponds to the Uploadex.aspx. After a short investigation by means of .Net Reflector I found the reason in the UploadPage base class defined in Microsoft.SharePoint.ApplicationPages.dll, Version=14.0.0.0. Let’s take a look at the OnPreInit method of the UploadPage:

protected override void OnPreInit(EventArgs e)
{
    if (!this.customPage)
    {
        string customUploadPage = base.Web.CustomUploadPage;
        if (!string.IsNullOrEmpty(customUploadPage))
        {
            try
            {
                base.Server.Transfer(customUploadPage);
            }
            catch (Exception)
            {
            }
        }
    }
    base.OnPreInit(e);
}

*Note: this code was added in SharePoint 2010 and wasn’t presented in SharePoint 2007

As we can see, the SharePoint 2010 itself allows to define the CustomUploadPage for a website. If it’s defined, the UploadPage automatically transfers every request to it. Apparently, after migration the CustomUploadPage was somehow set to _layouts/Uploadex.aspx. Another interesting moment here is the customPage boolean field, which acts as marker indicating whether the current page is the custom upload page or not.

Probably, the acceptable solution for our issue would be to set the CustomUploadPage property of the SPWeb object to the URL of our own custom upload page. But, firstly, the problem here is that our upload page derived from the UploadPage doesn’t know that it’s a custom one as the customPage field is set to false by default. Thus, without any code modification, we will have a kind of loop here, because our custom page due to the UploadPage base class will be transferring the request to itself infinitely. Secondly, I don’t want to rely on the CustomUploadPage property, which can be unexpectedly changed. I just want when I click on the direct link to our upload page, this page would be opened without any sudden redirections and transfers.

So, the best solution is to set the customPage field to true within the constructor of our custom upload page. No transfer happens in this case, and we don’t need to deal with the CustomUploadPage at all. In our case It looks like:

public class MyUploadPage : UploadPage
{
    // ...
    public MyUploadPage()
    {
        customPage = true;
    }
    // ...
}

That’s all!