Article 30 from 30 : Licensing your app

This post is article 30 from the 30 Articles App series for SharePoint

In this article, I will discuss about Licensing your SharePoint app on office store.

When you upload your app on the Office Store for publication, you can choose the terms of the license you want to offer, like offering your app for free, trial, or for purchase. Or your app can be acquired on a per-user or site basis.

SharePoint provides a licensing framework that lets you include code logic in your app to enforce whatever licensing restrictions you choose. For example, you can include code logic in your app that enables users to access certain app features if they have a paid license, but not if they have a trial license.

A user with a license for an app can use that app on any site for that particular SharePoint deployment. In general, for the purpose of app licenses, deployment is defined as the SharePoint farm for on-premises SharePoint installations, and the tenancy for SharePoint Online in Office 365. The app’s purchaser can manage the app license, assign those app licenses to other users within their deployment, and enable other users to manage the licenses. A user who is assigned an app license can access and use the app.

For apps for SharePoint that have a per-user license, each app license can be assigned to the specified number of SharePoint users. The app license applies only to the specified SharePoint deployment and the specified users.
For apps with a site license, that license is assigned to all users on that deployment automatically. You cannot programmatically assign app licenses.

App license query and validation process :
1. The user launches the app from within SharePoint.
2. This launches the app code in the cloud.
3. When the app needs to verify a user’s app license, it uses server-side code to query SharePoint, via the client object model, for the app license token.
4. It then passes that token to the Office Store verification service.
5. The verification service returns whether the license token is valid, and if it is, also returns the license properties.
6. The app can then take action, based on the validity of the license and its properties
OfLicAppSP

 

 

Finally, after you finish testing your app and are ready to move it to production, you need to add code to the license checks in your app so that the app no longer accepts test licenses.

Let’s validate app’s Validate the app license token in code:

Retrieving app license tokens using GetAppLicenseInformation :

productId = new Guid();
using(ClientContext ctx = new ClientContext(webUrl))
{
    ClientResult licensecollection = Microsoft.SharePoint.Client.Utilities.Utility.GetAppLicenseInformation(ctx, productId);
    ctx.ExecuteQuery();
}

Validating the app license token
After you retrieve the appropriate app license token, pass that token to the Office Store verification web service for validation. The verification service is located at the following URL: https://verificationservice.officeapps.live.com/ova/verificationagent.svc

The Office Store license verification web service also supports verifying app license tokens using REST calls. To verify an app license by using REST, use the following syntax:

https://verificationservice.officeapps.live.com/ova/verificationagent.svc/rest/verify?token=token

Where {token} is the app license token

For test app licenses, the IsTest property returns true and the IsValid property returns false.
This sample requires a reference to Microsoft.SharePoint.Client.Utilities, and a web service reference to the Office Store verification service.

retrieving app license tokens : GetAppLicenseInformation

//Get the license token XML from SharePoint.
this.rawToken = GetLicenseTokenFromSP(this.productId, this.clientcontext);

//Call the Office Store verification service.
VerifyLicenseToken(this.rawToken);

private string GetLicenseTokenFromSP(Guid productId, ClientContext clientContext)
{
    //Get the license from SharePoint.
    ClientResult licenseCollection = Utility.GetAppLicenseInformation(clientContext, productId);
    clientContext.Load(clientContext.Web);
    clientContext.ExecuteQuery();

    foreach (AppLicense license in licenseCollection.Value)
    {
        //Just get the first license token for now.
        rawLicenseToken = license.RawXMLLicenseToken;
        break;
    }
    return (rawLicenseToken);
}

private void VerifyLicenseToken(string rawLicenseToken)
{    
    if (string.IsNullOrEmpty(rawLicenseToken))
    {
        licVerifyEndPoint.Text = "There is no valid license for this user in SharePoint (OR) license cannot be obtained due to some error - check ULS.";
        return;
    }

    VerificationServiceClient service = null;
    VerifyEntitlementTokenResponse result = null;
    VerifyEntitlementTokenRequest request = new VerifyEntitlementTokenRequest();
    request.RawToken = rawLicenseToken;
    lblSPLicenseText.Text = System.Web.HttpUtility.HtmlEncode(request.RawToken);   

    try
    {
        service = new VerificationServiceClient();
        result = service.VerifyEntitlementToken(request);
    }
    catch (EndpointNotFoundException)
    {
        licVerifyEndPoint.Text = "Cannot access verification service endpoint";
    }
    catch (FaultException)
    {
        licVerifyEndPoint.Text = "Error: entitlement verification service is unavailable.";
    }
    catch (FaultException internalFault)
    {
        licVerifyEndPoint.Text = "Error: entitlement verification service failed. Details: " + internalFault.Detail.Message;
    }
    catch (Exception exception)
    {
        licVerifyEndPoint.Text = "Error: entitlement verification service failed. Details: " + exception;
    }

    if (result != null && result.AssetId !=null)
    {
        string licenseDetails = string.Format("Asset Id: {0}; Product Id: {1}; License Type: {2}; Is Valid: {3}; License Acquisition Date: {4}; License Expiry Date: {5}; IsExpired: {6}; IsTest: {7}; IsSiteLicense: {8}; Seats: {9}; TokenExpiryDate: {10}",
                result.AssetId, result.ProductId, result.EntitlementType, result.IsValid, result.EntitlementAcquisitionDate, result.EntitlementExpiryDate, result.IsExpired, result.IsTest, result.IsSiteLicense, result.Seats, result.TokenExpiryDate);

        if (result.EntitlementType.ToUpper() == "FREE")
        {
          //Allow basic functionality
        }
        else if (result.EntitlementType.ToUpper() == "PAID")
        {
          //Allow all functionality
        }
        else //trial
        {
          //Allow limited functionality
        }
    }
            else
    {
        licVerifyEndPoint.Text = "Verification service didn't return any results";
    }
}

Hope you have enjoyed this series !!

Advertisements

Article 29 from 30 : SPC14 summary on App Development

This post is article 29 from the 30 Articles App series for SharePoint

Future of Auto-hosted apps :

A few blogs from SPC14  say about AutoHosted Apps are being deprecated, This could be a rumor as Microsoft has not yet confirmed anything officially on this. If they are not being deprecated in near future, for how long they will be supported or when they may go from preview to fully supported is still not clear. As they are still in Preview, they should be avoided for Production design and recommended for only prototyping .

Some new Infographics for Apps:

These infographics can be downloaded from here . They give good and quick understanding on Why to build SharePoint apps?, App Concepts, App – hosting options, Data storage/access options etc.

New Office Web Widgets:

These experimental UI widgets were announced at SPC14 and are intended to help building apps for Office and SharePoint. The first release includes People Picker and the List View widgets. As per the Office dev team, these widgets are “experimental” and its primary goal is to collect feedback. They plan to release these controls for production use soon. Download it from NuGet Manager (search for Office Widgets) . Try it and send your feedback on UserVoice using the Office Web Widgets category.

NugetOfficeWidget

New Office 365 SDK for Android Preview:

Finally Microsoft is thinking openly ;). this sdk is built by  MS Open Tech and provides access to:

• Microsoft SharePoint Lists

• Microsoft SharePoint Files

• Microsoft Exchange Calendar

• Microsoft Exchange Contacts

• Microsoft Exchange Mail

The SDK is composed of three independent packages, so that you can import only the SDK that you need in your project.

  • office365-files-sdk [depends on office365-base-sdk]
  • office365-lists-sdk [depends on office365-base-sdk]
  • office365-mail-calendar-contact-sdk

For more info on this refer to http://msopentech.com/blog/2014/03/03/new-open-source-sdk-for-android-brings-office-365-apps-to-life/

 

External links to SPC14 Summary articles from SharePoint Community folks:

 

Article 28 from 30 : handling App Upgraded event

This post is article 28 from the 30 Articles App series for SharePoint

Web components can also be deployed programmatically using a remote event receiver InstalledEventEndpoint or an UpgradedEventEndpoint. If you are adding components in other than the app web you should also implement an UninstallingEventEndpoint that uninstalls those same components.

Handling the app updated event :

Your sharepoint app should have valid UpgradedEventEndpoint refering to your remote service.

In web project ,  open AppEventReceiver.svc.cs file and add a conditional structure to the ProcessEvent to handle appUpdated event like following.

if (properties.EventType == SPRemoteEventType.AppUpgraded)
{
using (ClientContext cc = TokenHelper.CreateAppEventClientContext(properties, true))
    {
        // CSOM code that accesses the app web
    }
    using (ClientContext cc = TokenHelper.CreateAppEventClientContext(properties, false))
    {
        // CSOM code that accesses the host web
    }
    // Other update code as per your need 
}

Provide conditional structure to handle the app updated event on subsequent updates

Version ver2OOO = new Version("2.0.0.0");
if (properties.AppEventProperties.PreviousVersion < ver2OOO)
{
    // Code to update from 1.0.0.0 to 2.0.0.0 is here.
}

Version ver3OOO = new Version("3.0.0.0");
if (properties.AppEventProperties.PreviousVersion < ver3OOO)
{
    // Code to update from 2.0.0.0 to 3.0.0.0 (previous update code) is here.
}
// Code to update from 3.0.0.0 to 4.0.0.0 is here.
catch (Exception e)
{ 
    // Make sure you catch all exceptions while updating and rollback to undo if that is necessary.
    result.ErrorMessage = "error message : " + e.Message;
    result.Status = SPRemoteEventServiceStatus.CancelWithError;
}

In some cases, you might need to migrate data or upgrade schema. If your old data is somewhere that can be accessed by a remote event handler, you can implement migration logic in an InstalledEventEndpoint web service of the new app. Alternatively, if the new app has access to the old data, you can put the migration logic in code that runs the first time that a user starts the new app. If the old data cannot be accessed by either the remote handlers or the new app, you can create an update of the old app that adds a data export capability and a UI for the capability. Users would first update the old app, and then use it to export the data to a location where the new app can access it. You include the capability and UI to import data in the new app.

Article 27 from 30 : updating an app

This post is article 27 from the 30 Articles App series for SharePoint

When an app is installed, the SharePoint host environment records the version number for the installed app instance. App catalog sites always track their version number with the Office Store and detect if there is any update is available or not. The upgrade process by the SharePoint app model provides user-friendly experience which looks like below steps.

The app tile you will show “An update for this app is available” approx. 24hrs after an app update is published to the app store.

UpgradeApp

By default, SharePoint checks every 24 hours for updates to installed apps. A farm administrator can change this value to whichever is suitable.  SharePoint Management Shell command, where h is the number of hours between checks.

Set-SPInternalAppStateUpdateInterval -AppStateSyncHours h

If you need to run this update immediately then you can click on “About” from the app tile – > get it and trust it to update the app.

Appupdate2

Make sure you do not change the ProductID number.

Major steps that may be needed when you create an update for an app for SharePoint :

  • Raise the Version number in the App element of the appmanifest.xml file. (MUST BE DONE)
  • Change the AppPermissionRequests and AppPrerequisites section of the appmanifest.xml file.
  • If your updating app-web components then Add any new components to the Feature exactly as you would if you were creating a new app for SharePoint project. Change existing files as needed. Open the Feature XML for editing, Increment the Version attribute of the Feature element.
  • Updating host-web components – custom actions and app parts is easier than in the app web. You don’t need any update semantics. Just add/change the custom actions and app parts. When the app for SharePoint is updated, SharePoint always applies any new element manifest files and reapplies any changed element manifest files with the most recent version. When you update an app part, SharePoint replaces the old version with the new version in the Web Part gallery. Be sure to change the Name property of the ClientWebPart object when you update an app part. Doing this ensures that, when the app is updated, SharePoint will remove the old version of the app part (which is no longer part of the app) from all pages to which it was added. Users will need to re-add the new version to pages.

You can also deploy web components programmatically using a remote event receiver, which I will cover in next article.

Article 26 from 30 : App authorization

This post is article 26 from the 30 Articles App series for SharePoint

In this article I will be discussing about app authorization policies.

Like users and groups, an app has its own identity in SharePoint. The authorization process verifies that an authenticated user and/or app has permission to perform certain operations or to access specific resources. The authenticated identities can be user identity only, user + app identities, or app identity only. Correspondingly three authorization policy are as following :

  • User-only policy— In this policy, the authorization checks take into account only the user identity. When a user is accessing SharePoint resources directly without using any app this policy is enforced.
  • User + app policy—In this policy, the authorization checks take into account both the user identity and the app identity.  An authorization checks succeed only if both the current user and the app have sufficient permissions to perform the action in question. This policy is used when a Office Store app, which does not run in SharePoint Server , wants to act on behalf of the user to get access to the user’s resources.
  • App only policy—In this policy, the authorization checks take into account only the app identity.  An authorization checks succeed only if the current app has sufficient permissions to perform the action , regardless of the permissions of the current user.  This policy is enforced is when the app is not acting on behalf of the user. In this policy, the person who installs the app has the rights that the app needs, even though users who actually use the app might not have those rights.

To request an app to use App-only policy your app needs to add attribute called “AllowAppOnlyPolicy” in tag node of AppPermissionRequests with value = ‘true”. User must be Site Collection Administrator to allow use of the app-only policy.

<AppPermissionRequests AllowAppOnlyPolicy="true">
... 
</AppPermissionRequests>

App- Only Policy can only be used for Auto Hosted Apps or Provider Hosted Apps.

Hope that helps..!!

Article 25 from 30 : App permissions – II

This post is article 25 from the 30 Articles App series for SharePoint

In this article, I will discuss more on scope and a few examples for app permissions.

an app can have these rights : Read , Write, Manage, FullControl. These rights correspond to the default permission levels: Reader, Contributor, Designer, and Full Control. For more information about user permission levels, see User permissions and permission levels.

Permission request scopes for other (other than sitecollection, website, list ) SharePoint features

Scope URI Available Rights More Info
http://sharepoint/bcs/connection Read Business Connectivity Services in SharePoint 2013
http://sharepoint/search QueryAsUserIgnoreAppPrincipal Search in SharePoint 2013
http://sharepoint/taxonomy Read, Write taxonomy
http://sharepoint/social/tenant Read, Write, Manage, FullControl  social
http://sharepoint/social/core Read, Write, Manage, FullControl  social
http://sharepoint/social/microfeed Read, Write, Manage, FullControl  social
http://sharepoint/projectserver Manage  projectserver
http://sharepoint/projectserver/projects Read, Write  projectserver
http://sharepoint/projectserver/projects/project Read, Write  projectserver
http://sharepoint/projectserver/enterpriseresources Read, Write  projectserver
http://sharepoint/projectserver/statusing SubmitStatus  projectserver
http://sharepoint/projectserver/reporting Read  projectserver
http://sharepoint/projectserver/workflow Elevate  projectserver

Only Read, Write, and Manage rights are allowed for Office Store apps. If you try to submit an app to the Office Store that requires FullControl rights, your app is blocked from submission. However apps that request more than Manage permissions can still be deployed through the app catalog.

Below are some example code for AppManifest file with different scope and rights of App permission

Request Read access to the web scope and the list scope.

<AppPermissionRequests>
  <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read"/>
  <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web/list" Right="Read"/>
</AppPermissionRequests>

Request Write access to the list scope.

<AppPermissionRequests>
  <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web/list" Right="Write"/>
</AppPermissionRequests>

The list permission request scope has an additional optional property. BaseTemplateId, and an integer value corresponding with a list base template, which filters the available lists down to the set of lists that match what is specified by the BaseTemplateId property.

<AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web/list" Right="Write">
    <Property Name="BaseTemplateId" Value="101"/>
</AppPermissionRequest>


Request access to all user profiles. ( This app must be installed by a tenant administrator. )

<AppPermissionRequest Scope="http://sharepoint/social/tenant" Right="Read">
</AppPermissionRequest>

Request user’s feed or the team feed. This scope applies to personal sites that support microblogging or to team sites where the Site Feed feature is activated. If the app installs on any other type of site, use the Tenant scope.

<AppPermissionRequest Scope="http://sharepoint/social/microfeed" Right="Read">
</AppPermissionRequest>

 

Hope that helps..!!

Article 24 from 30 : App permissions – I

This post is article 24 from the 30 Articles App series for SharePoint

In this article I will be discussing about app permissions. What are they and how does it work.

Like users and groups, an app has its own identity in SharePoint. each app in SharePoint is associated with a security principal, called an app principal. An app principal has certain permissions and rights.

An app may perform the operation on SharePoint site/web/list and other SharePoint artifacts, It needs certain permission just like an user or a group.

During installation, an app for SharePoint requests the permissions that it needs from the user who is installing it.

The developer of an app must request, the permissions that the particular app needs to be able to run, through the app manifest file.

The user who installs the app must grant all the permissions that an app requests or not grant any permission—the permission granted by the user to an app is all or nothing. An app must be granted permissions by the user who is executing the app. Users can grant only the permissions that they have.

The permission requests specify both the rights that an app needs and the scope at which it needs the rights.

SharePoint 2013 supports three different permission scopes within the content database and tenancy as below.

Scope URI Description
site collection :  http://sharepoint/content/sitecollection The permission request scope URI to the site collection where the app is installed. Includes all children of this scope.
website : http://sharepoint/content/sitecollection/web The permission request scope URI to the website where the app is installed. Includes all children of this scope.
list : http://sharepoint/content/sitecollection/web/list The permission request scope URI to the list where the app is installed. Includes all children of this scope.
tenancy : http://sharepoint/content/tenant The permission request scope URI to the tenancy where the app is installed.

If an app is granted permission to one of the scopes, the permission applies to all children of the scope. For example, if an app is granted permission to a website, the app is also granted permission to each list that is contained in the website, and all list items that are in each list.

SharePoint 2013 supports four rights levels in the content database. For each scope, an app can have these rights : Read , Write, Manage, FullControl

Permission request

Description

Permissions included

Read-Only Enables apps to view pages, list items, and download documents.
  • View Items
  • Open Items
  • View Versions
  • Create Alerts
  • Use Self-Service Site Creation
  • View Pages
Write Enables apps to view, add, update, and delete items in existing lists and document libraries.
  • Read-Only permissions, plus:
  • Add Items
  • Edit Items
  • Delete Items
  • Delete Versions
  • Browse Directories
  • Edit Personal User Information
  • Manage Personal Views
  • Add/Remove Personal Web Parts
  • Update Personal Web Parts
Manage Enables apps to view, add, update, delete, approve, and customize items or pages within a web site.
  • Write permissions, plus:
  • Manage Lists
  • Add and Customize Pages
  • Apply Themes and Borders
  • Apply Style Sheets
Full Control Enables apps to have full control within the specified scope.
  • All permissions

Check next article for more details on App permissions.

Hope that helps..!!

Article 23 from 30 : Troubleshooting High-Trust App

This post is article 23 from the 30 Articles App series for SharePoint

In this article I will be discussing about basic guidelines on troubleshooting tips for High-Trust apps. I assume that you already has good understanding of High-Trust app and how to develop one.

Below are some steps you should consider to look into when you run into problems:

(1)    For Hight-Trust App your remote web’s web.config should have appsetting something like below

<appSettings>

<add key="ClientId" value="your-client-id-guid-in-lowercase"/>

<add key="ClientSecret" value="client-secret"/>

<add key="ClientSigningCertificatePath" value="C:\cert.pfx"/>

<add key="ClientSigningCertificatePassword" value="****"/>

<add key="IssuerId" value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"/>

</appSettings>

(2)    Refer to article-15 to know about how to configure high-trust using client-certificate and configuring high-trust.

(3)    App deployed successfully but client context is always null or you are getting 401 unauthorized error

Make sure you are passing valid identity of Logged in user,

Do iisreset after high-trust configuration if necessary

(4)    App deployed successfully but you are getting 403 forbidden error

oAuth requires SharePoint to run HTTPS. So whenever your SharePoint app attempt to make a call using a test certificate, you will get 403 (forbidden) error.

To overcome this issue, simply turn off HTTPS on your development SharePoint environment using following Powershell command:

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

Hope that helps..!!

Article 22 from 30 : Troubleshooting Provider-Hosted App

This post is article 22 from the 30 Articles App series for SharePoint

In this article I will be discussing about basic guidelines on troubleshooting tips for provider hosted apps. I assume that you already has good understanding of provider hosted app and how to develop one.

Below are some steps you should consider to look into when you run into problems:

(1)    Make sure your remote web is already up and running before you deploy your app.

(2)    Make sure all the service are up and running and they have valid listening endpoints if you are using any remote receivers.

(3)    Make sure that you have valid client id in App manifest file, which must be exactly same as client id in your remote web’s web.config file

(4)    Make sure the client id is in lowercase in (3).

(5)    Make sure you have registered your app with SharePoint. You can register your app from Appregnew.aspx  page. It is available via following url : https://SPServer/Sites/AnySiteCollection/_layouts/15/Appregnew.aspx

Store the client id and secret and use that in (3)

appregnew

(6)    When you are deploying your app to office store you can generate client id, Client Secret from office seller-board.

(7)  Make sure your app has all the necessary permission.

Troubleshooting tips continues for Hight-Trust provider hosted app in next article.

Hope that helps..!!

Article 21 from 30 : what can be included in SharePoint App?

This post is article 21 from the 30 Articles App series for SharePoint

One of the common question I get from many readers is that what possibly they can do with SharePoint App? So here in this article I will discuss about what possible SharePoint artifacts and components you can include in an App.

One explicit limitation of the SharePoint App Model is that no server-side code can reside on the SharePoint farm as part of an App, and so if your app need to use any server-side code then it must be hosted outside of SharePoint either in the cloud or on-premises. So and when applicable any use of server-side code need cloud App Model. And the main benefit is that you can always scale your application without affecting the current SharePoint environment.

So here it begins, You can create/include all sort of SharePoint components mentioned below in your SharePoint App :

Fields (of field types that are built into SharePoint)

Custom content types

Custom List templates

List and library instances

Custom list views

Custom list forms

Remote event receivers -> check Article -17, 18 for more details

Custom actions (including shortcut menu items and ribbon customizations) -> Check Article -12

Modules, Pages, CSS, JavaScript files used by SharePoint pages,

SharePoint WebParts (built-in) and app parts -> Check Article -8

You can also include Features (Web-scoped only), Web templates (but not site definitions), BCS Models (web-scoped only), external Content types and external lists referencing to that BCS Model, Property bags; and Workflows (SP2013 workflows now use Azure hosted workflow runtime. Coded workflows that use the SharePoint-hosted workflow runtime cannot be included in an app for SharePoint.Only declarative workflows or workflows that use the newer runtime are allowed. to see what’s new in SP2013 workflow check this)