Using jQuery with custom Web services in SharePoint

I had an requirement of using  jQuery for fetching data from my custom web service. The approach was adopted to have better UI experience,

So the user doesn’t feel the post back and flickering of screens. 

 

I faced lot of issues to make it work, with all the note points found by goggling J made it work like charm.

 

 

The approach as follows

 

Step 1. Create a web service

Step 2. Client Side JavaScript definition to consume the web service

 

Step 1: Create web service

 

We will create a custom web service with a web method HelloWorld that takes a name as parameter and returns back a string in JSON format.

 

JSONJava Script Object Notation more info

 

It’s the same as C# objects. Object.Property to access the value.

 

Create a new web service project in ASP.NET and the web service definition as follows

 

namespace WebService1

{

    using System.ComponentModel;

    using System.Web.Services;

    using System.Web.Script.Services;

    using System.Web.Script.Serialization;

    /// <summary>

    /// Summary description for Service1

    /// </summary>

    [WebService(Namespace = "http://tempuri.org/")]

    [ScriptService]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [ToolboxItem(false)]

    public class Service1 : System.Web.Services.WebService

    {

        /// <summary>

        /// Hello world

        /// </summary>

        /// <param name="name">Name</param>

        /// <returns>Hello name</returns>

        [WebMethod]

        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        public string HelloWorld(string name)

        {

            responseObject = new

                {

                    MyName = "Hello " + name

                };

            return new JavaScriptSerializer().Serialize(responseObject);

        }

    }

}

 

Note:

ü  [ScriptService] to be added to allow calls from java script

 

ü  [ScriptMethod(ResponseFormat = ResponseFormat.Json)] over the method definition to return JSON

 

SharePoint context

Deploy the web service to the 12 hive folder to be accessible for any user regardless of the permission rights.

The following handler has to be added to the web.config in the layouts folder to avoid the 500 internal server error that will occur when you call the service from jQuery.

<httphandlers>

    <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,

System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

</httphandlers>

 

Step 2: Client Side JavaScript definition

 

jQuery AJAX calls are very simple to use compared to the native AJAX calls.  The call is made in jQuery by calling the function with required parameters.

 

var Name="Balaji";

var servicePath = "/_layouts/1033/myservice/Service1.asmx";

//the current site url + service url

var serviceURL = location.href.substring(0, location.href.lastIndexOf(‘/’)) + servicePath;

 

$.ajax({

        type: "POST",

        contentType: "application/json; charset=utf-8",

        url: serviceURL + "/HelloWorld",

        data: ‘{"name":"’ + Name + ‘"}’,

        dataType: "json",

        success: processResult,

        error: failure,

        crossDomain: true

    });

 

//Handle result

function processResult(xData) {

    var responseObject = jQuery.parseJSON(xData.d);

    alert(responseObject.MyName);

}

 

//Handle Failure

function failure(){

         alert("Error occurred");

}

 

 

Note:

ü  contentType and dataType to be defined as JSON

ü  crossDomain is set to true when you make cross domain queries like your app runs in a different domain and the service runs in another domain.

 

ü  The parameter passed to the webservice is case sensitive and the format should be JSON.

The parameter "name" in the web method HelloWorld is the same in the jQuery call "data" attribute.

data: ‘{"name":"’ + Name + ‘"}’

 

Hope this kick starts.



This message is for the designated recipient only and may contain privileged, proprietary, or otherwise private information. If you have received it in error, please notify the sender immediately and delete the original. Any other use of the email by you is prohibited.

CAML Basics

CAML (Collaborative Application Markup Language)

The CAML queries are internally used to query the SharePoint List with specific conditions and formatting. It is very powerful as SQL queries and improves the performance. The CAML query can be split into

  • Display Part
  • Conditional Part

Display Part

They are generally used to display the content in a grouped and ordered manner.

Eg: OrderBy, GroupBy

<Query>
  <OrderBy>
    <FieldRef Name=’Name’/>
  </OrderBy>
  <GroupBy>
    <FieldRef Name=’Location’/>
  </GroupBy>
</Query>

Conditional Format

They are used to retrieve data with certain conditions. Like using logical operators. The following example queries will give an overview.

1.Simple Condition

The condition (Name ==”Balaji”) in CAML form would look like

<Where>
  <Eq>
    <FieldRef Name=’Name’/>
    <Value Type=’Text’>Balaji</Value>
  </Eq>
</Where>

2.Multiple Condition

Multiple condition with Logical operators have a tricky part that each logical operator can have two parts more than two should have another logical operator to be defined encapsulating it.

The condition((Name ==”Balaji”) && (Location==”Chennai”) && (ID==1))in CAML form would look like

<Where>
  <And>
    <And>
      <Eq>
        <FieldRef Name=’Name’/>
        <Value Type=’Text’>Balaji</Value>
      </Eq>
      <Eq>
        <FieldRef Name=’Location’/>
        <Value Type=’Text’>Chennai</Value>
      </Eq>
    </And>
    <Eq>
      <FieldRef Name=’ID’/>
      <Value Type=’Number’>1</Value>
    </Eq>
  </And>
</Where>

Normal Operator SharePoint  specific
= Eq
> Gt
< Lt
>= Geq
<= Leq
Like Contains
Null Check IsNull
Not Null NotNull
Begins BeginsWith
Date Range DateRangesOverlap
&& And
|| Or

Generally CAML queries can be easily generated using several tools. Refer the following link for more info http://msdn.microsoft.com/en-us/library/ff648040.aspx

SP Value types http://msdn.microsoft.com/en-us/library/aa558695(BTS.20).aspx

MEF with Silverlight 4

MEF – Managed Extensibility Framework. While building applications for SharePoint using Silverlight came across a scenario of dynamic loading of XAP and loading an application. The main reason moving towards this approach is scalability and to reduce the load time delay in loading the XAP files. This approach serves the request by dynamic loading of the content. I will come up with a simple application demonstrating MEF. Now I will post the quick ref links of MEF.

10 Reasons to use MEF

Blogs

Part 1 , Part 2 , Part 3 , Part 4 , Part 5

Videos

Channel 9 Video series

Demo

Cloud Light Application submitted for Mix code challenge just 10Kb of size(More..)

Don’t Lie to your boss if you are in Social Networking !!!!!!

I love sharing my status to people and updates. I use to tweet more and I got this as an email warning from one of my friend and immediately I changed my accounts to be private and locked to public view and started a personal twitter account.(Confidential don’t tell anyone)

clip_image002

Dynamically show image in Silverlight

I had a requirement to show images in Silverlight dynamically and that was quite simple can be done in two steps in a minute but I spend nearly hours to figure out the issue.

Dynamically show images from code behind

var bitmapImage = new BitmapImage(new Uri(“http://www.google.co.in/intl/en_com/images/logo_plain.png”);
image1.Source = bitmapImage;

The above code will make you smile only if you run the application from the silverlight web application project and not the default genarated testpage.html

The whole point is that this scenario works only if the application is hosted or run from an local web application with fileserver.

Note: Only JPG,PNG,BMP works this way and GIF doesn’t go well. Check this post to make GIF work

http://www.eggheadcafe.com/tutorials/aspnet/c0046ba1-5df5-486a-8145-6b76a40ea43d/silverlight-handling-cro.aspx

SharePoint DB an Overview

The SharePoint heart is SQL it acts as the brain behind the scenes. SharePoint installed on a server edition OS uses the Internal Database by default. You can manually configure SharePoint to pick the SQL server on Configuration. To check the instances running on the machine you can use the SQL Configuration manager.

 image

The above picture shows two instances Internal Database and SQL Express.

Use SQL management studio for easier access. Use the instance to connect to appropriate instance and expand the databases to view the db attached to the particular instance

smgt

The default configured would have three db’s by default

 
_AdminContent  (Central Admin)

    The central administration db will be generally one per farm.

 
Wss_Content (Site Content)

    The content database is created one by default that can hold 15000 sites
This can be created separately for each application created in the farm to have control over the growth of the db.

Find the content db in your farm

Central Admin >>Application management >> Content Databases

 
Wss_Search (Search Index)

This is only applicable if only search index is enabled for the farm.

Note: The default database created will have the following settings auto growth (db would grow as the data increases) and no size limit for the db file. This applies for both the .MDF(SQL Database) and .LDF(SQL Log)

The procedure that can avoid the situations. The following are my personal view and take necessary backup before you proceed.

Pre – Action
  1. Connect to instance with Management studio
  2. Right-Click the db properties

image

3.Select the Files and you can see two files the db and the log

4.Click the button in the Autogrowth button and you will find the following window.

image5. Set the Restricted file growth as plan and that size should be greater than the existing file.

 

Post – Action

The Pre-action would help once a new server is setup. The main case is everyone miss this step and finally once log grows huge they search around for an solution. Check this might help. The below is my view and take precautions before giving a try.

  1. Stop SharePoint services and IIS
  2. Connect to the SQL Instance
  3. Expand the Databases item
  4. select the db right click >>Tasks >> Detach
  5. Rename the log file of the detached db
  6. Attach the db manually using the following query in SQKlMGmt
  7. sp_attach_single_file_db @dbname= ‘databasename’, @physname= ‘C:\Databases\databasefile.mdf’

7. Start SharePoint services and IIS that generates a new log file.

SharePoint web service a Beginner guide

The post gives a basic Idea about the web services inbuilt with the SharePoint which can be used in other types of desktop application and Silverlight application.

    The SOAP request has to be sent in the web request body to get the response from the web service.
    eg: SOAP call for getting the WebCollection.

"<?xml version=""1.0"" encoding=""utf-8""?> 
<soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope""
    <soap12:Body><GetWebCollection             xmlns=""http://schemas.microsoft.com/sharepoint/soap/"" /> 
     </soap12:Body> 
</soap12:Envelope>";

    The most commonly required url’s for interrogating with the SharePoint web. Replace the localhost with your SharePoint server url and hit the enter and you will see the SOAP request and reply format.

    • http://localhost/_vti_bin/Webs.asmx – sites and sub sites
    • http://localhost/_vti_bin/Lists.asmx – Lists
    • http://localhost/_vti_bin/Alerts.asmx – Alerts
    • http://localhost/_vti_bin/DspSts.asmx -Schemas and data
    • http://localhost/_vti_bin/DWS.asmx – Document Workspaces
    • http://localhost/_vti_bin/Forms.asmx –User interface forms
    • http://localhost/_vti_bin/Imaging.asmx – Picture libraries
    • http://localhost/_vti_bin/Meetings.asmx – Meeting Workspaces
    • http://localhost/_vti_bin/Permissions.asmx – SharePoint Services security
    • http://localhost/_vti_bin/SiteData.asmx – SharePoint Portal Server
    • http://localhost/_vti_bin/Sites.asmx – Site templates
    • http://localhost/_vti_bin/UserGroup.asmx – Users and groups
    • http://localhost/_vti_bin/versions.asmx – File versions
    • http://localhost/_vti_bin/Views.asmx -  views of lists
    • http://localhost/_vti_bin/WebPartPages.asmx - Web Parts

    Hope this gives a basic idea about web services and the further post will explain in making a web service call.. 

    Follow

    Get every new post delivered to your Inbox.