JavaScript: When parseFloat is really needed

September 22nd, 2011 No comments

     parseFloat function parses a passed string and returns a number with floating point. The given function determines whether the first character in the specified string is a number, then if it’s true, the function parses the string until it reaches the end of the number, and returns the number as a number, not as a string. In other words, parseFloat makes an explicit type conversion from a string to a proper number with floating point.

Today I’ve used this JavaScript function for the first time. On my page I extract some values from query string (window.location.search), then these values take part in some calculations. I’ve met with the fact that the calculation was absolutely wrong. Let’s see the next simplest formula:

var res = 90 + someVal;

someVal is a value extracted from query string. if someVal will be, for example, “30.555” (exactly with quotes), res will be “9030.555”. It’s kind of slightly unexpected result, though it’s absolutely explainable. JavaScript makes automatic type conversion when dealing with the operator ‘+’. If one operand is a string and the other is not, the other is converted to a string and the result is concatenated. Obviously, we have to turn string someVal into an appropriate number. parseFloat helps us out:

var someNumber = parseFloat(someVal);
var res = 90 + someNumber;

OK, now res is expectedly 120.555.

There is an alternative – Number():

var someNumber = Number(someVal);

I use parseFloat instead Number(), because in my case the value extracted from query string may contain some additional alphabetical characters. For example, I can get from query string something like “30.555oz.”. I’m too lazy to cut out the excess symbols, I prefer using parseFloat. Repeating what I said in the beginning of this article, parseFloat successfully parses a string, which starts with a string representation of a number. All symbols after last digit symbol will be ignored. That means that the string “30.555oz.” will be transformed to the number 30.555. Another string “3YQJGP7CCACF” will be transformed to 3 and so on. In contrast, Number() accepts only a valid string number without any additional symbols.

I’d like also to mention about another useful function – parseInt, which is logically associated with parseFloat. Good examples of its usage you can find here.

In addition I’d like to note that some people complain about a parseFloat rounding problem (e.g. here or here): when, for example, string “3.05” turns into number 3.04999999999…. The solution is to use the toFixed function, which formats a number to use a specified number of trailing decimals. toFixed accepts the number of digits after the decimal point.

var someNumber = parseFloat('3.05');
someNumber = someNumber.toFixed(2);

toFixed helps to overcome this rounding problem, however, for justice’ sake, I need to note that we may not always know how many digits after point our initial string number had. Therefore, the usage of toFixed function with an inappropriate number of digits may affect accuracy of calculations.

Categories: JavaScript Tags: , ,

SharePoint: How to add Content Type programmatically

September 16th, 2011 No comments

     To add a new Content Type through the SharePoint Object Model I’ve developed a few auxiliary methods and classes. The main class is ContentType class. It contains information used for specifying the required properties of the SPContentType object being added.

public class ContentType
{
    public string         ParentContentTypeName { get; set; }
    public string         Name                  { get; set; }
    public List<FieldRef> FieldRefs             { get; set; }

    public ContentTypeFormUrls   FormUrls       { get; set; }
    public ContentTypeProperties Properties     { get; set; }
    public SPContentTypeId       Id             { get; set; }
}

The FieldRefs property represents a collection of fields that have to be added to the Content Type. The other property names are self-descriptive.

The ContentType class makes reference to classes like FieldRef, ContentTypeFormUrls and ContentTypeProperties.

public class FieldRef
{
    public Guid?  ID                 { get; set; }
    public string Name               { get; set; }
    public string DisplayName        { get; set; }
    public bool?  IsRequired         { get; set; }
    public bool?  IsHidden           { get; set; }
    public bool?  IsReadOnly         { get; set; }

    public string Aggregation        { get; set; }
    public string Customization      { get; set; }
    public string PIAttribute        { get; set; }
    public string PITarget           { get; set; }
    public string PrimaryPIAttribute { get; set; }
    public string PrimaryPITarget    { get; set; }
    public string Node               { get; set; }
}

public class ContentTypeFormUrls
{
    public string DisplayFormUrl { get; set; }
    public string NewFormUrl     { get; set; }
    public string EditFormUrl    { get; set; }
}

public class ContentTypeProperties
{    
    public string Description                 { get; set; }
    public string Group                       { get; set; }
    public bool?  IsHidden                    { get; set; }
    public bool?  IsReadOnly                  { get; set; }
    public string NewDocumentControl          { get; set; }
    public bool?  RequireClientRenderingOnNew { get; set; }
    public bool?  IsSealed                    { get; set; }
}

The main method is AddContentType:

public static void AddContentType(SPWeb spWeb, SPList spList, ContentType contentType)
{
    // get appropriate parent content type
    SPContentType parentContentType = spWeb.AvailableContentTypes[contentType.ParentContentTypeName];
    if (parentContentType != null)
    {
        if (spList.ContentTypes[contentType.Name] == null)
        {
            spList.ContentTypesEnabled = true;

            // create new content type
            SPContentType spContentType = new SPContentType(parentContentType, spList.ContentTypes, contentType.Name);
            // set content type id
            SetContentTypeId(spContentType, contentType.Id);
            // set content type properties
            SetContentTypeProperties(spContentType, contentType.Properties);

            // add fields to conent type
            foreach (FieldRef fieldRef in contentType.FieldRefs)
            {
                if (spList.Fields.ContainsField(fieldRef.Name))
                {
                    SPField targetField = fieldRef.ID.HasValue ? spList.Fields[fieldRef.ID.Value] : spList.Fields.GetFieldByInternalName(fieldRef.Name);
                    if (targetField != null && !spContentType.Fields.ContainsField(fieldRef.Name))
                    {
                        SPFieldLink fLink = new SPFieldLink(targetField);
                        SetFieldRefProperties(fLink, fieldRef);
                        spContentType.FieldLinks.Add(fLink);
                    }
                }
                else
                    Console.Write(string.Format("Couldn't find field {0} in the list {1}", fieldRef.Name, spList.Title));
            }

            // set content type form urls
            SetContentTypeFormUrls(spContentType, contentType.FormUrls);

            // save changes
            spList.ContentTypes.Add(spContentType);
            spContentType.Update();
            spList.Update();
        }
        else
            Console.Write(string.Format("Content type {0} already exists in the list {1}", contentType.Name, spList.Title));
    }
    else
        Console.Write(string.Format("Couldn't find the parent content type {0}", contentType.ParentContentTypeName));
}

It utilizes SetContentTypeFormUrls, SetContentTypeProperties, SetFieldRefProperties and SetContentTypeId (you can read about the last method in detail in my other post – How to set Id to just created SPContentType).

public static void SetContentTypeFormUrls(SPContentType spContentType, ContentTypeFormUrls contentTypeFormUrls)
{
    if (contentTypeFormUrls == null)
        return;

    if (contentTypeFormUrls.NewFormUrl != null)
        spContentType.NewFormUrl = contentTypeFormUrls.NewFormUrl;

    if (contentTypeFormUrls.DisplayFormUrl != null)
        spContentType.DisplayFormUrl = contentTypeFormUrls.DisplayFormUrl;

    if (contentTypeFormUrls.EditFormUrl != null)
        spContentType.EditFormUrl = contentTypeFormUrls.EditFormUrl;
}

public static void SetContentTypeProperties(SPContentType spContentType, ContentTypeProperties cntProps)
{
    if (cntProps == null)
        return;

    if (cntProps.Description != null)
        spContentType.Description = cntProps.Description;
    if (cntProps.Group != null)
        spContentType.Group = cntProps.Group;
    if (cntProps.IsHidden != null)
        spContentType.Hidden = cntProps.IsHidden.Value;
    if (cntProps.IsReadOnly != null)
        spContentType.ReadOnly = cntProps.IsReadOnly.Value;
    if (cntProps.IsSealed != null)
        spContentType.Sealed = cntProps.IsSealed.Value;
    if (cntProps.NewDocumentControl != null)
        spContentType.NewDocumentControl = cntProps.NewDocumentControl;
    if (cntProps.RequireClientRenderingOnNew != null)
        spContentType.RequireClientRenderingOnNew = cntProps.RequireClientRenderingOnNew.Value;
}

public static void SetContentTypeId(SPContentType spContentType, SPContentTypeId contentTypeId)
{
    try
    {
        FieldInfo fi = typeof(SPContentType).GetField("m_id", BindingFlags.NonPublic | BindingFlags.Instance);
        if (fi != null)
            fi.SetValue(spContentType, contentTypeId);
        else
            Console.Write("Couldn't set content type id!");
    }
    catch(Exception ex)
    {
        Console.Write(string.Format("Couldn't set content type id! {0}", ex.Message));
    }
}

public static void SetFieldRefProperties(SPFieldLink fLink, FieldRef fieldRef)
{
    if (fieldRef == null)
        return;

    if (fieldRef.DisplayName != null)
        fLink.DisplayName = fieldRef.DisplayName;
    if (fieldRef.IsHidden != null)
        fLink.Hidden = fieldRef.IsHidden.Value;
    if (fieldRef.IsRequired != null)
        fLink.Required = fieldRef.IsRequired.Value;
    if (fieldRef.IsReadOnly != null)
        fLink.ReadOnly = fieldRef.IsReadOnly.Value;

    if (fieldRef.Aggregation != null)
        fLink.AggregationFunction = fieldRef.Aggregation;
    if (fieldRef.Customization != null)
        fLink.Customization = fieldRef.Customization;
    if (fieldRef.PIAttribute != null)
        fLink.PIAttribute = fieldRef.PIAttribute;
    if (fieldRef.PITarget != null)
        fLink.PITarget = fieldRef.PITarget;
    if (fieldRef.PrimaryPIAttribute != null)
        fLink.PrimaryPIAttribute = fieldRef.PrimaryPIAttribute;
    if (fieldRef.PrimaryPITarget != null)
        fLink.PrimaryPITarget = fieldRef.PrimaryPITarget;
    if (fieldRef.Node != null)
        fLink.XPath = fieldRef.Node;
}

Here is how you can use all of that stuff:

public void AddSomeContentType(SPWeb spWeb, SPList spList)
{
    ContentType newContentType = new ContentType()
    {
        ParentContentTypeName = "Item",

        Id   = new SPContentTypeId("0x0100078C8B39671A4532AB9C5AB6DCB388A6"), // id has to correspond to the parent content type
        Name = "some new content type name",

        Properties = new ContentTypeProperties() { Description = "super modern content type", Group = "List Content Types" },
        FormUrls   = new ContentTypeFormUrls() { DisplayFormUrl = "Lists/your list name/your custom page name.aspx" },
        FieldRefs  = new List<FieldRef>() 
            { 
                new FieldRef() { Name = "Title",  ID = new Guid("{fa564e0f-0b71-4ab7-b863-0177e6ddd247}"), IsRequired = false, IsReadOnly = true, DisplayName = "List Item Title" },
                new FieldRef() { Name = "Status", IsRequired = true, DisplayName = "List Item Status" },
                new FieldRef() { Name = "Involved_User", ID = new Guid("869963ef-9ca3-4ad7-a5f0-8fff724a6877"), DisplayName = "User Involved" } 
            }
    };

    AddContentType(spWeb, spList, newContentType);
}

Please note that you don’t have to fill out all properties of the auxiliary classes (ContentTypeProperties, ContentTypeFormUrls and FieldRef); the unspecified properties will be merely ignored, and the appropriate properties of SPContentType object will be left with their default values. Als,o pay attention to the fact that Content Type identifier has to contain the id of parent Content Type. Find out how to build a Content Type identifier recursively here.

SharePoint: How to set Id to just created SPContentType

September 15th, 2011 No comments

     When adding Content Type programmatically, sometimes you may need to set a certain Id to it, to ensure that other parts of the application can refer to the Content Type using a known identifier. If you use SharePoint 2010 you can get this done instantly, as SharePoint 2010 provides a handy SPContentType constructor, which accepts SPContentTypeId as parameter:

public SPContentType(SPContentTypeId contentTypeId, SPContentTypeCollection contentTypes, string name);

But if you use SharePoint 2007, you don’t have such a constructor or any built-in means to set the required identifier. Besides, the Id property of SPContentType appears to be read-only. After studying the SPContentType class with Reflector I’ve discovered that the Content Type id is stored in the private m_id property:

private SPContentTypeId m_id;

This means that we can use Reflection to set this property. Here is a special SetContentTypeId method I’ve implemented for doing that:

public void SetContentTypeId(SPContentType spContentType, SPContentTypeId contentTypeId)
{
    try
    {
        FieldInfo fi = typeof(SPContentType).GetField("m_id", BindingFlags.NonPublic | BindingFlags.Instance);                
        fi.SetValue(spContentType, contentTypeId);                
    }
    catch (Exception ex)
    {
        Console.Write(string.Format("Couldn't set content type id! {0}", ex.Message));
    }
}

The method accepts the instance of the SPContentType class and the required identifier as the instance of the SPContentTypeId class. Here is an example of use:

public void AddSomeNewContentType(SPWeb spWeb, SPList spList)
{
    SPContentType parentContentType = spWeb.AvailableContentTypes["some parent content type name"];
    if (parentContentType != null)
    {
        SPContentType spContentType = new SPContentType(parentContentType, spList.ContentTypes, "some new content type name");
        SetContentTypeId(spContentType, new SPContentTypeId("0x0100078C8B39671A4532AB9C5AB6DCB388A6")); // content type id you need has to be here, for example 0x0100078C8B39671A4532AB9C5AB6DCB388A6

        // set other properties of content type

        spList.ContentTypes.Add(spContentType);
        spContentType.Update();
        spList.Update();
    }
}

Please note that you must NOT use the SetContentTypeId method with existing built-in or earlier created Content Types. Otherwise, it may corrupt the SharePoint data integrity, especially when there are list items created based on the changed Content Type.

Note again, use the SetContentTypeId method ONLY immediately following the creation of a Content Type and ONLY before adding it to whatever collection of Content Types or before calling SPContentType.Update(). This is very important.

My next post describes how to add Content Type programmatically.

SharePoint: How to enumerate shared services

August 19th, 2011 No comments

     Continuing the previous article – How to get Shared Service name, I’m going to show how to enumerate all available Shared Services (or Shared Resource Providers, to be more precise). Here is the code (with Reflection, of course 🙂 ) :

public static void EnumerateSharedServices(SPSite spSite, Action<object> action)
{
    ServerContext serverContext = ServerContext.GetContext(spSite);
    object serverFarm = serverContext.GetType().GetField("m_ServerFarm", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(serverContext);
    var sspCollectionProp = serverFarm.GetType().GetProperty("SharedResourceProviders");
    var sspCollection = sspCollectionProp.GetValue(serverFarm, null) as IEnumerable;
    foreach (SPPersistedObject sharedServiceProvider in sspCollection)
        action(sharedServiceProvider);    
}

You have to use Reflection to get a property value of a Shared Service Provider; the general use of it is something similar to this:

EnumerateSharedServices(SPContext.Current.Site, delegate(object sharedResourceProvider)
{
    string sspName     = sharedResourceProvider.GetType().GetProperty("Name").GetValue(sharedResourceProvider, null).ToString(); 
    string sspUserName = sharedResourceProvider.GetType().GetProperty("UserName").GetValue(sharedResourceProvider, null).ToString();      
    string sspPassword = sharedResourceProvider.GetType().GetProperty("Password").GetValue(sharedResourceProvider, null).ToString();

    Console.WriteLine(string.Format("{0} [UserName: {1}, Passw: {2}]", sspName, sspUserName, sspPassword));

    // enumerate web applications that are served by the shared service
    var appCollection = sharedResourceProvider.GetType().GetProperty("WebApplications").GetValue(sharedResourceProvider, null) as System.Collections.IEnumerable;
    foreach (Microsoft.SharePoint.Administration.SPWebApplication app in appCollection)
        Console.WriteLine(string.Format("Web app: {0}", app.Name));
});

Let’s take a deeper look at EnumerateSharedServices. Its key object is serverFarm, which is an object of the internal ServerFarm class (the Microsoft.Office.Server.Administration namespace in the Microsoft.Office.Server DLL) containing a collection of Shared Resource Providers (collection of SharedResourceProvider objects). Navigating through this collection an user action is called for each provider.

To make this code more readable, I’d recommend using an object-wrapper for Shared Resource Provider. For example:

public class SharedServiceInfo
{
    protected readonly object _rawSharedResourceProvider;

    public string Name
    {
        get { return GetPropertyValue("Name").ToString(); }
    }
    public string UserName
    {
        get { return GetPropertyValue("UserName").ToString(); }
    }
    public string Password
    {
        get { return GetPropertyValue("Password").ToString(); }
    }
    public List<SPWebApplication> WebApplications
    {
        get 
        {
            IEnumerable iEnumerable = (IEnumerable)GetPropertyValue("WebApplications");
            return new List<SPWebApplication>(iEnumerable.Cast<SPWebApplication>()); 
        }
    }

    public SharedServiceInfo(object rawSharedResourceProvider)
    {
        _rawSharedResourceProvider = rawSharedResourceProvider;
    }

    protected object GetPropertyValue(string propName)
    {
        return _rawSharedResourceProvider.GetType().GetProperty(propName).GetValue(_rawSharedResourceProvider, null);
    }
}
public static void EnumerateSharedServices(SPSite spSite, Action<SharedServiceInfo> action)
{
    ServerContext serverContext = ServerContext.GetContext(spSite);
    object serverFarm = serverContext.GetType().GetField("m_ServerFarm", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(serverContext);

    var sspCollectionProp = serverFarm.GetType().GetProperty("SharedResourceProviders");
    var sspCollection = sspCollectionProp.GetValue(serverFarm, null) as IEnumerable;
    foreach (SPPersistedObject sharedServiceProvider in sspCollection)
        action(new SharedServiceInfo(sharedServiceProvider));
}

You can extend SharedServiceInfo with the properties you need.

Sample of usage:

EnumerateSharedServices(SPContext.Current.Site, delegate(SharedServiceInfo sharedServiceInfo)
{
    Console.WriteLine(string.Format("{0} [UserName: {1}, Passw: {2}]", sharedServiceInfo.Name, sharedServiceInfo.UserName, sharedServiceInfo.Password));

    // enumerate web applications that are served by the shared service
    foreach (Microsoft.SharePoint.Administration.SPWebApplication app in sharedServiceInfo.WebApplications)
        Console.WriteLine(string.Format("Web app: {0}", app.Name));
});

SharePoint: How to get Shared Service name

August 18th, 2011 No comments

     As you probably know, you can deploy several Shared Services in a SharePoint farm, having each of them serve one or more web applications. If you need to get the name of Shared Serviceserving your web application programmatically, you can use the following method:

public static string GetSharedServiceName(SPSite spSite)
{
    try
    {
        ServerContext sc = ServerContext.GetContext(spSite);
        PropertyInfo srpProp = sc.GetType().GetProperty("SharedResourceProvider", BindingFlags.NonPublic | BindingFlags.Instance);
        object srp = srpProp.GetValue(sc, null);
        PropertyInfo srpNameProp = srp.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
        string sspName = (string)srpNameProp.GetValue(srp, null);
        return sspName;
    }
    catch
    {
        return null;
    }
}

The method looks a bit obscure because of Reflection we have to use, as there is no supported way to get what we need without it. The ServerContext object contains the internal SharedResourceProvider property, which is an object of the internal SharedResourceProvider class. So, there is no way we can do that without using Reflection.

Please also note that according to MSDN, the ServerContext object provides run-time methods for Shared Services in Microsoft Office SharePoint Server 2007. In other words, ServerContext is available only in MOSS (I’m talking about SharePoint 2007. Yes, I still use it 🙂 ). The ServerContext is defined in Microsoft.Office.Server.Administration namespace in the Microsoft.Office.Server DLL.

Example of use:

string sharedServiceName = GetSharedServiceName(SPContext.Current.Site);