Ajax Toolkit date range pickers in SharePoint Online

I was always a fan of Microsoft Ajax Toolkit JavaScript. In the past was some documentation about how to use it only on client side, but now it seems the documentation is only about how to use it with server side components which generate for you JavaScript code. Unfortunately, you cannot do this on SharePoint Online, so I have decided to extract files from the latest version created under the governance of DevExpress and apply them in SharePoint Online environment.

Files preparation

Download files from this location, extract them from archive and upload them into a folder located on SharePoint. All of them should be in the same folder, so please don’t change their location relative to start.js file. Start.js file is an old files on demand loader created by Microsoft, which is not popular but I still consider to be the best option for what Microsoft has created.

Then, in your aspx file, using script manager or script proxy manager, add reference to these files.

<asp:ScriptManager runat="server" LoadScriptsBeforeUI="false">
<asp:ScriptReference Path="../Common/Resources/Resources.js" />
<asp:ScriptReference Path="../Common/Start.js" />
<asp:ScriptReference Path="../Common/Extended.js" />

Also, please create a reference to CSS file included in the archive.


Now as we have already a loader, we don’t need to worry about loading order of the files or if the files are already loaded or not. We just need to place our logic into Sys.require function calling.

Sys.require([Sys.scripts.Calendar], function () {
// Logic is placed here

In the HTML mark-up, please create two SharePoint text input controls.

<SharePoint:InputFormTextBox runat="server" ClientIDMode="Static" ID="startDate" />
<SharePoint:InputFormTextBox runat="server" ClientIDMode="Static" ID="endDate" />

We should start now creating the logic. Starting from somewhere, we can create two simple independent date pickers.

    $create(Sys.Extended.UI.CalendarBehavior, { id: 'startDate', format: 'yyyy-MM-dd'}, {}, null, $get('startDate'));
    $create(Sys.Extended.UI.CalendarBehavior, { id: 'endDate', format: 'yyyy-MM-dd' }, {}, null, $get('endDate'));

If everything goes as expected, we should have now two date pickers with no relationship between them. However, selecting a range means end date should be greater or equal with start date, so we need to create a relationship. For this, we need to attach a handler for date change event on start date client control.

        $create(Sys.Extended.UI.CalendarBehavior, { id: 'startDate', format: 'yyyy-MM-dd' }, {
            dateSelectionChanged: function (instance) {

                var dt = instance.get_selectedDate();

                // Add this only if you want to adjust end date automatically according the start date selection


        }, null, $get('startDate'));
        $create(Sys.Extended.UI.CalendarBehavior, { id: 'endDate', format: 'yyyy-MM-dd', startDate: $get('startDate').value }, {}, null, $get('endDate'));

I would say this is all you need for this functionality. What I like on this implementation is actually you can choose if your end date is automatically adjusted or not. When I have used jQuery date pickers, I couldn’t remove this option or it is hidden somewhere and I am not aware about. However, for complicated forms, customers requested to remove automatically adjustment, because users in general will use it to bypass validation and will start enter wrong information.


“Value is not among the set of valid lookup values” error saving a form in MOSS 2007

If you are using MOSS 2007 and you see “Value is not among the set of valid lookup values” error when you save a form, this is caused by a look-up field. Unfortunately, being an old system, SharePoint 2007 doesn’t render this type of field as a select HTML element. Instead it appears to be a textbox HTML element with some associated JavaScript events handlers. This means, an user can actually write down a value which doesn’t exist in the look-up list.


Now as you know where is the problem, you can restrict the user’s input by changing SharePoint:FormField control associated for the column with a SharePoint:DVDropDownList displaying values provided by a SharePoint:SPDataSource. So instead of having a code like this:

<SharePoint:FormField runat="server" id="ff1{$Pos}" ControlMode="New" FieldName="InternalFieldName" __designer:bind="{ddwrt:DataBind('i',concat('ff1',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@InternalFieldName')}"/>

you can a new code:

<SharePoint:DVDropDownList runat="server" id="ff1{$Pos}" DataSourceID="SPDataSourceId" DataValueField="ID" DataTextField="Title" __designer:bind="{ddwrt:DataBind('i',concat('ff1',$Pos),''SelectedValue','SelectedIndexChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@InternalFieldName')}" />

Please note the followings:

  • Drop down control is getting the data from an SPDataSource and data value field is ID.
  • Data text field is set to Title, but can be any other column from look-up list you want to display.
  • __designer:bind attribute was changed and ‘Value’ parameter changed with ‘SelectedValue’ and ‘ValueChanged’ was changed with ‘SelectedIndexChanged’.

I hope this will help you fixing the issue. In case you are planing to upgrade from MOSS 2007, you should not be worry about it anymore, as this was fixed. I checked on SharePoint Online, SharePoint 2013 and 2010 version.

Access data cross sub-sites – an old way which is still reliable

This post is about how you can read the data from one sub-site to another sub-site. As a special note, I am not talking about how to access data from one site to another inside the same site collection. Is a common confusion to name site collection what is actually top level site.

As a practical example for this article, we need to display data from a sub-site called “Primary Site”, with URL “/PrimarySite”, into a drop down list control placed in a page inside “Secondary Site”, with URL “/SecondarySite”. Need to mention the top level site has the following URL: domain.com/sites/toolkit/.

To do the task, all you need are several lines:

<SharePoint:DVDropDownList runat="server" DataSourceID="SourceOfData" DataValueField="Title" DataTextField="Title">

<SharePoint:SPDataSource runat="server" DataSourceMode="List" ID="SourceOfData" SelectCommand='<![CDATA[<View></View>]]>'>
<asp:Parameter Name="ListName" DefaultValue="Data Source List" />
<asp:Parameter Name="WebUrl" DefaultValue="/sites/toolkit/PrimarySite" />

Please note importance and effect of WebUrl select parameter, which should be composed from URL of the parent site (excluding of course domain.com part) and URL of the sub-site where list to serve as data source is created.

This might help you working with custom forms. And sometimes, I think these are better than complicated JavaScript solutions.

“Folder name is not valid” error trying to open a SharePoint Online site with SharePoint Designer

I was experiencing an error trying to open a SharePoint Online website with SharePoint Designer. I was receiving “Folder name is not valid” error and opened a request to SharePoint Online Support Team. I need to tell you the support was very good in this case. They figure out fast was an access denied issue causing the error.

It turned out the solution was an easy one, even I am not sure how happy customers can be with it. When you log to SharePoint Online using your credentials you need to check “Keep me signed in” option.

2015-03-20 11_37_34-Sign in to Office 365

After login step, you need to browse at least once website you are trying to open. This being told, you can try to apply this for future cases, until Microsoft will publish the solution on their site.

Select unique values and create grouping headers in dataformwebpart

Dataformwebpart is probably one the most powerful web parts in SharePoint environment. But one of the biggest problems is it is not very well known by the developers, therefore is considered to be hard to work with. I don’t feel the same and I am still digging into it.

One of the recent challenges working with it was to create from scratch grouping functionality, which is very close related to select distinct values technique in XSLT. Let’s take steps one by one.

First thing, I need to set a parameter to define dynamically grouping criteria. This consists into two changes. One is to bind the parameter in “ParameterBindings” section.

<ParameterBinding  Name="GroupBy" Location="QueryString(GroupBy)" DefaultValue="Title" />

The second step is to let know SPDataSource about parameter and execute select command according to it’s value.

<SharePoint:SPDataSource runat="server" DataSourceMode="List" UseInternalName="true" UseServerDataFormat="false" selectcommand='<![CDATA[<View><Query><GroupBy><FieldRef="{GroupBy}" /></GroupBy></Query></View>]]>'>
<WebPartPages:DataFormParameter Name="ListName" ParameterKey="ListName" PropertyName="ParameterValues" />
<WebPartPages:DataFormParameter Name="GroupBy" ParameterKey="GroupBy" PropertyName="ParameterValues" />

Now, it remained to work with XSLT. This should start with the following code.

<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal">
<xsl:param name="GroupBy" />


Now as our XSLT knows about GroupBy parameter, I need to create grouping headers template and select only distinct values for grouping field.

<xsl:template match="/" xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:SharePoint="Microsoft.SharePoint.WebControls">

				<xsl:call-template name="GroupHeaders">


<xsl:template name="GroupHeaders">
<xsl:for-each select="/dsQueryResponse/Rows/Row[not(@*[name() = $GroupBy] = preceding-sibling::Row/@*[name() = $GroupBy])]">
<xsl:variable name="Attr" select="current()/@*[name() =  $GroupBy]" />
<td><xsl:value-of select="$Attr" /></td>

Please note how select distinct XSLT technique can adapted to be applied dynamically based on a parameter value. And now is time to call template for showing data for each displayed header.

<xsl:template name="GroupHeaders">
<xsl:for-each select="/dsQueryResponse/Rows/Row[not(@*[name() = $GroupBy] = preceding-sibling::Row/@*[name() = $GroupBy])]">
<xsl:variable name="Attr" select="current()/@*[name() =  $GroupBy]" />
<td><xsl:value-of select="$Attr" /></td>
<xsl:with-param name="nodeName" select="$GroupBy" />
<xsl:with-param name="nodeValue" select="$Attr" />

<xsl:template name="RowView">
<xsl:param name="nodeName" />
<xsl:param name="nodeValue" />
<xsl:for-each select="/dsQueryResponse/Rows/Row[@*[name() = $nodeName] =  $nodeValue]">
<td><xsl:value-of select="@Title" /></td>

I hope this will help you customizing the web part. If you have any question, don’t hesitate to contact me on anvlpopescu@yahoo.com. As always, my code is not perfect, but can give you a start. Happy Codding!

Create a hierarchical jQuery date pickers structure

A was working recently with a SharePoint custom form with contains a lot of textbox controls to server as date pickers. Of course, as many other developers, I choose jQuery date picker. So far, so good, but one the requests was to put a series of 4 or 5 controls in hierarchical structure. In other words, date selection of one control was not supposed to be less than previous control selection.

Documentation of jQuery date picker range selection is limited to 2 controls. So to bypass this, I created an Ajax non visual control to integrate and extend this functionality to more date pickers. I will present the code below, which is not very complicated for someone who works with Microsoft Ajax controls.

/// <Reference Name="MicrosoftAjax.js" />


Sys.HierarchicDatePickers = function () {
    /// <summary>Create an instance of Sys.HierarchicDatePickers class</summary>
    Sys.HierarchicDatePickers.initializeBase(this, []);

    this._datepickersIds = [];
    this._pickersOptions = {};
    this._dateChanged = null;

Sys.HierarchicDatePickers.prototype = {

    initialize: function () {

        var instance = this;

        // Overwrite format date option if specified (will be improve in the next version)
        instance._pickersOptions['dateFormat'] = 'yy-mm-dd';

        for (var i = 0; i < this._datepickersIds.length; i++) {

            var ctl = $get(this._datepickersIds[i]);
            var jCtl = jQuery('#' + this._datepickersIds[i]);

            // If date picker is initialized, change date format option to our standard
            if (Sys.UI.DomElement.containsCssClass(ctl, 'hasDatepicker') === true) {
                jCtl.datepicker('option', 'formatDate', 'yy-mm-dd');

            // If date picker is not initialized, create date picker
            if (Sys.UI.DomElement.containsCssClass(ctl, 'hasDatepicker') === false) {

            // Trigger change event when date picker is closed, we will keep and execute also first previous on close handler
            var prevOnClose = jCtl.datepicker('option', 'onClose');
            jCtl.datepicker('option', 'onClose', function (dt, inst) {
                if (prevOnClose !== null) prevOnClose(dt, inst);




    dispose: function () {
        this._dateChanged = null;
        this._pickersOptions = null;
        Sys.HierarchicDatePickers.callBaseMethod(this, 'dispose');

    _add_changeHandler: function (index) {
        /// <summary>Add change handler for control (internal method)</summary>
        /// <param name="index"></param>
        var instance = this;

        $addHandler($get(this._datepickersIds[index]), 'change', function (evt) {
            if (instance._dateChanged !== null) instance._dateChanged.apply(instance);

    _triggerChange: function (element) {
        /// <summary>Trigger change event</summary>

        if ("createEvent" in document) {
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent("change", false, true);
        else {

    _setPickersMinDate: function () {
        /// <summary>Set picker min date (internal method)</summary>

        var minDate = $get(this._datepickersIds[0]).value.toString().trim();
        for (var i = 1; i < this._datepickersIds.length; i++) {
            var prev = $get(this._datepickersIds[i - 1]).value.toString().trim();
            minDate = (prev === '') ? minDate : prev;
            jQuery('#' + this._datepickersIds[i]).datepicker('option', 'minDate', minDate);

    set_id: function (id) {
        /// <summary>Set id for current instance of Sys.HierarchicDatePickers class</summary>
        /// <param name="id" type="String" mayBeNull="false" optiona='false">Id</param>
        /// <returns type="Sys.HierarchicDatePickers" />
        var e = Function.validateParameters(arguments, [{ name: 'id', type: String, mayBeNull: false, optional: false }], true);
        if (e) throw e;

        this._id = id;

    get_id: function () {
        /// <summary>Get id for current instance of Sys.HierarchicDatePickers class</summary>
        /// <returns type="String" />

        return this._id;

    set_pickersOptions: function (options) {
        /// <summary>Set date pickers options</summary>
        /// <param name="options" type="Object" mayBeNull="false" optiona='false">Pickers options</param>
        /// <returns type="Sys.HierarchicDatePickers" />
        var e = Function.validateParameters(arguments, [{ name: 'options', type: Object, mayBeNull: false, optional: false }], true);
        if (e) throw e;

        this._pickersOptions = options;
        return this;

    get_pickersOptions: function (options) {
        /// <summary>Get date pickers options</summary>
        return this._pickersOptions;

    set_datepickersIds: function (ids) {
        /// <summary>Set date pickers controls id</summary>
        /// <param name="ids" type="Array" elementType="String" elementMayBeNull="false">Controls id</param>
        /// <returns type="Sys.HierarchicDatePickers" />

        var instance = this;
        for (var i = 0; i < ids.length; i++) {
            var id = ids[i];
            if ($get(id) !== null && $get(id).tagName === 'INPUT' && $get(id).type === 'text') {
        return instance;

    get_datepickersIds: function () {
        /// <summary>Get date pickers id</summary>
        /// <returns type="Array" elementType="String" />

        var instance = this;
        return instance._datepickersIds;

    add_dateChanged: function (handler) {
        /// <summary>Add handler for date changed event</summary>
        /// <param name="handler" type="Function" mayBeNull="false" optional="false">Handler function</param>
        /// <returns type="Sys.HierarchicDatePickers" />
        var e = Function.validateParameters(arguments, [{ name: 'handler', type: Function, mayBeNull: false, optional: false }], true);
        if (e) throw e;

        this._dateChanged = handler;
        return this;

    remove_dateChanged: function () {
        /// <summary>Remove handler for date changed event</summary>
        this._dateChanged = null;


Sys.HierarchicDatePickers.registerClass('Sys.HierarchicDatePickers', Sys.Component);

For the moment, there are some limitation I want to bypass in the future. One of them is I am using YYYY-MM-DD date format, because is easy to work with it as string. But with a little help of some contributors, this can be extended.

Now, let’s assume we have 4 textbox controls with following id properties: StartDate, MiddleDate, AfterMiddleDate, EndDate. The requests is, of course, to have always dates selection in ascending in order. To do this we need put them in an array in the order we want to be.

var datepickers = ['StartDate', 'MiddleDate', 'AfterMiddleDate', 'EndDate'];

We might also want to add options for jQuery date pickers initialization and add a handler for change event.

var datepickersOptions = {
  buttonImage: '/teams/dealsupport/images/calendar.gif',
  showOn: 'button',
  buttonText: 'Select Date'

var changedHandler = function() {
// Do something here
// You can reference to instance of Sys.HierarchicDatePickers with this keyword

And now, the only thing we need to do is to initialize the class using $create Ajax function, which make our object life cycle to be managed by Ajax framework.

$create(Sys.HierarchicDatePickers, { 'id': 'pickers', 'datepickersIds': datepickers, 'pickersOptions': datepickersOptions }, { 'dateChanged': 	changedHandler }, {}, null);

Is not the perfect solution, but you can improve it and extend it and make it better. In any case, I think is an easier solution than writing lines and lines of code each time you need to have this functionality. Inheriting Sys.Component class, the code is ready to be reusable.

Wrap error message for a web form validator

For a lot of developers, web forms technology is not the first choice. However, if you are required to work with web forms, you will probably work with aspx validators. And one of the problems is to wrap error message for the validator. Solution is very simple, even is not straight forward.

We assume we have this control and we set the size to 200px.

<asp:TextBox runat="server" Width="200px" ID="RequiredField" />

If we place below a required field validator with Display property set to Dynamic and we also set a very long error message, it will appear of course longer than 200px and it might affect the layout. To bypass this problem, we can wrap the validator into a div.

        <div style="display:block; width:200px; white-space:normal">
            <asp:RequiredFieldValidator runat="server" ErrorMessage="A text longer than 200px" ControlToValidate="RequiredField" Display="Dynamic"  />

I know is not perfect solution, but is simple and is doing the job.