Saturday, March 8, 2014

Consuming JsonP from a WCF Service ( C# .Net ) using jQuery across different Domains

Introduction
This article explains how JsonP can be used to access data across different Domain and thus get rid of annoying message."This Page is accessing information that is not under its control. This poses a security risk. Do you want to continue?". In this article, I will explain in details how to create a WCF JsonP Service using C# .Net and then how to consume this service from a client side jQuery script in HTML.

Though JsonP is required for old browsers, I would strongly recommend using CORS in new browsers. Following references will provide you the required resource for implementing CORS.

To know about JsonP, please read followings

Background
We get an annoying message."This Page is accessing information that is not under its control. This poses a security risk. Do you want to continue?" when accessing JSON data from a different domain(also called as Cross Domain) . Though we can resolve this by changing settings in IE or other browser, this may not be the feasible solution

Using the code

Server Side Code : WCF Service Application
1) Create a WCF Service Application (In Visual Studio 2010)

2) Right click on the project and Add a Class. Name it Employee and add following properties to employee class as shown below.
public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Role { get; set; }
} 

3) Right click on the project and Add a new item of type WCF Service. Name it EmployeeService.svc 
Note: As per MSDN article we have to decorate/annotate the class with [JavascriptCallbackBehavior(UrlParameterName = "callback")] But I was able to make it work even without this tag.
[ServiceContract]
[JavascriptCallbackBehavior(UrlParameterName = "callback")]
public class EmployeeService
{
    private readonly Employee[] employees = 
    {     
        new Employee { ID = 1, Name = "Mathew", Role = "HR" },
        new Employee { ID = 2, Name = "Mark", Role = "Manager" },
        new Employee { ID = 3, Name = "John", Role = "Marketing" },
        new Employee { ID = 4, Name = "Luke", Role = "Developer" },
    };

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public List<Employee> GetEmployees()
    {
            
        return employees.ToList();
    }


    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public Employee GetEmployee(int id)
    {
        return employees.FirstOrDefault(p => p.ID == id);
    }       
       
} 

4) Modify the web.Config as below:
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="jsonPCrossDomainBinding" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <services>
      <service name="WcfDemo.EmployeeService">
        <endpoint  
            contract="WcfDemo.EmployeeService"
            address="" 
            binding="webHttpBinding"
            bindingConfiguration="jsonPCrossDomainBinding"
            behaviorConfiguration="webHttpBehavior"/>
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>  
</configuration>

Client Side HTML Code:
1) Add a new Asp.Net web form of HTML page
Add a jQuery reference from CDNA or use a local copy of Query.

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 

2) Add following Script to your HTML page 

<script type="text/javascript">
    $(document).ready(function () {

        $('#btnEmployees').click(function () {
            //Show loading
            var $employeesList = $('#employeesList');
            $("#loading").html('Loading Employees ...');

            // Get JsonP data from WCF
            $.getJSON('http://localhost:14900/EmployeeService.svc/GetEmployees?callback=',
                    null, 
                    function (employees) {
                        $("#loading").empty();
                        $employeesList.empty();
                        var count = 0;
                        $.each(employees, function () {
                            $employeesList
                                .append($('<li />')
                                .text(this.ID + " - " + this.Name + " - " + this.Role));
                            count++;
                        });

                    if (count > 0) {
                        $("#search").show();
                    }
             });
        });

        $('#btnSearchEmployee').click(function () {
            //Show loading                
            $("#loading").html('Loading Employee Details...');

            // Get JsonP data from WCF
            var employeeID = parseInt($("#searchText").val());
            $.getJSON('http://localhost:14900/EmployeeService.svc/GetEmployee?callback=?',
            { id: employeeID }, 
            function (employee) {
                $("#loading").empty();
                $('#employee')
                    .empty()
                    .text(employee.Name + " - " + employee.Role);
            });
        });
    });

</script> 

3) Add following HTML
 <div>
    <h2>
        Consuming JsonP from WCF using jQuery</h2>
    <input type="button" id="btnEmployees" value="Show All Employees" />
    <div id="loading">
    </div>
    <ul id="employeesList">
    </ul>
    <div id="search">
        <input type="text" id="searchText" />
        <input type="button" id="btnSearchEmployee" value="Search Employee" />
        <br />
        <div id="employee">
        </div>
    </div>
</div>

References

http://msdn.microsoft.com/en-us/library/ee816916(v=vs.110).aspx

You can find the working code at Consuming JsonP from a WCF Service ( C# .Net ) using jQuery across different Domains




Thursday, March 6, 2014

Finding SiteTemplate type in SharePoint 2010 & 2013

Many a times, we may not have access to the SharePoint environment. But we may want to know the SharePoint Site Template type without logging into the Servers and without using Site Settings/Administration.

Here are the steps:

1) View the Page source(In IE, Right Click on the page and click View Source. In Chrome, Click Ctrl + I).
Search for the Keyword g_wsaSiteTemplateId


If you see something like var g_wsaSiteTemplateId = 'STS#0';, then the site was created using Team Site. You can map the value of g_wsaSiteTemplateId  to a specific Site Template.
For example 'STS#0' is the code for Team Site


2) If you want to know all templates open PowerShell and run 
Get-SPWebTemplate | format-table -auto | Out-File -FilePath  "C:\temp\Output.txt" 
You will get a list of all templates
If you don't have a local SharePoint environment, you can find them from Bernd Kemmler's Blog

3) Some of the most commonly used  are
  • STS#0        Team Site
  • STS#1        Blank Site
  • WIKI#0      Wiki Site
  • BLOG#0     Blog Site
  • CMSPUBLISHING#0  Publishing Site               
  • BLANKINTERNET#0  Publishing Site                                                     

Thats it.

Good Luck.

Adding Twitter Widget to your Blog Templates (Step by Step)

Step 1:
Browse https://twitter.com/settings/widgets/new 
Enter your user name and password

Step 2:
Click "Create Widget" button found at the bottom of the page. You will see a screen as below.



Click save changes.

Step 3:
Select and Copy the HTML code from the Twitter Widget creation page. (Highlighted in yellow in my Screen Shot) 

Step 4:
Browse to https://www.blogger.com/home. Click on the Blog to which you want to add Twitter Widget. Click Layouts Template.

Step 5:
In the Layouts Template, click Add Gadget link where  you want to add Twitter Widget. This will open up a Popup with several options. Select HTML/Javascript option.

Step 6:
Paste the HTML code copied in step 3 Text Area for Gadget. Save the Layout Arrangement and then Preview template. Make sure to save your changes.

Twitter Buttons can also be added similarly using following link.
https://about.twitter.com/resources/buttons#tweet

That's it. Good Luck.