Friday, August 8, 2014

WCF Self Hosted Service using http Binding

Create Project based on WCF Service Library. This project will come with Service implementation by default as below

IService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFSelfHostingService
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}


Service.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFSelfHostingService
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}



Create Console Application and replace code as below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using WCFSelfHostingService;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/MyService/Service1");

            ServiceHost host = new ServiceHost(typeof(Service1), baseAddress);

            host.AddServiceEndpoint(typeof(WCFSelfHostingService.IService1),
                                new WSHttpBinding(), baseAddress);
            host.Open();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();

            // Close the ServiceHost.
            host.Close();

        }
    }
}


Create Windows Form Application and add code as below in form load event

private IService1 channel = null;
var endPoint = new EndpointAddress("http://localhost:8080/MyService/Service1");
            channel = ChannelFactory<IService1>.CreateChannel(new NetTcpBinding(), endPoint);
            string temp = channel.GetData(10);


WCF Self Hosted Service using Net Tcp Binding

Create Project based on WCF Service Library. This project will come with Service implementation by default as below

IService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFSelfHostingService
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}


Service.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFSelfHostingService
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}



Create Console Application and replace code as below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using WCFSelfHostingService;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("net.tcp://localhost:8080/MyService/Service1");

            ServiceHost host = new ServiceHost(typeof(Service1), baseAddress);

            host.AddServiceEndpoint(typeof(WCFSelfHostingService.IService1),
                                new NetTcpBinding(), baseAddress);
            host.Open();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();

            // Close the ServiceHost.
            host.Close();

        }
    }
}


Create Windows Form Application and add code as below in form load event

private IService1 channel = null;
var endPoint = new EndpointAddress("net.tcp://localhost:8080/MyService/Service1");
            channel = ChannelFactory<IService1>.CreateChannel(new NetTcpBinding(), endPoint);
            string temp = channel.GetData(10);

Thursday, August 7, 2014

JavaScript: Create an array with distinct random numbers with in a specified range

function getDistinctRandomIntForArray(array, range) { var n = Math.floor((Math.random() * range)); if (array.indexOf(n) == -1) { return n; } else { return getDistinctRandomIntForArray(array, range); } } function generateArrayOfRandomInts(count, range) { var array = []; for (i = 0; i < count; ++i) { array[i] = getDistinctRandomIntForArray(array, range); }; return array; }

Tuesday, June 10, 2014

SharePoint 2013: How to override user permission in SharePoint App

Each app has a manifest.xml file where the developer can define a list of resources that the app
needs access to using the AppPermissionRequests element. The following code snippet shows an
example of this element used in a provider-hosted app:

<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection"
Right="Read"/>
Right="Write">
<Property Name="BaseTemplateId" Value="101"/>
</AppPermissionRequest>
<AppPermissionRequest Scope="http://sharepoint/userprofilestore/feed"
Right="Post"/>
<AppPermissionRequest Scope="http://exchange/calendars" Right="Schedule"/>
</AppPermissionRequests>

Note the highlighted line in the code snippet. The app permission requests enable the app-only
policy, which means that only the app, and not the current user, requires the needed permissions. If
an app-only policy is not used, both the app and the current user require the necessary permissions
to complete a task such as accessing the entire site collection or writing to a list. The result would be
a context that contains both the app and the user identities.

Friday, May 23, 2014

SharePoint 2013: Organization App using Google Chart plugin

This example will get records from SharePoint List and display as chart for people organization.


Create Project using SharePoint App template.

Replace Default.aspx code as below

<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>

<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />

    <!-- Add your JavaScript to the following file -->

    <script type='text/javascript' src='https://www.google.com/jsapi'></script>
    <script type="text/javascript" src="../Scripts/App.js"></script>
    <script type='text/javascript'>

   </script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Organization Chart
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

    <div>
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
    </div>

    <div id='chart_div'></div>
    <div id='Div1'></div>       
</asp:Content>


Replace App.js code by below code :

'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var collList;
var clientContext;
var oWeb;
var oLists;
var oList;
var oListItems;
var oItems = "";
var hostweburl;
var appweburl;

hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
hostweburl = decodeURIComponent(hostweburl);
appweburl = decodeURIComponent(appweburl);

getUserName();
//retrieveListItems();

function drawChart() {
   
}

function retrieveListItems() {
    //clientContext = new SP.ClientContext.get_current();
    var appContextSite = new SP.AppContextSite(
    context,
    hostweburl
);
    //oWeb = appContextSite.get_web();
    oList = appContextSite.get_web().get_lists().getByTitle('OrgChart');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(
        '<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>1</Value></Geq></Where></Query>' +
        '<RowLimit>25</RowLimit></View>'
    );
    oListItems = oList.getItems(camlQuery);
    context.load(oListItems);
    context.executeQueryAsync(
        Function.createDelegate(this, onListSuceeded),
        Function.createDelegate(this, onListFailed)
        );
}
function onListSuceeded(sender, args) {
    //    alert("onListSuceeded");
    var EnumerateListItems = oListItems.getEnumerator();
    oItems = "data.addRows([ ";
    while (EnumerateListItems.moveNext()) {
        var oListItem = EnumerateListItems.get_current();
        var Name = oListItem.get_item('Name');
        var userName = "";
        if (Name != null)
            userName = Name.get_lookupValue();

        var ManagerName = oListItem.get_item('ManagerName');
        var managerName = "";
        if (ManagerName != null)
            managerName = ManagerName.get_lookupValue();

        oItems += "['" + userName + "','" + managerName + "',''],";
    }
    oItems = oItems.substring(0, oItems.length - 1);
    oItems += " ]);";
    //alert("from inside function " + oItems);
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Name');
    data.addColumn('string', 'Manager');
    data.addColumn('string', 'ToolTip');
    eval(oItems);
    var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
    chart.draw(data, { allowHtml: true });
    //$("#Div1").text(oItems);
}
function onListFailed(sender, args) {
    alert("onListFailed");
}
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}
// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    //$('#message').text('Hello ' + user.get_title());
    $('#message').text('Hello Rakesh Patel');
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}
google.load('visualization', '1', { packages: ['orgchart'] });
google.setOnLoadCallback(retrieveListItems);



Create List as per the attachment.