Wednesday, September 18, 2013

Creating a Custom WCF Service in SharePoint Server

Creating a Custom WCF Service in SharePoint Server:-




Add This Code to IRevert.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfService
{
    [ServiceContract]
    public interface IRevert
    {
        [OperationContract]
        void Revert(string listName, int listItemId);
    }
}

Add This Code to Revert.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfService
{
    using Microsoft.SharePoint.Client.Services;
    using System.ServiceModel.Activation;
    using Microsoft.SharePoint;

    [BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class RevertService : IRevert
    {
        public void Revert(string listName, int listItemId)
        {
            SPList oList = SPContext.Current.Web.Lists[listName];

            SPListItem oItem = oList.GetItemById(listItemId);

            if (oItem.Versions.Count > 1)
            {
                oItem.Versions.Restore(1);
            }
        }
    }
}



<%@ServiceHost Language="C#" Debug="true"
    Service="WcfService.RevertService, $SharePoint.Project.AssemblyFullName$"
    Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressBasicHttpBindingServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


Add to this .csproj file:-
<TokenReplacementFileExtensions>svc</TokenReplacementFileExtensions>





Run below Command:
svcutil.exe http://<server-name>/_vti_bin/CustomWCF/Revert/Revert.svc/mex?wsdl
After run we can see generated two file in this path "C:\wcftest"
1. output.config file
2. RevertService.cs file 
 

Source:  http://msdn.microsoft.com/en-us/library/ff521581(v=office.14).aspx
Thank You.

Friday, September 13, 2013

Working with CAML Query using Server OM, CSOM .NET, CSOM REST (JSON/ATOM), WEB Services, Powershell

CAML:-
---------
   <Where>
      <IsNotNull>
         <FieldRef Name='ID' />
      </IsNotNull>
   </Where>
   <ViewFields>
      <FieldRef Name='Title' />
   </ViewFields>

Server OM:-
---------------
try
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                using (SPWeb spWeb = site.OpenWeb())
                {
                    SPList spList = spWeb.Lists.TryGetList("Site Pages");
                    if (spList != null)
                    {
                        SPQuery qry = new SPQuery();
                        qry.Query = "<Where><IsNotNull><FieldRef Name=\"ID\" /></IsNotNull></Where>";
                        qry.ViewFields = "<FieldRef Name=\"Name\" />";
                        SPListItemCollection listItems = spList.GetItems(qry);
                        foreach (SPListItem listItem in listItems)
                        {
                            if (listItem != null & listItem["Name"] != null)
                            {
                                lblTitle.Text += listItem["Name"].ToString() + ", ";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
            finally
            { }

Client Side Object Model .NET (CSOM .NET):-
------------------------------------------------------------------
Source: http://msdn.microsoft.com/en-us/library/ee536158(v=office.14).aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using spClient = Microsoft.SharePoint.Client;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                spClient.ClientContext clientContext = new spClient.ClientContext("http://<server_name>:6677/");
                Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("Pages");
                clientContext.Load(spList);
                clientContext.ExecuteQuery();

                if (spList != null && spList.ItemCount > 0)
                {
                    spClient.CamlQuery camlQuery = new spClient.CamlQuery();
                    camlQuery.ViewXml = @"<View><Query><Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where></Query><ViewFields><FieldRef Name='ID' /></ViewFields></View>";

                    spClient.ListItemCollection listItems = spList.GetItems(camlQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();
                    foreach (spClient.ListItem listItem in listItems)
                    {
                        if (listItem != null && listItem["ID"] != null)
                        {
                            lblTitle.Text += listItem["ID"].ToString() + ", ";
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
            finally
            { }
        }
    }
}

Client Side Object Model ECMA Script:-
----------------------------------------------------------
1. Create a test ASPX page in the Pages library.
2. Add the Content Editor web part and add the following script in it.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
       <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/init.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            createList();
        });
    </script>
    <script type="text/ecmascript">
        function createList() {
            var clientContext = new SP.ClientContext.get_current();
            var oWebsite = clientContext.get_web();
            var listCreationInfo = new SP.ListCreationInformation();
            listCreationInfo.set_title('CustomList2'); // list name
            listCreationInfo.set_description('description'); // list description
            listCreationInfo.set_templateType(SP.ListTemplateType.genericList); //list type
            oWebsite.get_lists().add(listCreationInfo);
            clientContext.executeQueryAsync(
                Function.createDelegate(this, this.onQuerySucceeded),// when success
                Function.createDelegate(this, this.onQueryFailed) // when failed
                );
        }
        function onQuerySucceeded() {
            alert("List Created");
        }
        function onQueryFailed(sender, args) {
            alert("List Failed");
        }
    </script>
</asp:Content>

 -----------------------------------------------------------------------------------------------------
Client Side Object Model ECMA Script:-
--------------------------------------------------
1. Create a test ASPX page in the Pages library.
2. Add the Content Editor web part and add the following script in it.
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>    
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/init.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript">
if(typeof jQuery=="undefined"){
var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/";
document.write("<script src='",jQPath,"jquery.min.js' type='text/javascript'><\/script>");
}
</script>
    <script type="text/javascript">
        $(document).ready(function () {             
retrieveListItems();
        });
    </script>
    <script type="text/ecmascript">
function retrieveListItems() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<ViewFields><FieldRef Name=\'ID\' /><FieldRef Name=\'Title\' /></ViewFields>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));        
}
function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '\nID: ' + oListItem.get_id() + 
'\nTitle: ' + oListItem.get_item('Title');
    }
    alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

Client Side Object Model Rest (CSOM REST) using JSON:-
--------------------------------------------------------------------------------------
Source: http://blogs.breeze.net/mickb/CommentView,guid,d4bde347-853b-41b0-9e1c-11ce2ecbf500.aspx
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            CSOMRestJson();
        });
        function CSOMRestJson() {
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('CustomField')/Items?$select=Title",
                type: "GET",
                headers: { "accept": "application/json;odata=verbose" },
                success: function (data) {
                    if (data.d.results) {
                        var results = data.d.results;
                        var html = "<table>";
                        for (var i = 0; i < results.length; i++) {
                            html += "<tr><td>";
                            html += results[i].Title;
                            html += "</td><td>";
                            html += "</td><tr>";
                        }
                        html += "</table>";
                        alert(html);
                        $("lblText").text(html);
                        $('#<%= lblText.ClientID %>').text(html);
                    }
                },
                error: function (xhr) {
                    alert(xhr.status + ': ' + xhr.statusText);
                }
            });
            function onDataReturned(data) {
                // TODO: handle the data
            }
            function onError(err) {
                // TODO: handle the error
            }
        }
    </script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Label ID="lblText" runat="server"></asp:Label>
</asp:Content>

Client Side Object Model Rest (CSOM REST) using ATOM:- (but it is not working)
---------------------------------------------------------------------------------------------------------------------------------
Source: http://blogs.breeze.net/mickb/CommentView,guid,d4bde347-853b-41b0-9e1c-11ce2ecbf500.aspx
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            CSOMRestJson();
        });
        function CSOMRestJson() {
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('CustomField')/Items?$select=Title",
                type: "GET",
                contentType: "application/atom+xml;type=entry",
                headers: { "accept": "application/atom+xml" },

                success: function (data) {
                    if (data.d.results) {
                        var results = data.d.results;
                        var html = "<table>";
                        for (var i = 0; i < results.length; i++) {
                            html += "<tr><td>";
                            html += results[i].Title;
                            html += "</td><td>";
                            html += "</td><tr>";
                        }
                        html += "</table>";
                        alert(html);
                        $("lblText").text(html);
                        $('#<%= lblText.ClientID %>').text(html);
                    }
                },
                error: function (xhr) {
                    alert(xhr.status + ': ' + xhr.statusText);
                }
            });
            function onDataReturned(data) {
                // TODO: handle the data
            }
            function onError(err) {
                // TODO: handle the error
            }
        }
    </script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Label ID="lblText" runat="server"></asp:Label>
</asp:Content>

WEB Services:-
----------------------
Reference:- http://msdn.microsoft.com/en-us/library/aa979690(v=office.14).aspx
Web_Reference.Lists listsWS = new Web_Reference.Lists();
            listsWS.Credentials = System.Net.CredentialCache.DefaultCredentials;
            listsWS.Url = "http://<server_name>:6677/_vti_bin/Lists.asmx";

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            XmlNode queryNode = doc.CreateElement("Query");
            queryNode.InnerXml = "<Where><IsNotNull><FieldRef Name=\"ID\" /></IsNotNull></Where>";

            XmlNode viewfieldsNode = doc.CreateElement("ViewFields");
            viewfieldsNode.InnerXml = "<FieldRef Name=\"Title\" /><FieldRef Name=\"ID\" />";

            XmlNode queryOptionsNode = doc.CreateElement("QueryOptions");
            queryOptionsNode.InnerXml = "";

            string rowLimit = "150";

            System.Xml.XmlNode items = listsWS.GetListItems("CustomField", null, queryNode, viewfieldsNode, rowLimit, queryOptionsNode, null);
            foreach (System.Xml.XmlNode listItem in items)
            {
                lblTitle.Text += listItem.OuterXml + ", ";
            }
Powershell:-
---------------
$spweb = Get-SPWeb http://<server_name>:6677/
$splist = $spweb.Lists.TryGetList("Site Pages")
if($splist -ne $null)
{
   $query = New-Object Microsoft.SharePoint.SPQuery;$query.Query =
"<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>";$query.ViewFields = "<FieldRef Name='Title' />";$query.ViewFieldsOnly = $true;$items = $splist.GetItems($query);
}

Source: CAML Designer 2013.
Thank You.

Featured Post

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management https://docs.microsoft.com/en-us/azure/api-management/api-...

Popular posts