Ads

Monday, 13 April 2015

SharePoint Delegate Control with example

General delegates are also called as ambassadors, diplomats, representatives etc.
SharePoint has a couple of delegate controls like
  1. AdditionalPageHead
  2. GlobalSiteLink0
  3. GlobalSiteLink1
  4. GlobalSiteLink2
  5. PublishingConsole
  6. QuickLaunchDataSource
  7. SmallSearchInputBox
  8. TopNavigationDataSource
Apart from the above controls, we can also create our own custom delegate controls
The XML schema for delegate control is below:
<?xml version="1.0" encoding="utf-8" ?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
 <Control Id="SmallSearchInputBox" Sequence="100" Url="/templates/mysearchcontrol.ascx"/>
</Elements>


In above, properties for the delegate control as Control Id, Sequence and URL. We identify the delegate controls based on Control Id, Sequence number. The Sequence number defines the rank of the delegate, URL describes the source location of the control.
delegate control who’s Sequence id is less has most significant role in SharePoint site and will render on the site as first preference.
 What is the use of delegate control?
Using the delegate control a developer can customize the SharePoint site controls without editing or even touching the master page.
Note: We are not customizing the existing (default) delegate control but we are creating our own control loading onto the SharePoint site.

Let’s suppose assume one scenario, if we want to customize the SharePoint search box (by default SharePoint 2010 site has got input search box with one textbox and one button beside) see figure 1
Figure 1 - SharePoint 2010 Default Search Box
Figure 1 – SharePoint 2010 Default Search Box
Now I will try to customize the default search box, the requirement is to display the search box with scope drop down list, and also customizing the search button image with a arrow image button.
First open Visual Studio 2010 and click New > Project see figure 2
Figure 2 - Creating New Visual Studio 2010 Project
Figure 2 – Creating New Visual Studio 2010 Project
After project got created, I have deleted the not in use file (you can keep it there won’t be any problem if you don’t delete) because of maintaing clean solution I have removed user control, webpart related files see figure 3
Figure 3 - Solution Explorer File Structure
Figure 3 – Solution Explorer File Structure
Then add the following code in Elements.xml file

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
  <!--<Module Name="VisualWebPart1" List="113" Url="_catalogs/wp">
    <File Path="VisualWebPart1\VisualWebPart1.webpart" Url="CustomDelegateControl_VisualWebPart1.webpart" Type="GhostableInLibrary" >
      <Property Name="Group" Value="Custom" />
    </File>
  </Module>-->
  <Control
     Id="SmallSearchInputBox"
     Sequence="23"
     ControlClass="Microsoft.SharePoint.Portal.WebControls.SearchBoxEx"
     ControlAssembly="Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">
    <Property Name="QueryPromptString">This control is customized.....</Property>
    <Property Name="SearchBoxTableClass">search-box</Property>
    <Property Name="GoImageUrl">/_layouts/images/goviewfiles.png</Property>
    <Property Name="GoImageUrlRTL">/_layouts/images/goviewfiles.png</Property>
    <Property Name="GoImageActiveUrl">/_layouts/images/goviewfiles.png</Property>
    <Property Name="GoImageActiveUrlRTL">/_layouts/images/goviewfiles.png</Property>
    <Property Name="UseSiteDefaults">true</Property>
    <Property Name="FrameType">None</Property>
  </Control>
</Elements>


In the Element.xml file I have commented the Module section see figure 4
Figure 4 - Custom Delegate Control Element.xml file
Figure 4 – Custom Delegate Control Element.xml file
Now we are almost done, try to build, deploy and activate the feature which will result in change of SharePoint default search box with your customized control on fly without modifying the master page see figure 5
Figure 5 - SharePoint 2010 Custom Search Input Box
Figure 5 – SharePoint 2010 Custom Search Input Box

Friday, 10 April 2015

SharePoint 2013 Online App Development using NAPA Tool

 What is apps

‘Napa’ Office 365 Development Tools

For cretaing app MS has given  project templates in VS 2012 along with debugging tools.
Now MS gives new web based development tool called "Napa" Office 365 Development Tools.
Steps to create App with "Napa"
  1. Login to the Office 365
  2. Then Office 365 admin center --> developer site navigation --> Napa dev tool
  3. Napa tool download available in the home page of the developer site
  4. navigated to the Office apps store download site of the download
  5. step by step process of installing the Napa development tool to your environment.
This will be added to the trusted list of service in the browser (IE 9 or latter version)
After installation you can find NAPA inside developer site and under the site content section.


 Creating App using Napa (We will write JavaScript code to retrieve the list/library)

  1. Open the SharePoint Admin Center
  2. Under the site collection, open the developer site.
  3. Open the "Napa" Office 365 Development Tools from the developer Site Collection.
  4. Now you will be navigated to https://www.napacloudapp.com/.
  5. In the following page, you can see “What type of app do you want to build?” with App for SharePoint, Task pane App for Office, Content App for Excel and Mail App for Office project options.
  6. Enter the project name and click Create.
After creating the App using Napa, the project will auto create some folders and file as shown above.

Open the Default.aspx file under the Pages folder and add HTML tag to create a dropdown list.


Write JavaScript to retrieve the list names from the current app running context and populate the list names in the dropdown list. Open the file named App.js under the folder name Scripts.


We will write a GetListsToDisplay() which get the list/library name


And now, click on the Run Project button; appear near the status bar of the Internet Explorer.

Now your project will be packaged and installed on your SharePoint server. If this project is already running, the project uninstalls the previous version and installs the latest version.

The following screen capture will show the result for the code we have written in the JavaScript.









Wednesday, 1 April 2015

Start Client Object Model

SharePoint 2007 allows using its Object model to run against server running SharePoint. For clients (not running SharePoint in the box) the simplest way to communicate with SharePoint server is web services. SharePoint Client Object Model (OM) can be run on client PC (where SharePoint is not installed) to communicate with SharePoint server. So whereas SharePoint (Server) Object Model runs in a SharePoint server and can manipulate SharePoint objects, Client OM can run in client PC and communicate with SharePoint server remotely.

SharePoint 2010 introduces three new client APIs which can be used to interact with SharePoint sites. The three APIs are targeted for three different types of clients:
  1. For .net Managed applications (Eg: console applications, window applications, web applications).
  2. For Silverlight applications.
  3. For using with JavaScript (called ECMAScript or JSOM). 
    • This API is only available for applications hosted inside SharePoint (for example, web part deployed in SharePoint site can use this JavaScript API for accessing SharePoint from browser using JavaScript).
Lets see  some basic problems SharePoint 2017 in absence of Client Object Model.

Why Client Object Model (OM)?

SharePoint 2007 had no Client Object model available. So you may ask why this is introduced in SharePoint 2010? We had no problem without Client OM and millions of sites are running smoothly without having Client OM. The main reason is that Microsoft has found lot of requests from SharePoint users to introduce more and more web services to get data out of SharePoint in the last couple of years. But introducing web services will not fix the issues, as Microsoft found, because then the request for more functionality in the web services will continue. Even if Microsoft provides a good numbers of web services with SharePoint, customization in web services will be required for different clients and this will make the out of the box web services unusable. Also introducing a large number of web services will be a waste as not all companies will use all the web services functionalities.

In response to add more web services from users, Microsoft has taken a different approach called Client Object Model (OM). This SharePoint Client OM will allow getting data out of SharePoint from PCs that are not hosting SharePoint. Also Client OM provides complete API to interact with SharePoint Server which is more intuitive and useful and very much similar with SharePoint Object Model.

Similarity with SharePoint Object Model

The Client OM familiar with SharePoint Object Model as below.
Server (Microsoft.SharePoint) Client Object Model
SPContext ClientContext
SPSite Site
SPWeb Web
SPList List
SPListItem ListItem
SPField Field
So the class names in Client OM are similar as like SharePoint Object Model. However the way client OM will be used a bit different than usual SharePoint Object Model that we will explore in the upcoming posts.

How Client OM is developed and work under the hood?

It’s interesting how SharePoint team has developed the same set of classes for three different sets of applications (Managed, Silverlight and ECMAScript)
Client Type Assembly/File
Managed Client Microsoft.SharePoint.Client
Silverlight Microsoft.SharePoint.Client.Silverlight
ECMAScript SP.js or SP.debug.js
To ensure the same class object (say ListItem) behaves similarly in three different types of applications SharePoint team followed the steps described below:
a) SharePoint team first set attributes to the SharePoint classes and methods and properties that need to be exposed in Client OM.
b) Then a code generator is run against the SharePoint object model to generate client OM automatically.

This automated code generation has ensured maximum compatibility between these three sets of APIs. As the following figure shows client communicate to the server thorough Client OM which under the hood uses Client.svc WCF service to communicate with SharePoint Server. Client.svc service uses Server OM as per client request and return result to the client in JSON format.


image
Figure: How Client Object model works with Server
With this new Client OM, we almost don’t need to use web service to communicate with SharePoint server.
  
Client Object Model for JavaScript (ECMAScript)

Lets go through Client OM for JavaScript. ECMAScript Client OM is SharePoint 2010 client object model extension for using with JavaScript or JScript. Few points to notice about ECMAScript Client OM:
  • ECMAScript object model can only be used in SharePoint sites. So you can’t use this object model in an asp.net site to access SharePoint resources deployed in another url as this is cross-site scripting and not allowed.
  • You can’t use this object model in a SharePoint site to access resources in different SharePoint sites(i.e., different urls).
  • You can use JQuery with ECMAScript Client OM by adding reference to JQuery.js.
    • <SharePoint:ScriptLink Name="SP.js" runat="server" OnDemand="true" 
          Localizable="false" /> 
  • You can use this ECMAScript Client OM in web part pages or application pages (aspx pages) by referencing a javascript file (SP.js). You don’t need to add reference to the file manually.
    •  Rather use <SharePoint:ScriptLink Name=”sp.js” ………. />. 
    • Location: “Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS”
  • To update with JavaScript, you need to add a FormDigest tag in your page for security purpose. I’ll explain it later in details. 
    •  If your code modifies SharePoint content add a FormDigest control inside your page. The FormDigest add a security token inside your page based on user, site and time. Once the page is posted back the security token is validated. Once the security token is generated it’s valid for a configurable amount of time. Add the FormDigest inside <form>…</form> tag, as shown below:
    • <SharePoint:FormDigest runat="server" />
       
 Use Client OM to retrieve data:
 
<script type="text/javascript">
    function getWebProperties() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
        ctx.load(this.web);
        ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
            Function.createDelegate(this, this.onFail));
    }
    function onSuccess(sender, args) {
        alert('web title:' + this.web.get_title() + '\n ID:' + this.web.get_id() + 
            '\n Created Date:' + this.web.get_created());
    }
    function onFail(sender, args) {
        alert('failed to get list. Error:'+args.get_message());
    }
</script>

 Load minimal data if need:
  1. ctx.load(this.web,'Title','Id','Created');
 Execute your JavaScript function after sp.js is loaded:
  1.  ExecuteOrDelayUntilScriptLoaded(myjsfucntion, "sp.js");

 Update with ECMAScript Library:


<script type="text/javascript">
    function updateTitle() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
        web.set_title('UpdatedTitle');
        this.web.update();
        ctx.executeQueryAsync(Function.createDelegate(this, this.onUpdate),
            Function.createDelegate(this, this.onFail));
    }
    function onUpdate(sender, args) {
        alert('title updated');
    }
    function onFail(sender, args) {
        alert('failed to update title. Error:'+args.get_message());
    }
</script>

Deployment Consideration

SharePoint provides two sets of JavaScript file: minified and unminified/debug version.
  1. sp.js file is minified 
  2. sp.debug is minified and debug version. 
The default master page in SharePoint has a scriptmanager in the page and whose ScriptMode is set to auto, as a result the minified version of js file loaded. If you want to use debug version you can add the
<deployment retail="false" /> in the <system.web> section of the web.config.

The ECMAScript supported in the following browsers:
  • Microsoft Internet Explorer 7.0 or greater.
  • Firefox 3.5 or greater
  • Safari 4.0 or greater

Ads