Thursday, December 15, 2016

SharePoint JSOM to get User Profile Properties from the People Picker control

<!--References:
//https://thermofisher-my.sharepoint.com/_api/SP.UserProfiles.PeopleManager/GetMyProperties
//http://www.vrdmn.com/2013/07/sharepoint-2013-get-userprofile.html
//http://www.vrdmn.com/2013/07/sharepoint-2013-get-userprofile.html
//http://aaclage.blogspot.in/2015/05/get-user-profile-properties-and-update.html
//https://www.napacloudapp.com/Share/Edit/e201f57407b04e6484adb31f17a02201#/Pages/Default.aspxx -->


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="/_layouts/15/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="/_layouts/15/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/_layouts/15/init.js" type="text/javascript"></script>
//<script src="/_layouts/15/sp.runtime.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.js" type="text/javascript"></script>
<script src="/_layouts/15/SP.UserProfiles.js" type="text/javascript"></script>

<script type="text/javascript">


$(document).ready(function(){

});


SP.SOD.executeOrDelayUntilScriptLoaded(startOnChangeEvenet, 'SP.UserProfiles.js');

function startOnChangeEvenet(){
$("div[title='Name']").click(function() {
    alert("Onchange event");
    getUserProperties();
})

}


    var userProfileProperties;

    function getUserProperties() {

       var clientContext = new SP.ClientContext.get_current();
       var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
       
       
        //Property to fetch from the User Profile
      var propertyName = "PreferredName";
   
   //Domain\Username of the user (If you are on SharePoint Online)
  var targetUser = getUserFromPicker(); //"i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com";

if(targetUser != undefined){  
   
       userProfileProperty = peopleManager.getUserProfilePropertyFor(targetUser, propertyName)
       
       clientContext.load(userProfileProperty);
       clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
       }
     
       /* var clientContext = new SP.ClientContext.get_current();
        var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
        userProfileProperties = peopleManager.getMyProperties();
        clientContext.load(userProfileProperties);
        clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);*/
    }
   
    //Get the people picker resolved user name
    function getUserFromPicker()
    {  
var _PeoplePicker = $("span[class='sp-peoplepicker-userSpan']").attr('sid');      
        return _PeoplePicker;
    }

    // This function runs if the executeQueryAsync call succeeds.
    function onRequestSuccess() {  
 

var FirstName =userProfileProperties.get_userProfileProperties()['FirstName'];
$('input[title=FirstName]').attr(
       {value: FirstName});


var LastName=userProfileProperties.get_userProfileProperties()['LastName'];
$('input[title=LastName]').attr(
       {value: LastName});



var DisplayName=userProfileProperties.get_userProfileProperties()['PreferredName'];
$('input[title=DisplayName]').attr(
       {value: DisplayName});


var WorkPhone=userProfileProperties.get_userProfileProperties()['WorkPhone'];
$('input[title=WorkPhone]').attr(
       {value: WorkPhone});


var WorkEmail=userProfileProperties.get_userProfileProperties()['WorkEmail'];
$('input[title=WorkEmail]').attr(
       {value: WorkEmail});


var Manager=userProfileProperties.get_userProfileProperties()['Manager'];
Manager=Manager.split('|')[2];
$('input[title=Manager]').attr(
       {value: Manager});


var Office=userProfileProperties.get_userProfileProperties()['Office'];
$('input[title=Office]').attr(
       {value: Office});


var Group =userProfileProperties.get_userProfileProperties()['TFS-Group'];
$('input[title=Group]').attr(
       {value: Group});


var Division=userProfileProperties.get_userProfileProperties()['TFS-Division'];

$('input[title=Division]').attr(
       {value: Division});



var BusinessUnit=userProfileProperties.get_userProfileProperties()['TFS-BusinessUnit'];
$('input[title=BusinessUnit]').attr(
       {value: BusinessUnit});



var JobFamily=userProfileProperties.get_userProfileProperties()['TFS-JobFamily'];
$('input[title=JobFamily]').attr(
       {value: JobFamily});



var Functions=userProfileProperties.get_userProfileProperties()['TFS-Functions'];
$('input[title=Functions]').attr(
       {value: Functions});




var Department=userProfileProperties.get_userProfileProperties()['SPS-Department'];
$('input[title=Department]').attr(
       {value: Department});


    }

    // This function runs if the executeQueryAsync call fails.
    function onRequestFail(sender, args) {
        //$get("results").innerHTML = "Error: " + args.get_message();
    }


//People Picker On Change event







</script>

<!--<div id="results"> </div>-->

SharePoint JSOM Script to get User Profile Properties for current user

<!--References:
//https://site-my.com/_api/SP.UserProfiles.PeopleManager/GetMyProperties
//http://www.vrdmn.com/2013/07/sharepoint-2013-get-userprofile.html
//http://www.vrdmn.com/2013/07/sharepoint-2013-get-userprofile.html
//http://aaclage.blogspot.in/2015/05/get-user-profile-properties-and-update.html
//https://www.napacloudapp.com/Share/Edit/e201f57407b04e6484adb31f17a02201#/Pages/Default.aspxx -->


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="/_layouts/15/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="/_layouts/15/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/_layouts/15/init.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.runtime.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.js" type="text/javascript"></script>
<script src="/_layouts/15/SP.UserProfiles.js" type="text/javascript"></script>

<script type="text/javascript">

    //$(document).ready(function(){
        SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
    //});

    var userProfileProperties;

    function getUserProperties() {

        var clientContext = new SP.ClientContext.get_current();
        var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
        userProfileProperties = peopleManager.getMyProperties();
        clientContext.load(userProfileProperties);
        clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
    }

    // This function runs if the executeQueryAsync call succeeds.
    function onRequestSuccess() {  
 

var FirstName =userProfileProperties.get_userProfileProperties()['FirstName'];
$('input[title=FirstName]').attr(
        {value: FirstName});


var LastName=userProfileProperties.get_userProfileProperties()['LastName'];
$('input[title=LastName]').attr(
        {value: LastName});



var DisplayName=userProfileProperties.get_userProfileProperties()['PreferredName'];
$('input[title=DisplayName]').attr(
        {value: DisplayName});


var WorkPhone=userProfileProperties.get_userProfileProperties()['WorkPhone'];
$('input[title=WorkPhone]').attr(
        {value: WorkPhone});


var WorkEmail=userProfileProperties.get_userProfileProperties()['WorkEmail'];
$('input[title=WorkEmail]').attr(
        {value: WorkEmail});


var Manager=userProfileProperties.get_userProfileProperties()['Manager'];
Manager=Manager.split('|')[2];
$('input[title=Manager]').attr(
        {value: Manager});


var Office=userProfileProperties.get_userProfileProperties()['Office'];
$('input[title=Office]').attr(
        {value: Office});


var Group =userProfileProperties.get_userProfileProperties()['TFS-Group'];
$('input[title=Group]').attr(
        {value: Group});


var Division=userProfileProperties.get_userProfileProperties()['TFS-Division'];

$('input[title=Division]').attr(
        {value: Division});



var BusinessUnit=userProfileProperties.get_userProfileProperties()['TFS-BusinessUnit'];
$('input[title=BusinessUnit]').attr(
        {value: BusinessUnit});



var JobFamily=userProfileProperties.get_userProfileProperties()['TFS-JobFamily'];
$('input[title=JobFamily]').attr(
        {value: JobFamily});



var Functions=userProfileProperties.get_userProfileProperties()['TFS-Functions'];
$('input[title=Functions]').attr(
        {value: Functions});




var Department=userProfileProperties.get_userProfileProperties()['SPS-Department'];
$('input[title=Department]').attr(
        {value: Department});


    }

    // This function runs if the executeQueryAsync call fails.
    function onRequestFail(sender, args) {
        //$get("results").innerHTML = "Error: " + args.get_message();
    }


//People Picker On Change event

$("div[title='Name']").bind('OnControlResolvedUserChanged', function() {
     alert("Onchange event");
})


</script>

<!--<div id="results"> </div>-->

SharePoint 2013 Provider Hosted App Step by step configuration

A high-trust app is a provider-hosted app for SharePoint for use on-premises, which uses the server-to-server protocol. "High-trust" is not the same as "full trust", and high-trust does not mean the app has full trust. A high-trust app must still request app permissions. The app is considered "high-trust" because it is trusted to use any user identity that the app needs, because the app is responsible for creating the user portion of the access token.
A high-trust app is built for use in an on-premises environment; it's not intended for use in a cloud-hosted environment. Apps that use the server-to-server protocol would typically be installed behind the firewall in instances that are specific to each individual company.
 A high-trust app uses a certificate instead of a context token to establish trust.
The server-to-server STS isn't intended for user authentication. Therefore, you won't see the server-to-server STS listed on the user sign-in page, in the Authentication Provider section in Central Administration, or in the People Picker in SharePoint 2013.
Following instructions show you how to create a high-trust app and provides setup instructions for running it. Steps for creating a High Trust Provider hosted app are as follows:
·         Configure an app for use as a high-trust app.
·         Configure SharePoint 2013 to use high-trust apps.
·         Create a basic high-trust app.

1.  Create a public and private test certificate –
This example creates and exports a test certificate by using the Create Self Signed Certificate option in IIS. You’ll need a commercial certificate issued by a Certificate Authority when you publish your app. You’ll create a test .pfx certificate file first, and then a corresponding test .cer file.

To create a test .pfx certificate file

1.    In IIS manager, select the ServerName node in the tree view on the left. Select the Server Certificates icon



2.       Select the Create Self-Signed Certificate link from the set of links on the right side
3.       Name the certificate and choose OK.
4.       Right-click the certificate, and then select Export.
5.       Export the file to a common folder where you store all of the certificates that you use for your apps and give it a password. In this example, the password is password.

To create a corresponding test .cer file

1.       In Server Certificates view, double-click HighTrustSampleCert to display the certificate details.
2.      On the Details tab, choose Copy to File to launch the Certificate Export Wizard, and then choose Next.
3.     Use the default value No, do not export the private key, and then choose Next.

                                           

4.      Use the default values. Choose Next.

                                          

5.     Choose Browse, name the certificate, and then save it in a location you choose. The certificate is saved as a .cer file.



Note : The .pfx file must be accessible to the computer where Visual Studio is running. The .pfx file must be deployed to the web server that is hosting your web application, in the same file path as the computer running Visual Studio. Alternatively, the path can be adjusted in the web.config file.
The .cer file must be accessible to the server running SharePoint.

2.  Generate an issuer ID
Next, you generate an issuer ID, which is a GUID. There are many GUID generators online that you can use, or you can use the built-in GUID generator in Microsoft Visual Studio 2012. The issuer ID and the certificate together identify the issuer of the app. The issuer ID must have a one-to-one correspondence with the certificate, so whenever you create a new certificate for a high-trust app, you must create a new issuer ID to associate with it, and if you use the same certificate for more than one app, you must associate the same issuer ID with it. You can also use the following Windows PowerShell command to create a GUID.

 [System.Guid]::NewGuid().ToString()


3.  Configure SharePoint 2013 for server-to-server app use and configure trust for your app

1.    Create an isolated app domain on your development computer
a.    Ensure that the spadmin and sptimer services are running by opening a command prompt and typing the following commands.

net start spadminv4
net start sptimerv4
    1. Create your isolated app domain by running the SharePoint Management Shell as an administrator and typing the following command.

            Set-SPAppDomain "your app domain"
    1. Ensure that the SPSubscriptionSettingsService and AppManagementServiceInstance services are running by typing the following command in the SharePoint Management Shell.

Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"} | Start-SPServiceInstance
    1. Verify that the SPSubscriptionSettingsService and AppManagementServiceInstance services are running by typing the following command in the SharePoint Management Shell. The output will indicate whether each service is online.

Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"}
    1. You must specify an account under which the SPSubscriptionService and AppManagementServiceInstance service instances will run. This account must be an SPManagedAccount. You can create an SPManagedAccount by typing the following command in the SharePoint Management Shell. (You’ll be prompted for the account domain\user and password.)

$account = New-SPManagedAccount
    1. Specify an account, application pool, and database settings for the SPSubscriptionService and AppManagementServiceInstance services by typing the following code in the SharePoint Management Shell. If you created a SPManagedAccount in the preceding step, use that account name here.

$account = Get-SPManagedAccount "domain\user"
$appPoolSubSvc = New-SPServiceApplicationPool -Name SettingsServiceAppPool -Account $account
$appPoolAppSvc = New-SPServiceApplicationPool -Name AppServiceAppPool -Account $account
$appSubSvc = New-SPSubscriptionSettingsServiceApplication –ApplicationPool $appPoolSubSvc –Name SettingsServiceApp –DatabaseName SettingsServiceDB
$proxySubSvc = New-SPSubscriptionSettingsServiceApplicationProxy –ServiceApplication $appSubSvc
$appAppSvc = New-SPAppManagementServiceApplication -ApplicationPool $appPoolAppSvc -Name AppServiceApp -DatabaseName AppServiceDB
$proxyAppSvc = New-SPAppManagementServiceApplicationProxy -ServiceApplication $appAppSvc

    1. Specify your tenant name by typing the following code in the SharePoint Management Shell.

Set-SPAppSiteSubscriptionName -Name "app" -Confirm:$false

2.    Configuring Trust for your App
On the computer where you installed SharePoint 2013, run the following Windows PowerShell cmdlets to configure trust for your app:
a.     Get the .cer file that you want to use with your app.

           $publicCertPath = "common folder:\HighTrustSampleCert.cer"
b.     Get the issuer ID of your app. Currently, all the letters in the issuer ID GUID must be lowercase.

           $issuerId = [System.Guid]::NewGuid().ToString()
c.     Get the SharePoint 2013 URL where you will be installing your app.

           $spurl ="http://ContosoSharePoint.com"
d.     Get the website where you are installing your app.
Note:   If you're doing remote development where Visual Studio 2012 and SharePoint 2013 are not installed on the same computer, the root site collection must be created from a Developer Site template. It's required. If Visual Studio 2012 and SharePoint 2013 are installed on the same computer, it isn’t required

$spweb = Get-SPWeb $spurl
e.     Get the current authentication realm for your SharePoint site.

$realm = Get-SPAuthenticationRealm -ServiceContext $spweb.Site
f.      Get the file that corresponds to the .cer file you’re using for the app.

$certificate = Get-PfxCertificate $publicCertPath
g.     Add the certificate to SharePoint’s list of trusted root certificate authorities.

New-SPTrustedRootAuthority -Name "unique name for the certificate" -Certificate $certificate
h.     Get the issuer ID together with the realm value.

$fullIssuerIdentifier = $issuerId + '@' + $realm
i.      Create a trusted security token service. This fetches metadata from your app (for example, thecertificate) and establishes trust with it, so that SharePoint 2013 can accept tokens that are issued by your app.

New-SPTrustedSecurityTokenIssuer -Name $issuerId -Certificate $certificate -RegisteredIssuerName $fullIssuerIdentifier –IsTrustBroker
Note : The –Name parameter must be unique. You cannot reuse a previously used value. If you do, errors will be thrown.
j.      Run the iisreset command to make your new issuer ID valid. The issuer ID will become valid after 24 hours if you do not run iisreset.



Note: The following step is optional. However, we recommend that you develop and test with HTTPS turned on. Turning off HTTPS might cause you as a developer to miss certain issues when building an app that would occur during a production deployment where HTTPS is required.

OAuth now requires SharePoint to run HTTPS, not only for your service but also for SharePoint 2013. You’ll get a 403 (forbidden) message when attempting to make a call to SharePoint by using a test certificate.
On the computer where you have SharePoint 2013 installed, you can turn off the HTTPS requirement during development by using the following Windows PowerShell cmdlets.

$serviceConfig = Get-SPSecurityTokenServiceConfig
$serviceConfig.AllowOAuthOverHttp = $true
$serviceConfig.Update()

Remember to turn the HTTPS requirement back on later by using the following Windows PowerShell cmdlets.

$serviceConfig = Get-SPSecurityTokenServiceConfig
$serviceConfig.AllowOAuthOverHttp = $false
$serviceConfig.Update()

Create a provider hosted app
1.     In Visual Studio 2012, choose File, New, Project.
2.     In the New Project wizard, expand the Visual C# node, and then expand the Office/SharePoint node.
3.     Choose Apps, and then choose to create an App for SharePoint 2013 project.
4.     Name the project HighTrustSampleApp.
5.     Save the project in a location you choose, and then choose OK.
6.     Select the Provider-hosted hosting option, and then choose the Next button.
7.     Under How do you want your app to authenticate?, choose Use a certificate.
8.     Click the Browse button next to the Certificate location box and navigate to the location of the self-signed certificate (.pfx file) that you created. Type the password for this certificate in the Password box. Type the issuer ID in the Issuer ID box.

To test the app for SharePoint and its remote web application, press F5 in Visual Studio 2012. The web application will be deployed to IIS Express at localhost. The app for SharePoint will be installed to the target SharePoint website. You’ll be prompted by SharePoint to grant the permissions that the app for SharePoint requests. The Site Contents page of your target SharePoint website will open and you’ll see the new app listed there.
 
                            


Click Trust It.



The token helper code in TokenHelper.cs does the following:
  • Configures .NET to trust certificates when making network calls.
  • Retrieves a server-to-server access token that is signed by the application's private certificate on behalf of the specified WindowsIdentity object and that the SharePoint 2013 uses to establish trust.
  • Gets the SharePoint security token service (STS) certificate.

Note: In a high-trust app, there is no context token, even if you use the appredirect.aspx file. The context token is specific to configurations that use Windows Azure Access Control Service (ACS). However, an access token is still required. If you’re using a high-trust configuration, your web application has to authenticate the user in the same way that SharePoint 2013 does (that is, the app is responsible for creating the user portion of the access token).






Publishing & Packaging WebApp project
·         Upon completing the above development and configuration of the project, we need to publish the projects.
·         Before you can publish your app, you have to register it and obtain an app ID and secret. When you use the Visual Studio 2012 publishing wizard, it’ll ask you to supply these values. See Guidelines for registering apps for SharePoint 2013 for the full range of ways to register your app. The steps in this article assume that you are using the http:// yoursite/_layouts/15/appregnew.aspx page of your SharePoint 2013 site.
o   To obtain App id and secret
Navigate to the http://yoursite/_layouts/15/appregnew.aspx page of your SharePoint site. Choose the Generate buttons to generate values for your app ID and secret. Provide the base URL of the domain where the remote portions of your app will run. If you need a redirect URI, enter a value for that also.


Choose Create. The information that you entered for your app will be displayed on the next page, as shown in Figure 2. Be sure to keep this information available because you will need it when you use the Publish apps for Office and SharePoint wizard.

·         Copy the AppID , AppSecret in Config file in <appsettings> section –
<appSettings>
    <add key="ClientId" value="3fdc79ce-bc35-446f-b2e6-b193ecc3cfb7" />
    <add key="ClientSecret" value="9Bnnm0fh2GbQhK7yfexe+YQQN0uXcmdVng2b3TOiOds=" />
    <add key="ClientSigningCertificatePath" value="C:\Supriya\HighTrustSampleCert.pfx" />
    <add key="ClientSigningCertificatePassword" value="Newuser@123" />
    <add key="IssuerId" value="0b6abcab-f90f-4463-b5b0-46b97e5286c6" />
  </appSettings>


AppManifest.xml – AppPrincipal
<AppPrincipal>
    <RemoteWebApplication ClientId="3fdc79ce-bc35-446f-b2e6-b193ecc3cfb7" />
  </AppPrincipal>


·         The first project i.e the App project gets published to SharePoint and the AppWeb  project i.e .net web application gets published to the other server( not necessarily SharePoibnt server). We can deploy this AppWeb project on a local server or remote server.
Publishing the App project.
Ø  Go to the App Project and open the AppManifest.Xml file

Ø   Under General tab Supply the start page url. In our case we have the website url on http://www.ltispapps.com/pages/default.aspx
Ø  Under Permissions tab we need to provide full control at web scope.
Ø  Save and Click publish.











Ø  Create a profile, type the name and click next.

Ø  Type the ClientId and Client Secret for the app created above through appregnew.aspx and Click Next.
Ø  Check the Summary and click Finish.
Publishing the AppWeb project
·         But before publishing the AppWeb projects we need to keep certain things in mind.
Ø  AppWeb project can be published through Web deploy, File System, FTP, FPSE.
Ø  While publishing via Web Deploy there are some pre-requisites which is needed to be done on the destination server. Firstly, Web Deployment Tool 2.1 and Web Deploy3.0 needs to be installed through web platform installer on the destination server.
Click Install.
Ø  Under services.msc  we can check that Web Deployment Agent Service and Web Management Service should be running after installation is complete.



·         On the remote server, create a website in iis and add a virtual directory.

·         In this case, we have created new website named - spApps and added a virtual directory in c:\.
·         We need to edit the bindings and supply the host name. In our case we have hosted it on port 80.

·         For https we need to export the self-signed certificate that we have used while the associating the app. On destination server, we import it through iis under server certificate.



·         Click Import


·         Supply the path by clicking the Browse, password and certificate store will be personal. Click Ok.



·         For our newly created website at port 80 we need to associate the certificate for https.

·         We need to create the publishing profile for our website.

For creating publishing profile, select the website under content view.
Click the Configure Web Deploy Publishing.
A window  will open . We need to specify the path for the profile and click Setup.

·         Navigate to the path where profile is published.

·         Copy this profile published file and paste it on the source server.


We move on to the source server and perform the publishing part of WebApp.
·         Go to the solution and select AppWeb project. Right Click and select publish.

·         Upon clicking publish, windfow will open . Click Import and select the profile publish file which you have pasted on the source server.

Click Next


·         The details are automatically filled in through the profile publish file which we have imported. The service Url should be from ip address and not from the machine name. Because on validating the connection it throws an error.
·         Provide the password and cross check the details and click Next.

·         Click Next

·         We can preview  by clicking the Start Preview which display all the dll’s and files which get published to our .net website on the destination server.

Click Accept.

Click Publish.


Ø  Deploy the solution


Ø  We will be navigated to the browser where we have to enter the credentials.
Ø  Click Trust it

Ø  On clicking trust it we will be navigated to the contents of the App with the url of our .net website.