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.. 

    Top Twitter Apps

    Twitter is the most spoken word of the year 2009. I started tweeting only mid of this year but I love tweeting it shares the information both personal and the technical. The friends who follow you will be up to date.I don’t have to call and check what are you up to ?

    This really helps people stay in touch.

    The apps that I found to be the best ones.

    Windows

    Witty – http://code.google.com/p/wittytwitter/

    Seesmic – http://seesmic.com/ (Updated 20/6)

    Desktop Gadget (Vista / Win 7)

    Tweetz – http://blueonionsoftware.com/gadgets.aspx

    Google Desktop

    http://www.twittergadget.com/

    iPhone / iPod Touch /MAC

    http://twitterrific.com/

    http://itunes.apple.com/app/twitter/id333903271?mt=8 (Updated 20/6)

    BlackBerry

    http://www.ubertwitter.com/

    Nokia

    http://www.nokiasymbianthemes.com/free-mobile-applications/all-mobile-twitter-apps-for-nokia

    Java Based

    Snaptu – http://www.snaptu.com/  (Updated 20/6)

    Fring – http://www.fring.com/  (Updated 20/6)

    Hope this helps the newbie.

    If you find something interesting and I have missed it feel free to comment on it.

    Chrome OS Review

    Today I got a chance to preview Chrome OS and I would like to share the experience.

    Downloaded the chrome VM and loaded it on my PC.

    It didn’t login at first and finally found the trick to use the login name chromium to login.

    • Google Chrome OS focuses on three things Speed, Simplicity, Security
    • All data on Chrome OS is in the cloud
    • Chrome OS looks like Chrome browser
    • User data on machine is always encrypted and always synced to the cloud – local data is just a cache
    • Cold reboot demo – to logon screen in 7 sec, full OS in another 3 sec
    • It can be used on Netbooks.
    • Chrome OS is open source and you can download it from here

    VM download – http://gdgt.com/google/chrome-os/download/

    Direct VM – http://tiny.cc/4iOOw

    Install and develop SharePoint applications on Window 7 – 64 Bit

    I used to develop web parts in windows 2008 server and it was pretty sluggish and felt bad to use a server OS as a desktop machine. So I thought could try installing SharePoint over windows 7. I came across issues on first install and gave up and went back to windows 2008. Once I was bored and was keen to find out a way to install SP on windows 7  and finally succeeded.

    Install Procedures

    Install Visual studio 2008 with SQL express edition( this will be used as a DB server)

    I would Thank Bamboo solution for the post http://tinyurl.com/wssonwin7

    Do the following steps mentioned in the above post link and while configuring in the below stage

    config_5F00_2[1]

    use .\SQLEXPRESS this is your internal Express edition instance and your system login credentials.

    finally use the create application to create a base site. Some time you may face an issue the create application may be hidden in the central administration.

    Run Internet Explorer as Administrator to resolve :P

    Development

    I have been using Visual Studio Extensions – VSS 1.2 for a long time with no issues but tried installing VSS 1.3 and it turned out odd and didn’t work pretty well on the first try but finally succeeded. VSS1.3 looks cool has lot new features ease of deployment and debugging.

    VSS 1.3

    If you face any issues in using VSS1.3 first check the web service running in the IIS namely VSSEWSS try to open the address in browser and it should open up with a default page or try you need to register WCF with IIS and update its scriptmaps. to do this,

    1. Navigate to %SystemRoot%\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\
    2. Execute ServiceModelReg.exe -i

    more info on this tool can be found here:

    http://msdn.microsoft.com/en-us/library/ms732012.aspx

    VSS 1.2

    If you plan to go with VSS 1.2 over 64 Bit use this tool ORCA MSI Editor to remove 32 Bit check

    1. Run VSeWSSv12.exe

    2. Copy C:\Program Files (x86)\MSECache\vsewssv12.en-us to a temp folder

    3. Open Orca (from the platform SDK) and load VSeWSSv12.msi

    3. Remove the following lines

    • InstallExecuteSequence>X64System
    • InstallUISequence>X64System
    • InstallExecuteSequence>WSSNotInstalled
    • InstallUISequence>WSSNotInstalled

    4. Run edited MSI

    Download Links

    WSS 3.0 32 Bit http://tinyurl.com/wss3sp2x86

    WSS 3.0 64 Bit http://tinyurl.com/wss3sp2x64

    VSS 1.2 32 Bit http://tinyurl.com/vss12

    VSS 1.3 32 Bit http://tinyurl.com/vse13-x86

    VSS 1.3 64 Bit http://tinyurl.com/vse13-x64

    ORCA http://www.technipages.com/wp-content/uploads/2007/11/orca.Msi

    Feel free to comment if you face any issues that may help others.

    Follow

    Get every new post delivered to your Inbox.