Pages

Friday, May 30, 2014

Get SPList items (by CAML query) using JavaScript in SharePoint Apps

Introduction

Today I will show how to get SPList Items by filtering using CAML query. Also this post includes how to get the data from a custom field.

Solution Background

I use JQuery.Deferred and Promise in order to achieve the success and failure of the asynchronous call. There are plenty of articles on the internet regarding JQuery.Deferred. Please see the Reference section for more on this.

Solution

  1.   function query() {
  2.  
  3.             var camlQuery =
  4.                 "<Where>" +
  5.                 "<Neq>" +
  6.                 "<FieldRef Name='CustomFieldOne' />" +
  7.                 "<Value Type='Text'>Suhail Jamaldeen</Value>" +
  8.                 "</Neq>" +
  9.                 "</Where>";
  10.  
  11.             //Calling the method getListItemsByCAMLAsync.
  12.             //Here the fail and done methods are from the deffered object which is returning.
  13.             getListItemsByCAMLAsync('NameOfList', camlQuery, 'Include(DisplayName, Id, CustomFieldOne)')
  14.                     .fail(function (e) {
  15.                         alert((handeler.parseSPException(e)));
  16.                     }).done(function (items) {
  17.                         var enu = items.getEnumerator();
  18.                         while (enu.moveNext()) {
  19.                             var cu = enu.get_current();
  20.                             var id = cu.get_id();//Read the Id
  21.                             alert(id);
  22.                             var prope = cu.get_fieldValues();//You can see the fields which you are retreiving
  23.                             var initiator = cu.get_fieldValues().CustomFieldOne;//Readvalue from custom property (Single line)
  24.                             alert(initiator);
  25.                         }
  26.                     });
  27.  
  28.         };
  29.  
  30.         //This returns a deferred object.
  31.         function getListItemsByCAMLAsync(listName, query, fieldsFilter) {
  32.             var def = $.Deferred();
  33.             var clientContext = new SP.ClientContext();
  34.             var oWeb = clientContext.get_web();
  35.             var ol = oWeb.get_lists().getByTitle(listName);
  36.             var qry = new SP.CamlQuery();
  37.             qry.set_viewXml(query);
  38.             var items = ol.getItems(qry);
  39.  
  40.             clientContext.load(items, fieldsFilter);
  41.             clientContext.executeQueryAsync(function () {
  42.                 def.resolve(items);
  43.             },
  44.                 function (a, b) {
  45.                     def.reject(b);
  46.                 });
  47.             return def.promise();
  48.         };

Reference

http://sharepoint.stackexchange.com/questions/69878/how-to-use-client-object-model-javascript-to-get-a-custom-user-profile-propert

http://api.jquery.com/category/deferred-object/

http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html

Conclusion

Should say Melick (http://melick-rajee.blogspot.com) for the guide on SharePoint Apps.

Wednesday, May 21, 2014

Get SharePoint list properties using JavaScript Object Model

Introduction

I was developing a SharePoint App using SharePoint JavaScript Object Model which also called SharePoint ECMAScript Client Object Model. Today I will show how to retrieve basic properties from SharePoint list.

Solution

  1. function getSPListProperties() {
  2.  
  3.           //Get the current context. Same as SPContext in server side
  4.           var ctx = SP.ClientContext.get_current();
  5.  
  6.           //Get the web
  7.           var web = ctx.get_web();
  8.  
  9.           //Get the list by its title
  10.           var list = web.get_lists().getByTitle('Title of the List Instance');
  11.  
  12.           //Load the properties which we need
  13.           ctx.load(list, 'Title', 'Id', 'Created', 'ItemCount');
  14.  
  15.           //Excecute the loded queries asyncronisly
  16.           ctx.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
  17.  
  18.           //Success method
  19.           function onQuerySucceeded() {
  20.               alert(list.get_title());
  21.               alert(list.get_id());
  22.               alert(list.get_created());
  23.               alert(list.get_itemCount());
  24.           }
  25.  
  26.           //Falied method
  27.           function onQueryFailed() {
  28.               alert('failed');
  29.           }
  30.       }

 

Conclusion

Please note that when you get the list through the method web.get_lists().getByTitle('Title of the List Instance'); It doesn’t load all the properties like in server side. We have to explicitly load the properties which we need.
When you didn’t load for a property, and try to call the method in order to get the data it will throw an exception.
Capture
Reference:
http://msdn.microsoft.com/en-us/library/office/jj245759(v=office.15).aspx#constructors

Saturday, April 19, 2014

How to prevent from declaring global variables in JavaScript?

Introduction

When we declare a variable in JavaScript; if its declared with the var keyword it will be a local variable and if we omit the var key work it will be implicitly declared as the global variable. Developers are always careful on creating global variables.

Problem Background

Developers may accidentally declare global variable without their knowledge.

Solution

  1.  
  2. function funcationName() {
  3.      "use strict";
  4. };


To avoid developers from creating global variable you can use strict mode as given below. .

 
Conclusion

If we use strict method; when we debug we will get an exception on the line where we have declared global variables. See the screenshot below.

Wednesday, April 16, 2014

The property 'opacity' is not compatible with Internet Explorer 8.0

Introduction

I had to set opacity value for a text using cascading style (CSS). But when I type opacity it showed “The property 'opacity' is not compatible with Internet Explorer 8.0” in Visual Studio. See the screen shot below. 



Solution

To set the opacity value you have to set both opacity and a filter value; so that it will work for all browsers. 

   
p {
    opacity: 0.8;//0.0 is fully transparent and 1.0 is fully opaque 
    filter: alpha(opacity=80);//Here 0 is transparent and 100 is fully opaque 
}
 

Conclusion

Reference: 
Programming with HTML5 with JavaScript and CSS3 – A Microsoft Learning Product
 

Wednesday, April 9, 2014

Redirect to an external website from SharePoint App

Introduction

I’m assigned to a project where I’m to develop SharePoint hosted app using JSOM.

Problem Background

There I wanted to redirect to external web page. Eg.http://google.com. I used 

  • location.href='http://google.com'; 
  • window.location.replace("http://google.com");
  • document.location.href = url;
which we use normally to redirect to another website. But they didn’t work for me. This is because there was a post back on my page and I still want it.

Solution


I set a Timeout and it worked for me; use the below code to redirect.


   
  setTimeout(function () { document.location.href = url }, 20);

Conclusion


Hope this will help you. :) 
 

Friday, March 28, 2014

How to get the correct audit occurred time from SPAuditEntry

Introduction

I was assigned to a project where I had to retrieve audit data programmatically using C#. I used SPAuditQuery and SPAuditEntry in order to achieve this.

Problem Background

When I retrieve the audit occurred time by spAuditEntry.Occurred; it gives a different value from the actual time.

Solution Background

SharePoint save the audit data in content database in table dbo.AuditData. To see auditing data; open your content database and go to the table dbo.AuditData and see the column “Occurred” there you can see the UTC Date time of the actual audit time. 





I learnt from various blog posts that SharePoint usually store datetime in UTC DateTime format in the content database; and when it want to display the date time in SharePoint site the value stored in database is converted to webapplication’s time and then displays the time according to the time zone the person is in.

Solution

To get the web application time you have to call RegionalSettings.TimeZone.UTCToLocalTime() method.


   
spWeb.RegionalSettings.TimeZone.UTCToLocalTime(spAuditEntry.Occurred)
//spAuditEntry.Occurred is the time stored in content database which is a in DateTime format

Conclusion

So when you retrieve any data from content database programatically  which contains datetime;  please use the above method as you need. I have already blogged on a same kind of issue here. This was to retrieve the LastItemModifiedDate as Local Time.

Wednesday, March 12, 2014

Set application page heading dynamically in SharePoint

Introduction

I was had to set the heading of the application page dynamically from the code behind (server side).


Solution

Your application page will look something like this.

 Applicationpage

What you can do is simply replace "My Application Page" with a label and you can replace the text from the back end.

  1. <%-- This is Heading of the page --%>
  2. <asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
  3. <asp:Label runat="server" ID="labelPageTitle"></asp:Label>
  4. </asp:Content>

Now from the code behind you can access the label by its id and set the text as you need.

  1. labelPageTitle.Text = "From code behind";


Conclusion

Your page will look something like this.

apppage