Moustafa Refaat
Login   Search
Skip Navigation Links
Home
Publications
Service Offerings
Downloads and Samples
My Resume
Endorsements
Contact Me
Books
Technical Articles
Software Packages
Scroll up
Scroll down
BizTalk The Practical Course
Mastering The BizTalk Technical Interview
Soduku:Challenging Puzzels
Scroll up
Scroll down
Design Patterns Review
Software Architecture Basics Review
Simplified BizTalk Content Based Routing for a Pass_Throu data
An Extensible Light Xml Rules Engine Component
Secure Messaging Solution
Create a SQL Database Programmatically
BizTalk Unzip Adapter
Implementing Singleton pattern with BizTalk Orchestrations
Developing BizTalk Custom Adapters
BizTalk ESB Toolkit Experience Series
Scroll up
Scroll down
Setting the ESB Toolkit on the 64 Bit Machines
How The ESB Works
Sample Custom Resolver
Scroll up
Scroll down
Recent Training
Scroll up
Scroll down

News List

  • iBTSInterview (BizTalk Technical Interview) is available on iPhone and iPad
  • Toronto Code Camp Presentation is uploaded
  • BizTalk: The Practical Course is recommended by Micorsoft
  • Canadian Gigs Network (www.CanadianGigs.Net) a job web site focusing on Canadian Jobs
  • BizTalk Technical Interview Preparation
  • GT-DataSafe© Online Backup for Amazon Storage Services 3.0 is released
  • Soduku Challenging Puzzles
  • BizTalk: The Practical Course
  • Mastering The BizTalk Technical Interview is Published Now Avaliable on iPhone an iPad

Technical Articles

  • ArchiMate 3.0 Simplified
  • http://moustafarefaat.blogspot.ca/2016/11/installing-hadoop-273-on-macos-sierra.html
  • BizTalk: Implementing Web Pages with a BizTalk Endpoint
  • BizTalk: Process HTTP Post Information
  • BizTalk: ESB Itinerary as a Template
Skip Navigation Links
> Blog entries about: SharePoint
JavaScript, and SharePoint Calculated Field Trick

I had a client who wanted to display and indicator showing the task list status as of today, for example: if  there is more than 15 days for the task due date display a green light image, less than 15 days display yellow light image, the task is already late display a red light image.

 

 

Simple, however, this client is hosting the SharePoint out of site and we can not deploy custom code at all. I can use an calculate field to select the image to display however that image would not get updated unless a user updates the task, I can write a timer that would run daily and update the filed but that is not possible as I can not deploy custom code, or I can write a custom code that runs a client machine using SharePoint APIs iterates through the task list and updates the items causing all calculated fields to be re-evaluated. The problem with this solution is that it is kind of dependent on having a client machine that would run this code periodically and frankly kind of a messy solution. After researching many of the info on the internet, and a friend’s brains, we devised the following solution.

 

The calculated field would contain a simplified date and a javascript would run in the browser updating the field with HTML with the proper image info and executing that HTML.

 

 

 

<script type="text/javascript">

//<!-- This script searches for calculated fields that are "marked" vith "Due:" and         -->

//<!-- Create a calculated field in the list with the following formula:                    -->

//<!-- =IF(DueDate="","N/A","Due: "&MONTH(DueDate)&"/"&DAY(DueDate)&"/"&YEAR(DueDate))      -->

//<!-- The data type returned from this formula is: Date and Time                           -->

// call script

findDatefields();

function findDatefields() {

    var d = new Date();

    var today = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();

 

    var arr = document.getElementsByTagName('td');

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

        // Check if it is "our field"

        if ((arr[i].className == "ms-vb2") && (arr[i].innerHTML.indexOf("Due:") == 0)) {

            var sepDate = arr[i].innerHTML.substring(5).split("/", 3);

            var m = sepDate[0];

            var d = sepDate[1];

            var y = sepDate[2];

 

            // build the datestring

            var fieldDate = new Date(y, m - 1, d, 00, 00, 00).getTime();

            if (fieldDate > today) {

                arr[i].innerHTML = "<IMG src='_layouts/images/KPIDefault-0.gif' Title='On track' />";

            }

            else if (fieldDate == today) {

                arr[i].innerHTML = "<IMG src='_layouts/images/KPIDefault-1.gif' Title='Due today' />";

            }

            else {

                arr[i].innerHTML = "<IMG src='_layouts/images/KPIDefault-2.gif' Title='Overdue' />";

            }

        }

    }

}

// For it to work in collapsed views

function ExpGroupRenderData(htmlToRender, groupName, isLoaded) {

    var tbody = document.getElementById("tbod" + groupName + "_");

    var wrapDiv = document.createElement("DIV");

    wrapDiv.innerHTML = "<TABLE><TBODY id=\"tbod" + groupName + "_\" isLoaded=\"" + isLoaded + "\">" + htmlToRender + "</TBODY></TABLE>";

    tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild, tbody);

    findDatefields();

}

</script>

 

You can check the following links for information on this subject  

  •  Dynamically Updating A SharePoint Calculated Column Containing A "Today" Reference http://vspug.com/dez/2008/07/31/dynamically-updating-a-sharepoint-calculated-column-containing-a-quot-today-quot-reference/
  • Date Functions in Calculated Fields http://blogs.msdn.com/b/sharepointdesigner/archive/2008/08/01/date-functions-in-calculated-fields.aspx
{28/02/2011 9:17 AM} {2 comments}  {Tags: SharePoint, JavaScript}
Customizing the XSLTListView Web Part

In a project I was working in I wanted to customize how the blog post was displayed. The Post.aspx in the Post list uses the new WebPartPages:XsltListViewWebPart, which is a new web part in SharePoint 2010. I would not bore you with a lot of background and stuff that You can read in the MSDN. I will just describe the solution that I implemented.  I had to change the XSL Link  it uses in Miscellaneous  options of the web part and implement  the template as follows

<!-- BaseViewID='7' and TemplateType='301' is Posts.aspx view for Blog's posts list -->

  <xsl:template match="View[@BaseViewID='7' and List/@TemplateType='301']" mode="full">

    <xsl:apply-templates select="." mode="AdeccoRenderView" />

   

  </xsl:template>

 

  <xsl:template match="View" mode="AdeccoRenderView">

    <xsl:variable name="ViewStyleID">

      <xsl:value-of select="ViewStyle/@ID"/>

    </xsl:variable>

  

    <!-- total first -->

 

    <xsl:variable name="HasExtraColumn" select="$TabularView='1' and $MasterVersion=4 and ($ViewStyleID = '' or $ViewStyleID = '17')"/>

    <xsl:variable name="Fields" select="ViewFields/FieldRef[not(@Explicit='TRUE')]"/>

    <xsl:variable name="Groups" select="Query/GroupBy/FieldRef"/>

    <xsl:variable name="Collapse" select="Query/GroupBy[@Collapse='TRUE']"/>

    <xsl:variable name="GroupCount" select="count($Groups)"/>

    <xsl:if test="Aggregations[not(@Value='Off')]/FieldRef">

      <tr>

        <xsl:if test="$HasExtraColumn">

          <td/>

        </xsl:if>

        <xsl:if test="$InlineEdit">

          <td width="1%"/>

        </xsl:if >

        <xsl:apply-templates mode="aggregate" select="ViewFields/FieldRef[not(@Explicit='TRUE')]">

          <xsl:with-param name="Rows" select="$AllRows"/>

          <xsl:with-param name="GroupLevel" select="0"/>

        </xsl:apply-templates>

      </tr>

    </xsl:if>

    <xsl:for-each select="$AllRows">

      <xsl:variable name="thisNode" select="."/>

      <xsl:for-each select="//Row">

        <tr>

          <td colspan="2">

 

 

            <div class="TopTitle">

              <div  class="PostTitle">

                <strong>

                  <xsl:value-of select="@Title" disable-output-escaping="yes" />

                </strong>

              </div>

              <xsl:if test="../../@BaseViewID='7'">

                <!-- Handle _edit only their own_ property on list -->

                <xsl:if test="($thisNode/../@value.listpermission.EditListItems = '1' and (($thisNode/../@value.listpermission.ManageLists  = '1') or ($XmlDefinition/List/@WriteSecurity = '2' and $thisNode/@Author.id = $Userid) or ($XmlDefinition/List/@WriteSecurity != '2')))">

                  <div  class="ms-blogedit">

                    <a href="javascript:" onclick="javascript:STSNavigate('{$HttpVDir}/{$thisNode/../@resource.wss.lists_Folder}/{$thisNode/../@resource.wss.blogpost_Folder}/EditPost.aspx?ID={$thisNode/@ID}&amp;Source={$HttpVDir}%2Fdefault.aspx');">

                      <xsl:value-of select="$thisNode/../@resource.wss.blog_edit" />

                    </a>

                  </div>

                </xsl:if>

              </xsl:if>

            </div>

        

            <div class="PostSubtitle" >

              <div class="PostAuther" >

                By: <xsl:value-of select="@Author" disable-output-escaping="yes" />

              </div>

              <div class="PostPublishDate">

                Posted <xsl:value-of select="@PublishedDate" />

              </div>

            </div>

            <div class="PostTable">

              <div class="PostDateBox" >

                <div class="PostSmallDate">

                  <xsl:value-of select="ddwrt:FormatDateTime(string(@PublishedDate), 1033, 'MMM. d yyyy')" />

                </div>

              </div>

              <div class="PostBody" >

                <xsl:value-of select="@Body" disable-output-escaping="yes"/>

              </div>

              <div class="PostComments">

                <img src="_layouts/images/AdeccoPortal2010/icon_comment.png" alt="comment"/><xsl:value-of select="@NumComments" /> Comment(s)

              </div>

            </div>

 

            <hr />

         

       

          </td>

        </tr>

 

       

 

      </xsl:for-each>

 

    </xsl:for-each>

    <xsl:if test="$InlineEdit and not($IsDocLib) and $ListRight_AddListItems = '1'">

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

        <xsl:with-param name="Fields" select="$Fields"/>

      </xsl:call-template>

    </xsl:if>

  </xsl:template>

 

Now the blog post looks like the following

 

Not bad eh

Hope this helps you in your SharePoint 2010 implementation

{15/09/2010 12:17 PM} {0 comments}  {Tags: SharePoint}
SharePoint List Simplified Configuration Store

This is a sample configuration store that I wrote for a SharePoint implementation that I was working on. The configuration manager has a simple interface that takes two keys (siteID, and Key)  and returns the string associated with these keys here is the interface definition

 

public interface IConfigurationManager

    {

        string GetConfiguration(string siteID, string key);

    }

 

The implementation for the IConfiguration manager expects to find the list URL and the site URL where the list exists(the list can exist in any site) in the application settings of the web.config. The implementation caches the retrieved values which has its own draw backs as changes to the list are not reflected till the cash expires but for this implementation the requirement did not expect lots of changes.

/// <summary>

    ///  Reads the configuration information from the Configuration list

    ///  the URL for the list is stored in application settings in key

    ///   <add key="ConfigListURL" value="/Configuration/Lists/ConfigurationStore" />

    ////  <add key="configWebSiteURLKey"  value="http://localhost/Configuration"/>

    /// 

    /// </summary>

    public class ConfigurationManager: IConfigurationManager

    {

        private const string configListNameKey = "ConfigListURL";

        private const string configWebSiteURLKey = "configWebSiteURLKey";

       

        public ConfigurationManager()

        {

        }

        public string GetConfiguration(string siteID, string key)

        {

            string entry = null;

            bool dirty = false;

            Dictionary<string, Dictionary<string, string>> globalMap = GetMap();

            Dictionary<string, string> siteMap = null;

            if(globalMap.ContainsKey(siteID))

            {

                siteMap = globalMap[siteID];

                if(siteMap.ContainsKey(key))

                {

                entry = siteMap[key];

                }

                if(null == entry)

                {

                    dirty = true;

                    entry = GetConfigEnrtyFromSharePoint(siteID, key);

                    if (entry != null)

                    {

                        siteMap[key] = entry;

                    }

                }

            }

            else

            {

                dirty = true;

                entry = GetConfigEnrtyFromSharePoint(siteID, key);

                siteMap = new Dictionary<string, string>();

                if (entry != null)

                {

                    siteMap[key] = entry;

                }

                globalMap[siteID] = siteMap;

            }

            // update map if need be

            if (dirty)

            {

                HttpContext.Current.Cache[globalMapCacheKey] = globalMap;

            }

            return entry;

        }

        private string GetValue(SPListItem item)

        {

            string value = string.Empty;

            try

            {

                value = item["Value"].ToString();

            

            }

            catch

            {

                Debug.WriteLine("NoValue");

            }

            return value;

        }

 

        const string queryformatstr = "<Where> <And><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq><Eq><FieldRef Name='SiteID'/><Value Type='Text'>{1}</Value></Eq> </And></Where>";

        private string GetConfigEnrtyFromSharePoint(string siteID, string key)

        {

            string result = null;

            string SiteUrl = WebConfigurationManager.AppSettings[configWebSiteURLKey];

            SPSecurity.RunWithElevatedPrivileges(delegate()

            {

                using (SPSite siteCollection = new SPSite(SiteUrl))

                {

 

                    using (SPWeb rootweb = siteCollection.OpenWeb())

                    {

 

                        string configlistUrl = WebConfigurationManager.AppSettings[configListNameKey];

                        SPList list = null;

                        try

                        {

                            list = rootweb.GetList(configlistUrl);

                            SPQuery oQuery = new SPQuery();

                            oQuery.Query = string.Format(queryformatstr, key, siteID);

                            SPListItemCollection collListItems = list.GetItems(oQuery);

                            if ((null != collListItems) && (collListItems.Count >= 1))

                            {

                                result = GetValue(collListItems[0]);

                            }

                        }

                        catch (Exception ex)

                        {

                            Debug.WriteLine(ex.ToString());

                        }

                    }

                }

            }

            );

            return result;

        }

        const string globalMapCacheKey = "globalConfigurationMapCacheKey";

 

        private Dictionary<string, Dictionary<string, string>> GetMap()

        {

            Dictionary<string, Dictionary<string, string>> map = HttpContext.Current.Cache[globalMapCacheKey] as Dictionary<string, Dictionary<string, string>>;

            if (null == map)

            {

                map = new Dictionary<string, Dictionary<string, string>>();

                HttpContext.Current.Cache[globalMapCacheKey] = map;

            }

            return map;

        }

    }

}

 

The Provider just loads the implementation based on the class name and assembly name of an entry in the application settings in web.config.

// <summary>

    ///  

    /// Class, Assembly

    ///     <add key="configManagerProvider" value="ConfigurationManager, GlobalConfiguration, Version=1.0.0.0, Culture=neutral, PublicKeyToken=22d2dcb173b01686"/>

    /// </summary>

    public class ConfigurationManagerProvider

    {

        private const string configManagerProviderKey = "configManagerProvider";

        static public  IConfigurationManager GetConfigurationManager()

        {

            string str = WebConfigurationManager.AppSettings[configManagerProviderKey];

            int isep = str.IndexOf(',');

            string assemblyName = str.Substring(isep+1);

            string typeName = str.Substring(0,isep);

            Assembly asm = Assembly.Load(assemblyName);

            IConfigurationManager mngr = asm.CreateInstance(typeName) as IConfigurationManager;

            return mngr;

        }

    }

 

The consumer would write code similar to

      IConfigurationManager cm = ConfigurationManagerProvider.GetConfigurationManager();

      lblSiteTitle.Text = cm.GetConfiguration("Site1", "Key1");

 

{26/08/2010 1:47 PM} {0 comments}  {Tags: SharePoint}
Vaughan Online my Latest SharePoint Project

I was working on a project to migrate a SharePoint 2003 implementation to a new 2007 implementation. This new portal involved restructuring, reorganizing and actually a complete a new architecture and UI design. You can see the sample landing page above Very impressive do not you think so? I used Ajax, with SharePoint to develop many of the web parts, I will write later more updates about the lessons learned from this Project, specially the Migration process.
{30/11/2009 8:30 AM} {0 comments}  {Tags: SharePoint, Web Developmenet}

Copyright © Moustafa Refaat 2016. All Rights Reserved.