Creating WCF service in SharePoint 2010

Whether you already tried creating WCF service as a standalone website project or WCF library – creating SharePoint hosted WCF add whole new meaning to it 🙂

Suppose you want to create a service which you can call using URL and receive and XML or JSON back in your browser or JavaScript app.

I’ll demonstrate the process step by step:

In our case we’ll call

and receive

}
}

1. Create new Visual Studio 2010 Blank SharePoint project.

2. Map a new SharePoint folder in your solution – it’ll be ISAPI folder. That’s where our Service definition is going to sit.

3. Add a new Text file in the newly mapped ISAPI folder. Rename the text file to SVC extension and add the following code to it:

}
}
}
}
}
}

Ensure you replace highlighted parts with valid assembly information and namespaces.

4. Add the following references to your project:

Microsoft.SharePoint.Client.DLL – (C:\Windows\assembly\GAC_MSIL\Microsoft.SharePoint.Client.\ 14.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.dll)

System.ServiceModel.DLL

System.ServiceModel.Web.DLL

5. Add a new folder to your solution called WCF Service (or anything else). This is where we`re going to our service classes and contract.

6. Add new class called IService1.cs – which is the service contract. Replace it`s code with the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace WCFOnSP
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(UriTemplate = "/MyCall?message={message}",
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Xml)]
        string GetData(string message);
        // TO Call this method - deploy the solution and call the following URL:
        //  Text
    }
}

Pretty self explanatory – I event included a comment on what`s the call syntax. WebMessageFormat.Xml will determine if the return is XML or JSON – so this is how you toggle it.

7. Now let`s implement the REST call method. Create new class in the same folder as your contract – name the file: Service1.cs, replace it`s content with the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel. using Microsoft.SharePoint.Client.Services;
namespace WCFOnSP
{

    [BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class Service1 : IService1
    {
        public string GetData(string message)
        {
            return string.Format("You entered: {0}, Entered on: {1}", message,  DateTime.Now.ToString());
        }
    }
}

Also, pretty self explanatory – this method can really execute anything as long as it returns a string value. Attributes on a top of the class will ensure the service has necessary resources to run within the environment – which you normally get by default in SP 2010.

That`s all there is to it – deploy your solution and use the calling URL from above – you should get your desired message in XML. Now you can consume the XML or JSON your application.

Good Luck!

Getting started with WCF services on SharePoint 2010

As you may know, SharePoint 2010 can host WCF services in it’s environment. There are number of benefits to using WCF over ol way of using SOAP. This is going to be one of at least 2 articles I’m planning to talk about WCF an SharePoint.

In this part I will talk about how you can use Listcheap valium.svc out of the box web service in your sample application. In next post I will cover how to create you custom WCF service an consume it through browser calls in XML or JSON.

Listcheap valium.svc is an out-of-the-box service allowing you to list any lists available on the current web an access items within those lists using web service calls.

Navigate to (C:\Program Files\Common Files\Microsoft Share\Web Server Extensions\14\ISAPI) where you will fin: Listcheap valium.svc. From the buy soma online no prescription you can access this service by using relative URL: ~/_vti_bin/Listcheap valium..svc.

This means if you have a site collection http://localhost – you woul call cheap valium.svc”>http://localhost/_vti_bin/Listcheap valium.svc; try an make the call. If you see XML back – that’s a goo sign. If you got an error

</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>

this means you first nee to apply the following service pack: cheap valium.svc issue service pack” href=”http://support.microsoft.com/kb/976127″ target=”_blank”>http://support.microsoft.com/kb/976127.

Try calling a web service an see if you get results back.

Now let’s try to call out list ata service using JavaScript. Create a new HTM file an paste the following coe in it.

<html>
<hea>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
                $('#resultarea').appen($(html));
       </hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>
</hea> <boy>    <iv i="resultarea">    </iv> </boy> </html>

This coe assumes you have a list calle Calenar on your root site of your site collection. Make sure you create one an a few items into the list. The coe will iterate through the list an isplay titles of all calenar events you have in the list.

This conclues our short emonstration of out-of-the-box WCF services an calling them in JS.

Check back tomorrow to see how you can create your own SharePoint hoste REST services.

Goo Luck!

Have SharePoint public site – here is how to make it mobile friendly

SharePoint, especially 2010 release, is becoming more popular as a public site platform – and with an increased number of mobile devices – mobile site experience is expected.

Both SharePoint and SharePoint 2010 have mobile support. When user with a mobile device accesses the site – the site redirects users to a mobile version of the site. In this article we will cover how to make sure that you redirect all of the latest devices to a mobile site as well as how the actual redirect happens.

If you Navigate to the root of your SharePoint site in IIS (Ex. C:\Inetpub\wwwroot\wss\VirtualDirectories\80) you will locate App_Browsers – the folder that contains browser definitions. In order to ensure you have support for all of the latest browsers – you can download the latest browser definition file (mobile.browser) from codeplex – (credit goes to Mark Bice for this one) .

Now copy the mobile.browser file you downloaded to Devices folder in App_Browsers which you will have to create.

If you worked with ASP.Net before you probably know that HttpContext has a property that will determine whether your browser is a mobile browser – HttpContext.Request.Browser.IsMobileDevice . This will ordinarily return false unless you have an up to date mobile.browser file – so keep your browser definitions current.

What happens next is really up to you. You can create a user control in the masterpage of your SharePoint site; the user control will have a code behind that will determine whether the current browser is a mobile device browser and redirect users to more simplified version of a site.

Here is how my user control code behind could look like:

string pageName = req.Url..[req.Url..Length - 1];
string pageName = req.Url..[req.Url..Length - 1];
string pageName = req.Url..[req.Url..Length - 1];
string pageName = req.Url..[req.Url..Length - 1];
string pageName = req.Url..[req.Url..Length - 1];
string pageName = req.Url..[req.Url..Length - 1];
string pageName = req.Url..[req.Url..Length - 1];
string pageName = req.Url..[req.Url..Length - 1];

Good Luck!

Automated SharePoint 2010 install/upgrade using PowerShell

When you develop with SharePoint you often have to set up development, build, qa environments, but wait – there is also production etc. All that takes time and SharePoint 2010 really stepped up in how you can quickly automate building of your environment.

You can start with abase machine installation: Windows, SQL etc. When you’re happy with configuration and and VM is all good to go – you can use the following steps to set up your SharePoint.

1. Copy SharePoint 2010 installation files to any directory accessible from your computer
(in my case: \Desktop\Sp2010Install)
2. Open the following file in the copied installation file structure:
Desktop\Sp2010Install\Files\SetupSilent\config.xml.
4. The contents will look like this:

<Configuration>
<Package Id=”sts”>
<Setting Id=”LAUNCHEDFROMSETUPSTS” Value=”Yes”/>
</Package>

<Package Id=”spswfe”>
<Setting Id=”SETUPCALLED” Value=”1″/>
</Package>

<Logging Type=”verbose” Path=”%temp%” Template=”SharePoint Server Setup(*).log”/>
<PIDKEY Value=”Enter product key” />
<Display Level=”none” CompletionNotice=”no” />
<Setting Id=”SERVERROLE” Value=”SINGLESERVER”/>
<Setting Id=”USINGUIINSTALLMODE” Value=”0″/>
<Setting Id=”SETUP_REBOOT” Value=”Never” />
<Setting Id=”SETUPTYPE” Value=”CLEAN_INSTALL”/>
</Configuration>
Here we have the value of the product key.

Also, we changed the value of SETUPTYPE to CLEAN_INSTALL to perform a clean install. If this is an upgrade – use V2V_INPLACE_UPGRADE
For more options available – check out config.xml reference (SharePoint Foundation 2010) at TechNet:

5. Now create new file in the parent directory of your SP 2010 installation files folder called simplefarm.ps1
Replace the contents of the file with contents of the file as described on Technet (Quick start: Deploy single server in an isolated Hyper-V environment (SharePoint Server 2010)):

6. Replace the settings section values on the top of the simplefarm.ps1 file with the something that will match your silent install scenario, if you leave those as is – you will be prompted for installation parameters. In my case the info is as follows.

## This is the folder where installation files are
$SetupPath         = "C:\Users\MyUsername\Desktop\Sp2010Install"
## This command will prompt for the username and password
$FarmCredential    = Get-Credential "mydomain\yar";
## Database server name - we assume you already have this set up
$DBServer          = "mydbservername"
## This is optional parameter - a farm name
$FarmName          = "SP2010"
## This is also optional parameter - the port of the central admin site
$CAPort            = "1111"

7. Run the simplefarm.ps1 file by right clicking and selecting Run with PowerShell.

8. If you get a OWSTIMER crash error – just click NO to debug option and your setup will continue.

Good Luck!

Demystifying: SharePoint site collection specific timer jobs

If you worked with timer jobs in SharePoint (both MOSS and 2010) – you know that those execute on Web Application level. There in Central Administration you can see all of the definitions and statuses of running job. In SharePoint 2010 you can even change the schedule of those definitions.

The most typical way to provision new timer job is to use Web Application scoped feature will all the definition to SharePoint – which basically is a record in SharePoint configuration DB.

If you open SharePoint central administration and take a look at the list of timer job definitions – you will see that some of them are scoped to various site collection. In fact there are duplicates of the same timer job definition running on several sites.

So how do you provision site collection specific timer job from Web Application scoped feature?

Here is one of the ways to do it. Assuming your site inherits from a custom site template, we can enumerate web application site collections that have that template and provision our time job as we normally would once we find our site template.

The code would look like this:

webApp.Url
webApp.Url
webApp.Url
webApp.Url
webApp.Url
webApp.Url
webApp.Url
webApp.Url
webApp.Url
webApp.Url
webApp.Url
webApp.Url

One of the other ways to do it, is to accept feature parameters which will denote your Url in this case you would use:

webApp.Url

One of the things that becomes an issue though is when you use an automated tool to deploy your site – your web application gets created first – seemingly activating all the dependent features. In our case this means that actions will be taken on site collections that don’t yet exist.

In this case, you would need to activate your features manually once the structure has been provisioned using your automated tool.

Good Luck!

Programmatically accessing SharePoint 2010 Visual Upgrade options

One of the cool features in SharePoint 2010 is it’s ability to easily upgrade the site from MOSS. Just recently I have been upgrading a heavily customized site that had custom branding (and I’m talking custom-custom), JQuery calls to web services, custom web parts targeted for SharePoint 2010, site definitions, page layouts and many more. The upgrade went seamlessly and I think I was asked less questions than when I installed MS Excel.

As soon as the site is upgraded you will see all of the 2010 features available and event some of the icons in system UI will look 2010-ish; your Central Administration have 2010 UI. Your site however, will still be based of UI Version 3 (MOSS). You can upgrade it by using Visual Upgrade :

You will be given 3 options:

Use the previous user interface
Preview the updated user interface
Update the user interface

Usually when your site definitio(s) use custom master page, you will break your site when upgrading the UI to version 4. You will get an error message similar to this:

“Cannot find ContentPlaceHolder ‘PlaceHolderCSSLayout’ in the master page ‘/_catalogs/masterpage/v4.master’, verify content control’s ContentPlaceHolderID attribute in the content page.”

In case your users broke the site this way – you can always restore it back to the previous version by either using an upgrade page on your site: _layouts/prjsetng.aspx

or programmatically by updating the value of the SPWeb object of your root site collection site:

web.UIVersion 3; // 3/4 version web.UIVersionConfigurationEnabled = true; // is upgrade option locked?
web.UIVersion 3; // 3/4 version web.UIVersionConfigurationEnabled = true; // is upgrade option locked?

here you can also toggle whether you want to see upgrade option in Site Actions menu event though the upgrade has been successful – in case you want to toggle between UI versions in your development environment.

Good Luck!

Top 60 custom solutions built on Microsoft SharePoint Server 2010

Today is pretty exciting day for me – my book titled “Top 60 custom solutions built on Microsoft SharePoint Server 2010” is available for sale. It’s right now for purchase hereand at Amazon.com and in few more months in your local book store.

The book is intended for:

.NET developer with little experience in SharePoint looking to start developing using the latest release of SharePoint.

SharePoint developer gearing up for the new release of the product.
You’ll be taken through some neat examples similar to stuff you usually read on my blog. Plus you get all of the book source code.

Few goals that I kept in mind while writing this book are:

Get you familiar with technical and business scenarios rather than features of the product. When you’re in the middle of reading vague requirements on what you actually need to implement, it’s hard to see how all of those great new features you’re reading about will fit together to solve your problem on time. This book navigates through business and technical scenarios and, hopefully, it will get you to the correct solution right from the table of contents.

Give you a real code with all of the steps you need to do to run it. We’ve all been there. You have a technical problem, you find the solution someone has posted online, you put it together .. – it doesn’t The last thing you want to see is a sample that’s broken, and then few hours later find that post author forgot to include one step that you never thought you would be required to do. This book comes with references to downloadable solution files that have been compiled and tested.

Get you thinking about what else you can do with features described and scenarios used. Association is a powerful thing.

Hope you enjoy it!

Searching SQL from SharePoint 2010 search UI

In SharePoint 2010 there has been many improvements on how you can access external data and allow for it to be displayed to the user using SharePoint 21 UI. Search federation is one of those features.

Essentially on your search results page you can have few Search Core Results web parts where each can be set to return data from various Federated Locations. In this example we’ll take a look how you can configure local SQL running Adventure Works to be one of those Federated Locations.

In your SharePoint Central Administration select Search Service Application and then click Manage Federated Locations on the left.

You will be presented with an interface similar to below:

Here you can see few existing federation locations which you can export. In my example I’m going to export Internet Search Results federation location and rename the resulting OSDX file to SQLResult.osdx.

Next we’re going modify the OSDX file to support search in SQL Adventure Works.

Open OSDX file in notepad and modify below respective items in the XML file:

<ShortName>Adventure Works Results</ShortName>
 <Description>This location provides Adventure Works results.
location">1.</Version>  <ConnectionUrlTemplate xmlns="http://schemas.microsoft.com/
location">1.</Version>  <ConnectionUrlTemplate xmlns="http://schemas.microsoft.com/
27/location">SQLFederation.SQLServerLocationRuntime, SQLFederation, 
Version=1., Culture=neutral, PublicKeyToken=3afddfad18ff4ff</LocationType>  
<Version xmlns="http://schemas.microsoft.com/Search/27/
location">1.</Version>  <ConnectionUrlTemplate xmlns="http://schemas.microsoft.com/
Search/27/location">mssql://Data Source=.;Initial Catalog=AdventureWorksLT28; 
UserId=mydomain\yar;Password=mypassword;?q=Select TOP 1 Name as title 
From [SalesLT].[vProductAndDescription]</ConnectionUrlTemplate>

We’ll modify the query inside ConnectionUrlTemplate at this time ensure you have a proper user name and password to your SQL which I assume already has Adventure Works installed.

Now, you can import the newly modified file using the import command. After the import succeeds you can review what changes now have been added to the template and save the federation location.

At this time you can go to your search center and pick Search Core Results web part that you will use for your Adventure Works results and access the properties of the web part as shown below:

You can pick your new federated location; however, when you launch new search you won`t get any results just yet. In my next article I`ll show you how you can actually retrieve results from the Adventure Works DB and display them here.

Stay tuned ..

Creating custom list alert templates in SharePoint 2010

SharePoint 2010 allows you to create custom alert templates per list, meaning you can customize what’s going to show up in your SPList alert body.

In this example I won’t focus how you can actually edit the alert CAML – you can figure it out based on existing list of templates, let`s see what`s involved in creating a new alert template and assigning it to the list:

1. Create a new Visual Studio 2010 SharePoint solution.

2. Map a TEMPLATES folder in your solution directory and create a new folder underneath it called XML. This XML folder will contain an XML file that will define your alerts.

3. Create a new file in sub folder (project specific name) inside XML folder in your solution and add XML File into a sub folder.

4. Navigate to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML on your file system and open alerttemplates.xmlthis is out-of-the-box alert definition that you should not modify. Take a loot at the structure of the file and how each alert is defined.

5. Copy alert definition of the list type that closely resembles what you want your new alert to look like ad paste it into your solutions custom alert XML file. If we were to copy generic list template – everything including the XML below would have to be copied:

+ "YourAlertTemplates.xml");
Name="SPAlertTemplateType.GenericList">
</AlertTemplate>

6. Make any adjustments to the custom alert CAML (this is something you will have to figure out based your needs).

7. Create a new site scoped feature which will add our custom alert template to the list of your choice and not to any other on the site.

8. Add a receiver to the feature and in FeatureActivated method place the following code:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPSite site = properties.Feature.Parent as SPSite;
+ "YourAlertTemplates.xml");
    // The path to your alert templates
    xmlDoc.Load(SPUtility.GetGenericSetupPath(@"XML\YourProject")
+ "YourAlertTemplates.xml");
    // The list you want to have custom alert template
    SPList list = site..Lists["YourList"];
    SPAlertTemplate template = new SPAlertTemplate();
    template.Xml = xmlDoc.InnerXml;
    template.Name = "YourAlertTemplate";
    list.AlertTemplate = template;
    list.ParentWeb.AllowUnsafeUpdates = true;
    list.Update();
}

Above is going to take care of loading the template and assigning it to the list.

Now when this code is executed and template loaded to the list – new alert that are triggered with the template are going to come with the definition you have specified in your custom alert template file.

Good Luck!

Adding web title to your SharePoint 2010 search refiner

If you worked with SharePoint 2010 Faceted Search you know that now you have a refiner web part allowing you to refine your search by various criteria. The criteria in the refiner web part can be adjusted, removed or new ones can be added. As always there s a trick to things working. .. here is what’s involved in adding a Web Title to the refiner properties.

What we want to achieve here is when users search for keywords contained in files on various webs – we want the titles of those Webs to show up in the refiner web part.

I assume you already have the search there site.

1. Switch to the edit mode of the result page.

2. Locate the Refinement Panel Web Part and select Edit Web Part.

3. Under the Refinement category of the properties locate Filter Category Definition

4. Open the XML in some sort of an editor and add a new <Category></Category> to the list of existing categories.

Here is how the code of that category will look like:

LessLinkText="show less" ShowCounts="Count"></Category>
LessLinkText="show less" ShowCounts="Count"></Category>
LessLinkText="show less" ShowCounts="Count"></Category>
LessLinkText="show less" ShowCounts="Count"></Category>
LessLinkText="show less" ShowCounts="Count"></Category>
LessLinkText="show less" ShowCounts="Count"></Category>

Above, everything is pretty explanatory – we bind to the MappedProperty=”sitetitle” and show the results along with any corresponding properties.

Now, the only thing left is to make sitetitle to be accessible through a refiner.

1. Navigate to your SharePoint 2010 Central Administration.

2. Open Manage Service Applications UI.

3. Open Fast Query service application.

4. Under Administration on the left click Fast Search Administration.

5. Select Managed Properties and find the SiteTitle prperty.

6. Open the property details page and ensure you have the Refiner Property is selected along with others that look like this:

Click OK and now you should be all set. You can save you modified Refiner WebPart and perform another search. If your keyword matches any documents on several sub sites on the farm – those sub sites will show up in refiner.

Good Luck!