-->
Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, 13 August 2015

Issues of Console.Log with Internet Explorer


Recently, I ran into an issue with one of my client where my particular callback function of ajax call was not called at all. It worked absolutely fine with google chrome and it was only issue with the Internet Explorer.

I did lot of digging around the ajax calls using fiddler to see if there is problem in the ajax call or whether some JavaScript file is not loaded correctly but could not find it much on that front.

I could track the issue when we open the IE development toolbar and it used to work absolutely fine. Initially I could not produce it  on my machine as I frequently use the IE toolbar. After troubleshooting a bit i found out that console object is exposed only when the developer tools are opened for a particular tab. If I do not open the developer tools window for that tab, the console object remains exposed for each page you navigate to. If I open a new tab, I must also open the developer tools for that tab in order for the console object to be exposed.

This was some petty issue which took lot of time to identify for me. So for workaround on this I  developed a small utility file for logging into console which will work across all the browsers.
This utility will log console messages only when console object is active else it will skip logging.

 /*
 FileName  :  DPSUTILS.js
 Author   :  Dhaval Shah
 Description :  This Javascript library contains common methods to do the read/Write operation across  
         different data sources e.g. UserProfile, Managed Metadata Service and Search Service
 */
 (function() {
   if (!window["DPS"]) {
     window["DPS"] = {};
   }
   DPS.Namespace = {
     Register: function(namespace) {
       var parts,
         context,
         nsPath,
         partsLength;
       parts = namespace.split(".");
       partsLength = parts.length;
       context = window;
       nsPath = "";
       for (var i = 0, l = partsLength; i < l; ++i) {
         var name = parts[i];
         if (!context[name]) {
           context[name] = {};
           context[name].__namespace = name;
         }
         nsPath += name + ".";
         context = context[name];
         if (!context.__namespace) {
           context.__namespace = nsPath.substring(0, nsPath.length - 1);
         }
       }
       return context;
     }
   };
 })();
 /**
  * This namespace contains utility functions used across application.
  */
 (function() {
   DPS.Namespace.Register("DPS");
   DPS.Namespace.Register("DPS.UTILS");
      DPS.UTILS = {    
     /*
      * Logs the exception message in browser console
      * @param {string} message - Exception Message
      */
     logAjaxErrorMessage: function(xhr, status, error) {
         if (xhr.responseText != "") {
           var message = xhr.responseText;
           if (typeof console === "undefined") {
             return;
           }
           console.error(message);
         }
       },
       logMessage: function(message) {                
           if (typeof console === "undefined") {
             return;
           }
           console.log(message);        
       }
   };
 })();

Save this file as DPSUTILS.js and reference it in your code.

In order to log message you can directly use

DPS.UTILS.logMessage("My Log Message . . .");


I hope this was helpful..

Happy Coding !

Monday, 21 May 2012

Sharepoint 2010 Client Object Model - Part 2

In my previous post we discussed about the basic's of the Client Object Model in Sharepoint 2010 and it's architecture.


As we discussed COM can be implemented using 3 client API's viz
  1. .NET managed application (Console application/Windows Forms Application) 
  2. Silverlight 2.0 application
  3. ECMAScript (JavaScript, JScript)

This Article we will discuss it with the use of the .Net Managed Application


Create a console application with Microsoft .Net Framework 3.5 and use the following code snippet in the Main File
Note : You will be required to add reference to the Sharepoint Client Assemblies located under C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll

static void Main(string[] args)
        {
            var _ctx = new ClientContext("<sitecolleciton_url>");
            var _web = _ctx.Web;
            var _lists = _web.Lists;

            _ctx.Load(_lists, c => c.Include(l => l.Title, l => l.Description)
                  .Where(l => l.Hidden == false)
                );

            // Call to the Load method does not actually load anything.
            // Instead, it informs the client object model that when the
            // application calls the ExecuteQuery method, you want to load
            // the property values of the siteCollection object.
            _ctx.ExecuteQuery();

            foreach (var list in _lists)
            {
                Console.WriteLine(list.Title + " *** " + ((list.Description.Length > 0) ? list.Description.Substring(0, 25) + "..." : String.Empty));
            }
            Console.ReadLine();
        }



ClientContext : ClientContext object instantiates the context object for a specific site collection. It serves as the main entry point for accessing the client object model.
Load : This method is called to retrieve the properties of a specified client object, such as the ListCollection collection. The properties are stored in the client object. Request call to the sharepoint is not made yet during this call, it will just store the properties that has to be retreived.
ExecuteQuery : The call to the ExecuteQuery method causes the SharePoint Foundation 2010 managed client object model to send the request to the server. There is no network traffic until the application calls the ExecuteQuery method.

Note : To optimize data retrieval, the Client OM queue all requests to the SharePoint server till an invocation to the ExecuteQuery is made. So no data will be available from the server till the ExecuteQuery method is invoked. If you want to use a property that you are not asked to load in the ClientContext.Load method, you’ll get PropertyOrFieldNotInitializedException is thrown.

In our other example we will use the LoadQuery method

static void Main(string[] args)
        {
            var _ctx = new ClientContext(" <sitecolleciton_url> ");
            var _web = _ctx.Web;
            var _lists = _web.Lists;

             var _query = from list in _lists select list;
            // The LoadQuery method has different semantics than the Load method.
            // Whereas the Load method populates the client object 
            // (or client object collection) with data from the server, the LoadQuery                                                   
            // method populates and returns a new collection.
            // This means that you can query the same object collection multiple times
            // and keep separate result sets for each query.
            IEnumerable<List> myLists = _ctx.LoadQuery(_query);
            _ctx.ExecuteQuery();

            foreach (var list in myLists)
            {
                Console.WriteLine(list.Title + " ***** " + list.Description);
            } 
            Console.ReadLine();
        }


 LoadQuery : The LoadQuery method is similar in functionality to the Load method, except that LoadQuery method populates and returns a new collection while Load method populates the client object. This means that you can query the same object collection multiple times and keep separate result sets for each query. Additionally you can filter the returned result set.

Below example depicts how to create a list, In this case We have created the document library "My Docs"

static void Main(string[] args)
        {
            var _ctx = new ClientContext(" <sitecolleciton_url> ");
            var _web = _ctx.Web;
            var _lists = _web.Lists;

            //Create a document library
            ListCreationInformation listCreationInfo = new ListCreationInformation();
            listCreationInfo.Title = "My Docs";
            listCreationInfo.TemplateType = (int)ListTemplateType.DocumentLibrary;

            List oList = _web.Lists.Add(listCreationInfo);

            _ctx.ExecuteQuery();

        }


Same way we can update the properties of the lists, See the code-snippet below

static void Main(string[] args)
        {
            var _ctx = new ClientContext(" <sitecolleciton_url> ");
            var _web = _ctx.Web;
            var _lists = _web.Lists;

            //Update the list information
            List oList = _web.Lists.GetByTitle("My Docs");

            oList.Description = "My Document reporsitory";

            oList.Update();

            _ctx.ExecuteQuery();

        }



In our subsequent articles we will describe how to implement each of the COM using different client.

I Hope this article was informative. Happy Sharepointing !

Please do Share/Like/Comment if this article was helpful.

Tuesday, 8 May 2012

Sharepoint 2010 Client Object Model - Part 1

Last week one of my colleague took a session for all of us to explain the Client Object Model in Sharepoint 2010, so i thought to share the knowledge via this blog article.


What is Client Object Model (COM)
Client Object Model (Client OM) is a unified model which can be used by developers to access the server. The Client OM can be accessed via web services, via a client (JavaScript) API, and via REST. Microsoft SharePoint 2010 introduces three new client APIs that allow you to interact with SharePoint sites from script that executes in the browser, from code that executes in a .NET managed application, or from code that executes in a Microsoft Silverlight 2.0 application.


Key Points one should know about the COM:
  1. There are limitations to what can be done client side compared to server side, say for example you cannot access the FARM level properties, you can get/set only the properties at the web application level.
  2. we cannot elevate the privilege in COM as we can do in server object model.
  3. No SharePoint installation is required in the development machine.Only  the Client DLL's are required.
  4. No Compilation required as required on the server side, NO IISRESET required.
  5. Path to get DLL's: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI


The following table shows the equivalent objects that the new APIs provide for common SharePoint Foundation 2010 server objects.

Server Object Model .Net Managed & Silverlight JavaScript
SPContext ClientContext SP.ClientContext
SPSite Site SP.Site
SPWeb Web SP.Web
SPSite.Title Site.Title SP.Site.get_title() & SP.Site.set_title()

Client Object Model Mechanics
Below mentioned diagram explains the architecture of the Client Object Model in Sharepoint 2010
Image Reference is here
  • Client Object Model is a façade on top of WCF service.
  • Requests for the resources are batched using Load & LoadQuery methods.
  • Requests are executed using ExecuteQuery or ExecuteQueryAsync methods.
    • XML document with batched request information is sent to server.
    • JSON response with requested resources is sent back to the client.
In our subsequent articles we will describe how to implement each of the COM using different client.

I Hope this article was informative. Happy Sharepointing !


Please do Share/Like/Comment if this article was helpful.