Friday 15 January 2016

Jquery Datatables Plugin - Tabular display of data

Server Side
----------------------    
 public class Result
        {
            public int articleid { get; set; }
            public string Name { get; set; }
            public string Position { get; set; }
            public string Office { get; set; }
            public string Extn { get; set; }
            public string Startdate { get; set; }
            public string Salary { get; set; }
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public static string GetJsonEmps()
        {
            List<Result> lsts = new List<Result>();
            for (int i = 1; i <= 10; i++)
            {
                lsts.Add(new Result() { articleid = i, Name = "AA" + i, Position = "home" + i, Office = "aas" + i, Extn = "extn" + i, Startdate = "date" + i, Salary = "sal" + i });
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            string json = js.Serialize(new { data = lsts });
            if (!string.IsNullOrEmpty(json))
            {
                return json;
            }
            return "";
        }

Client Side
-------------------

 <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" />
    <script src="Scripts/jquery-1.11.1.js" type="text/javascript"></script>
    <script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js" type="text/javascript"></script>


 $(document).ready(function () {


            $("#btnSave").click(function (e) {              
                var table = $('#example').DataTable();
                e.preventDefault();
                $(".chkcls").each(function () {
                    if (this.checked) {                     
                        var $row = $(this).closest('tr');
                        // Get row data
                        var data = table.row($row).data();
                        // Get row ID
                        var rowId = data[0];
                        alert("row id is " + rowId);
                    }
                });
            });


            createtable();

        });

     function drawTable(arr) {
            var table = $('#example').DataTable({
                iDisplayLength: 5,
                responsive: true,
                processing: true,
                "aaData": arr,
                columns: [
            { title: "Select" },
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "Extn" },
            { title: "Startdate" },
            { title: "Salary" }
           ],
                "aoColumnDefs": [{
                    "aTargets": [0],
                    //"mData": "download_link",
                    "mRender": function (data, type, full) {
                        //debugger;
                        if (isarticlesubmittable(data)) {
                            return '<input type=\"checkbox\" class=\"chkcls\" disabled="disabled" checked value="' + data + '">';
                        } else {
                            return '<input type=\"checkbox\" class=\"chkcls\" value="' + data + '">';
                        }
                    }
                }]
            });
        }

        function isarticlesubmittable(status) {
            return status == 1 || status == 3;
        }

 var datatable;
        function createtable() {
            $.ajax({
                type: "GET",
                url: "Jquery-datatable.aspx/GetJsonEmps",
                data: "{}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) { drawtable(response); },
                error: function (xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }

            });
        }
        function csave() {           
            datatable.destroy();
          
        }

        function drawtable(result) {
            var result = $.parseJSON(result.d);
            var arrayReturn = [];
            for (var i = 0, len = result.data.length; i < len; i++) {
                var res = result.data[i];
                arrayReturn.push([res.articleid, res.Name, res.Position, res.Office, res.Extn, res.Startdate, res.Salary]);
            }       

            drawTable(arrayReturn);          
        }

Final Output
-------------------


Publishing , Packaging & Deploying Provider Hosted App – Vol 2

This tutorial contains information about Packaging , Publishing & Deployment of Apps using Visual Studio 2012 or later.
Today we gonna discuss how to package our provider hosted application and publish it through App Catalog.The Publishing procedure contains two phase , in first we will publish the App Web Project and in second we’ll do it for all the App Projects.An App project is which is deployed/installed in SharePoint server(Online or On-Premise) pointing to a web application(Web App Project) hosted at some location(Infrastructure) provided by Organization i.e IIS Server or Windows Azure.


Some Prerequisites:
  • Microsoft SharePoint Server 2013 or SharePoint online(Office365).
  • Visual Studio 2012 with Office Developer Tools for VS2012 else VS2013(No need of additionally installing Developer Tools).

Setting the Scenario:

At this stage we are supposed to have Provider Hosted App working fine when deployed and Installed Directly using VS(Optional).This practically means we have ClientID, ClientSecret and IssurID in web.config of Web Project ,set and configured correctly to SharePoint.Refer this link to Know More.

Steps to Publish Provider Hosted App

It’s a Pre-Requirement from Microsoft that if our Provide hosted application has App Web Application i.e Web Project then we need to deploy it first after that we’ll publish our App Project.
Note:In order to deploy ClientID, ClientSecret and IssuerID to sharepoint along with Web Project we need to Publish(Register) it through SharePoint App Register Page.

Registering The App to SharePoint Server

you can open it for your site collection by appending “/_layouts/15/appregnew.aspx/” at last of URL.
For example: http://(server-name):(port-number)/_layouts/15/appregnew.aspx/

appregnew
On that page enter ClientId & ClientSecret in place of AppId and AppSecret Respectively.
Give tile of your app in Title text box and in App Domain enter the Server Name(Machine Name) already set as App domain in Central Admin where your App will be hosted.
Redirect URL is optional here. After all set up hit “Create”.
Next , we will move to Publish Our Web Project. Here are the steps:

Publishing App Web Project to SharePoint Server

    First of all in VS , select App Web Project say “DemoAppWeb”. Right click “DemoAppWeb” and click on “Publish”.It will open Publish Web Application Form.
  • Here the first step is to Choose/Import a Publish Profile or Create a new One.This Publish Profile basically specifies your Host Server for App Web.You can have more then one Profile based on your requirements.For now we are creating a new One.It will open create publishing wizard for profile.Enter the name for new Publish Profile.Hit next.
  • Now, For publish method we’ll choose Web Deployment Package.
  • Next give a path for package location where we gonna save this package file.you can store it anywhere say in “D:”drive.
  • After that give the site/application name where this Web Application going to be hosted in IIS Server.So give a path like this.
    http://(target-server-name):(port-number)/
    note:Save this “port-number” somewhere , as we need to create a site application in IIS Server with this same Port number which will act as Virtaul Directory for our App Web Project.
  • Then hit next tab.
  • Now comes the settings section , here we’ll choose “Release” as our option.Hit on next and Publish.This will create Some files along with a Zip File with name as“DemoAppWeb.zip”. Save location of this file.We’ll need it.

Hosting Web Project in IIS(local) Server

  • First of all unzip the “DemoAppWeb.zip” file it will create a folder with name “DemoAppWeb”. This Folder’s content will be used for the Virtual Directory we gonna create in Next Step.
  • Now browse to PackageTmp folder in the Extracted Zip Folder and copy its path.
  • Create a new App Pool in IIS Server using .Net Framework 4.0.
  • Now, we have to add a new Site in IIS Serer assign this App Pool created above to it and give it a port we have saved earlier for this purpose. I can remember we have giver 1234 as port number.:)
  • Click on Create website and it will create a new website under sites folder in IIS.
  • Open Authentications Settings for this website and Enable Windows Authentication and Disable Anonymous Authentication.
  • We have to give Read & Write Permission on this folder (PackageTmp) for “Everyone” and “IIS_IUSRS”Users.Find “IIS_IUSRS” by selecting the Server as location while adding the permission group.

Publishing App Project to be deployed via App Catalog

Now, the last step in Publishing is to publish and create package file for App Project. Follow below steps for this:
  • In VS Solution, right click on App Project i.e “DemoApp” in this example and select publish.
  • In Profile section, select an old profile or create a new one.We’ll go for new profile here.
  • Then it’ll ask for host location where this is gonna be hosted. Here give the URL of the App Web hosted on the IIS in “Hosting Web Project in IIS(local) Server” section above. i.e
    https://(target-server-name):1234/
    Note:For the https above we need to add https binding under Site Bindings with default port number for it.
    Or For you can put https:// for meanwhile just for publishing app. and later you can modify it back to https by editing .app file.This will work. HTTPS will not be supported by many browsers or ask for allowing content to render data,so better you make it HTTP only.
  • Provide ClientIDCertificatePath,CertificatePassword and IssuerID used in Web.config under App settings tag.
    webconfig
  • Now Click on Next and finish it Off.
  • After publishing successfully it will open the publish folder , there we can find “DemoApp.app” file very easily.This is our App file.

Deploying Provider Hosted App using App Catalog to SharePoint

Now, we need to just deploy this App to SharePoint Site Collection using App catalog.

Follow below Steps for Deployment.
  • In the App Catalog Site created in Target Web Application, add new app to the “Apps for SharePoint” list and browse to the .app file we got after publishing. Upload this .app file and fill the details form.
  • After this .app file is successfully added to the list of apps.Just select this app item and click on View Details page.
  • Add this App to the App Catalog.This will get added and listed in All Site Contents.
  • Next you need to Deploy it to the desired Site Collection under this Web Application.
  • At last consume this app from your target site collection and you are done.

HOW TO CREATE PROVIDER HOSTED APP IN SHAREPOINT 2013

This tutorial will cover creation of Provider Hosted App in SharePoint 2013 On-Premise using Visual Studio 2012. We’ll discuss complete Configuration and settings required to create a provider hosted app with a step by step approach.Also In a Continuing Article we’ll share procedure to Publish Your App in Front-End Server(Client Side) with Some Trouble Shooting tips.SharePoint App Model has become popular among developers , you can realize this by seeing progressive graph of number of Apps in SharePoint App Store.

Microsoft Introduces Apps Model in its SharePoint 2013 Model having “Everything is an App” Policy.We are provided with three Kind of Apps:
  • SharePoint Hosted Apps
  • Provider Hosted Apps
  • Auto Hosted Apps
To know More About all these Apps Refer this Link.
We’ll go with Provider Hosted App in this article.
Prerequisites
You need to set your SharePoint Application Server with these required Software’s:
1.Windows Server 2008 R2 OS -64 Bit/Windows 7 and other Variant.
2.Microsoft Sharepoint 2013 Server – Enterprise Edition(For Enhanced Functionality).
3.Visual Studio 2012- Professional/Ultimate.
4.Microsoft Office Developer Tools for Visual Studio 2012 (RTM).
5.Microsoft Web Deploy – v3.0 or higher(Required for Publishing Apps).
6.Microsoft Exchange Web Services-EWS Managed API 2.0 or Latest.
Some Server Level Settings:
1.Check below mentioned Services are up and running on Server
Central Admin -> System Settings -> Manage Services on Server.
(1) App Management Service.
(2) Claims to Windows Token Service.
(3) Microsoft SharePoint Foundation Subscription Settings Service.
(4) Request Management Service.
(5) User Profile Synchronization Service.
2.Features to be activated at Web Application Level
Central Admin ->Application Management -> Manage Web Application Features (in ribbon control)
Apps that require accessible internet facing endpoints (For SharePoint Store- optional).
Open Visual Studio “Run As Administrator”. -> New Project -> Find Apps for SharePoint 2013 Under Office/SharePoint Template Group.
SharePoint Solution
Note:
(1)If you are facing Error “An error occurred whilst trying to load some required components, Please ensure the following prerequisite components are installed…” . referThis Link to resolve this.
(2)Also you need to Run Visual Studio with System Admin Account also Farm Admin for Sharepoint Server. But this account should not be used while configuring and installing SharePoint Farm otherwise you will face Error.You won’t be able to deploy it.Same issue has been Listed On MSDN Forum here…, To resolve this you can create a new Account in Active Directory , Add it in System Administrators Group and also add it as Farm Admin. Run using this account.

  • In Next Page VS will ask for name for the App, Debugging location (Site collection URL where you want to deploy) and Type of hosting.Choose Provider Hosted from the drop down list and click next.
  • App Hosting Type
    Next you need to give Authentication Settings , you can see two options in RadioButton, First is using ACS(Low-Trust Apps) and second is using a Certificate(High-Trust Apps). Choose second option Use a Certificate. Insert Certificate location, password and Issuer ID. How to Create OAuth Certificate In SharePoint 2013 For High-Trust Apps.Also that certificate has to be registered under SPTrustedSecurityTokenIssuer.Lean how to Register Here.

    OAuthCertificate
    • You’ll see that the New Solution for Provider Hosted App is Ready.The Solution will contain two projects one App and one Web. In Web Project we have TokenHelper.cs Class it contains Methods to setup trust across Server and authenticate client for accessing this app.Solution Structure
    • Now Select Web Project & Right Click->Properties.Under Web tag you can use IIS Express or custom IIS Web Server.For IIS Server in Project URL you will have like http://localhost/{Project-Name} for Port:80. Click on Create Virtual Directory button , it will create a virtual directory for your app in IIS Server under Site SharePoint -80 having Port 80.You can create under any other site also changing the Port Number.Virtual Directory
    • Now in App Project Double click on AppManifest.xml file in App Project. And go under Permissions Tab there add Scope to Web, Site Collection, Lists, Taxonomy, User Profiles and other fields depending upon your Requirement.These are permissions you gonna give to your App or user depending upon the App policy You chose.Permissions
      After that right click on AppManifest.xml and choose view Code. You will find all permissions given above inside tag. And put AllowAppOnlyPolicy attribute set to true for App Only App policy i.e App having Elevated Privileges in one way.
    • Now we need one ClientId for our app registered as an App Principle for SharePoint.Learn how to register App Principal here.
      Registering an App Principal
      For each App we’ll need a Client Id registered with Sharepoint. We need to register it before deploying our app.Client Id is just a GUID with all letters in small case. We can generate a GUID for this via following Page. URL will be like
      http://Root-url/_Layouts/15/appregnew.aspx
      We’ll use above App Id as our Client Id and register it with Sharepoint. We have PowerShell script for this, shown below:

      cls
      Add-PSSnapin "Microsoft.SharePoint.PowerShell"
      # set intialization values for new app principal
      $appDisplayName = "(Identifier-name)"
      $clientID = "(Generated-ClientId-Above)"
      $targetSiteUrl = "(Site-URL)"
      $targetSite = Get-SPSite $targetSiteUrl
      $realm = Get-SPAuthenticationRealm -ServiceContext $targetSite
      $fullAppPrincipalIdentifier = $clientID + '@' + $realm
      Write-Host "Registering new app principal"
      $registeredAppPrincipal = Register-SPAppPrincipal -NameIdentifier $fullAppPrincipalIdentifier -Site $targetSite.RootWeb -DisplayName $AppDisplayName
      $registeredAppPrincipal | select * | Format-List
      $registeredAppPrincipal | select * | Format-List | Out-File -FilePath "Output.txt"
      Write-Host "Registration Completed"
      #Get-SpAppPrincipal -?
      Note: Above mentioned values in (), has to be chnaged according to your setup, where:
      (Identifier-name):- Name of App Identifier you need to use for Registering App Principal.
      (Generated-ClientId-Above):- ClientID generated above from App registration Page.
      (Site-URL):-Target Site Collection URL.
    • Now this ClientID we need to replace in Two Places. One in Web.Config under Web Project you will find all values given previously for Cerificare in tag. Put Value for ClientID that we just registered & other in Appmanifest.xml file under App Project.
    • That’s It.Now just press F5 in debug mode.It will go through a series of Steps and end with Deployment.After deployment it will open App Principal Trust Page.As the app is going to access resources, so it’ll ask you if you trust this app or not.This page will come once only for the first time after deployment, until you retract it again.Trust App Principal
    • Trust it, it will redirect to Default.aspx(Default aspx web form) page deployed locally.The Url will be like
      http://localhost/{Project-Name}/Pages/Default.aspx?{StandardTokans}
      This URL is set in AppManifest.xml under:
      ~remoteAppUrl/Pages/Default.aspx?{StandardTokens}
      appmanifest