DotNetSlackers: ASP.NET News for lazy Developers

Friday, December 11, 2015

Folder protection for Windows using C# and concepts on Windows Shell menu for folders

Since the release of Windows 8, we have all ben wondering when we would see a touch-optimized Office experience.  We saw apps delivered to both iOS and Android first, but still nothing for Windows other than Office 2013 for desktop.  All of that changes today as Microsoft has release previews of Word, Excel, and PowerPoint as Universal Apps for Windows 10.  If you are not familiar with the term Universal app yet, this is a single app that can run on Windows 10 desktops, tablets, and phones.  Support for Xbox One has even been pledged but there hasn’t been any updates on that in quite some time.  These look just like existing apps for Windows 8.1 formerly known as Metro, Windows Store, and now Modern Applications in Windows 10.
You’ll need to be running the latest public build (9926) of Windows 10 to try these preview out.  The original blog post had links to Word, Excel, and PowerPoint.  However, they have been removed for the moment.  However, I still have the links to Word and Excel handy.  These links only worked for me in Internet Explorer.  If you try them on a Windows 8.1 computer, you won’t see the “Get” button nor will you be redirected to the Windows Store to download the app.  The blog posts says you can do a search from the new Windows Store (Beta) app, but I haven’t had it work yet.  This is typical though when a new app is released to the store.
After you have installed the apps, launch them from your start menu or by asking Cortana.  We’ll start with Excel Preview.  Notice, Excel Preview listed as a Modern Application where Excel 2013 is a DesktopApplication.
W10b9926SearchExcel
When each Office Preview app starts, it will show you a quick three-step tutorial on how to get started specifically highlighting touch features.  Here, you learn how to move columns by touch.
ExcelPreviewStartup1
You can add rows and columns with a tap.
ExcelPreviewStartup2
Here, you have the option to join the customer experience improvement program.
ExcelPreviewStartup3
Once you start the app, you’ll see a familiar screen with templates that you can use to get started.  It will automatically pull in your recent files that you have used on OneDrive.
ExcelPreviewOpenFile
Be sure and click on the Accounts button to add your Office 365 account if you have one.  Unfortunately, you have to do this in each app separately.
ExcelPreviewAddAccount
You’ll then be able to see a list of all your apps across OneDrive for Personal and Business use like you see in this example from Word Preview
WordOpenLocations
If we create a new document, we’ll see a new touch friendly Excel.  The buttons and icons are spaced a part to make them each to touch with your finger.
ExcelPreviewNewDocument
One feature I really like is the light bulb icon.  Clicking this will allow you to search for functionality that you can’t find in the ribbon.  For example, if I wanted to insert a chart, it gives me the options right there by typing the word “Chart”.
ExcelPreviewLightbulb
Excel should be able to open many of your existing spreadsheets as well.  Although, I found that Excel Preview crashes quite a bit more than the other Office Preview apps.  Some of my spreadsheets it just refused to open.  That’s to be expected though.  Excel spreadsheets can get complicated quickly and this is a preview product.
ExcelPreviewDocument
Some spreadsheets are out-right not supported.  If you are pulling data from a SharePoint list or using PowerView, it will display an error message telling you why.  I’m not surprised this doesn’t work but maybe it will some day in the future.
ExcelPreviewCantOpenFileSharePointError
For desktop users of Office 2013, the biggest change you will have to adjust to is that you can only have one file open at a time.  Now before you start bashing Universal apps on Windows 10, keep in mind that the Office apps on iOS and Android have this same restriction.
I’ve been pretty excited to see the launch of Office for Windows 10.  We’ll cover Word Preview and PowerPoint Preview in an upcoming article.  While you may not use these apps on your Surface Pro 3 in desktop mode.   I think these apps will do great when the device is running in Tablet mode.  If you have been thinking about running Windows 10 on your device

C# 6.0 Language features and its internals Part 2

As discussed in my last article on C# 6.0 features we have discussed some of the interesting features like : Auto property initialization, Expression bodied functions, Static class uses and string interpolation method. In this post, we will take the discussion ahead with more language features introduced with the new language.

The features will be covered with basic introduction to internals are :

5. Null Conditional operators
6. Exception filters
7. nameof operator
8. Dictionary initializers
9. await in try / finally.
10. Parameterless constructor for struct




Feature 5 : Null conditional operators

Getting into NullReferenceException or "Object reference not set to instance of an object" is one of the most common exception that every developer must see while working with the langauge. It has been a common problem where developers need to give extra stress to check the null value before calling any member functions. Null for compiler is unknown, and hence if you call a method on null, it will point nowhere and hence throws NullReferenceException and exists the stack.

To handle nulls Microsoft had introduced few language constructs already like Null coalesce operator (??) or Conditional operators. But with the new feature introduced in C# 6.0, the language team has introduced another operator which checks for null.

Null Conditional operator is a new construct that gives away a shortcut to condition the null check before calling its members.


string zipcode = (address == null? null : address.zipcode);

string zipcode = (person == null? null : (person.address == null ? null : person.address.zipcode))

Here in the above two lines you can see how the complexity rises when there are multiple number of null checking on an expression. In the first statement the address is checked with null and when it has address, it will only then evaluate the zipcode. On the second statement, the person object is checked with null, then its address and then finally the zipcode is evaluated.

With null conditional operator the code would look like :


string zipcode = address?.zipcode;

string zipcode = person?.address?.zipcode;

Here the code is reduced greatly even though the actual expression logic remains the same. The ? mark is used for null conditioning. Null conditional operators does not exists as well, it is the same representation as that of the previous conditional operators. If you try to look into reflector, you will see it like :


You can see the null conditional operators are replaced by the compiler with normal conditional statements.

Feature 6 : Exception Filters

Now after so many syntactic sugar introduced with latest version of C#, this is the only new feature that directly relates to IL (Intermediate Language). From the very inception, the exception filters were there in CLR but was not exposed to the C# language. With C# 6.0, the exception filters finally came into existence and finally as a C# developer you can make use of it.

In C# the exception block contains try/catch/finally with multiple catch blocks supported. Based on type of the exception that has been encountered during runtime, the runtime chooses the appropriate catch block to execute. Exception filters allows you to filter out the catch blocks to ensure which catch block can handle the exception. With exception filters in place, there could be multiple catch blocks with same type where the type determines which filter it will call first.

Let us take a look at the code :


public class ExceptionFilters
    {
        public static bool LogException(Exception ex)
        {
            //Log
            return false;
        }
        public static bool LogAgainException(Exception ex)
        {
            //Log
            return true;
        }
        public void CallMe()
        {
            try
            {
                throw new ArgumentException("Exception");
            }
            catch (Exception ex) when (LogException(ex))
            {
                //Keep exception stack intact
            }
            catch(Exception ex) when (LogAgainException(ex))
            {
                // Calling the catch
            }
            
        }
    }

Here the ArgumentException is thrown when CallMe is invoked. The Exception filters are specified using when keyword just like in VB.NET. So the execution is like, it will call LogException method, executes the code and see whether the return statement is true or false. If it is true, it executes the catch block and exit, or otherwise it move and call LogAgainException method.

The exception filter expects a boolean value, hence the call to LogException should be a method returning bool or otherwise we need a comparison operator to always evaluate the when statement to boolean. Exception filters allows the developer to run arbitary code between the exception and the catch block execution without interfering the original stack trace of the exception object.

I have already told you that exception filters is a CLR concept. The IL is laid out as :

 .try --- to --- filter --- handler --- to ---

This tells the compiler to execute try block from line no --- to line ----. It will then call filter line and then call the handler which executes some bunch of lines. Cool ? Yes.

One small addition that I would want to add, if an exception filter encounters an exception and is left unhandled, the compiler handles it for you and automatically skip the exception block and moves to the next catch block. For instance if LogException in the code above throws an exception, it will call LogAgainException without modifying the Stack for ex.

Feature 7 : nameof Operator

nameof is a new addition to operator list supported by C#. This new operator is nothing but a compiler trick, where the compiler determines the name of a Property, Function or an Extension method and writes it directly in compiled output. For instance,


string name1 = nameof(this.MyProp); // evaluates MyProp
string name2 = nameof(DateTime.Now);//evaluates Now
string name3 = nameof(Console.WriteLine); //evaluates WriteLine
string name4 = nameof(new List<string>().FirstOrDefault); // Evaluates FirstOrDefault
string name5 = nameof(name4);//Evaluates name4

The nameof operator works on any type where the type has a name. In case you specify a variable, the nameof operator will evaluate to the name of the variable.

Feature 8 : Dictionary initializers

Dictionary is one of the common array object which used often to send data between objects. Unlike arrays, Dictionaries form an array of KeyValuePair. In modern days, Dictionary is used interchangeably with arrays because of its flexibility of defining key value set.


var list = new List<string>();
list.Add("Abhishek");
list.Add("Abhijit");

//Access
var first = list[0];
var second = list[1];

Here you can see a list is used to store string data, where index giving you the reference to individual objects. If I write the same with dictionary, it will look like :


var dict = new Dictionary<int,string>();
dict.Add(0, "Abhishek");
dict.Add(1, "Abhijit");

//Access
var first = dict[0];
var second = dict[1];

Even though the basics remain the same, the developers are increasingly inclined to use the later as it gives a flexibility to assign any index. You can define "Abhishek" to 10 and "Abhijit" to 20 without the limitation of fixed incremental index usage of dictionary.

As more and more people are going to Dictionary, language team thought about giving easier constructs to define Dictionary. Even though we can go without it, but it is a nice to have feature. In C# 6.0, you can define dictionary using the following syntax : 
var dict = new Dictionary<int,string>
{
   [10] = "Abhishek",
   [20] = "Abhijit"
};

//Access
var first = dict[10];
var second = dict[20];

Or even if the key is declared as string, you can also use like:

var dict = new Dictionary<string,string>
{
   ["first"] = "Abhishek",
   ["second"] = "Abhijit"
};

//Access
var first = dict["first"];
var second = dict["second"];

This way it is very easier to declare and use dictionaries. The last two syntaxes were introduced in C# 6.0.

Now if you think of the actual implementation, there is nothing as such. If you try to sneak peek on the compiled code, you will be seeing the same code with object being initialized inside the constructor.


Here even though the new construct is used, the dictionary object is actually initialized in constructor itself. The code is re-written by the compiler.

Feature 9: Await in catch and finally

If you are not using async / await stuffs too often you might have already overlooked that you cannot specify await in catch or finally block before the latest version of C#. Microsoft has initially thought that it wont be possible to allow awaits in catch/finally because the compiler creates a state machine which slices each and every await statements into a sequence of calls which can pause and resume the function upon request. But as try/catch/finally are handled by CLR, allowing such thing will indicate every errors in the state machine is properly handled and also each of try/catch/finally would need their individual state machines each.

Based on the complexity, microsoft haven't provided the feature in previous version, but as everything is handled by the compiler itself, it is a very important feature to have as a programmers perspective hence in latest version of C# 6.0, the feature have been revised and await in catch/finally is allowed.


 public async Task<string> DownloadUrl(string url)
        {
            WebClient client = new WebClient();
            client.BaseAddress = "www.abhisheksur.com";
            try
            {
                return await client.DownloadStringTaskAsync(url);
            }
            catch
            {
                return await client.DownloadStringTaskAsync("mvp");
            }
            finally
            {
                //Await is also allowed.
            }
        }

Hence you can successfully compile the code above where the await works during the catch execution.

If you try looking at the code in reflector it will look very ugly with so many of StateMachine declarations and so many of goto statements to properly navigate to lines inside the state machine on failure. It would be nice if you can look into it personally, but if there is any problem understanding the implementation, feel free to ask me in discussions.

But as a benefit, you get this feature ready.

Feature 10: Parameterless constructor for struct

If you are unaware, there was no parameterless constructors in struct.  This is because of the fact that ValueTypes has a unique behavior where it will be automatically assigned a default memory when declared.

For instance,

int x;

Here int is a struct (System.Int32) and the value of x would be automatically 0. You can even declare array of a struct. For instance,


struct MyStruct
{
  public int Property1{get;set;}
  public string Property2 {get; set;}
}

MyStruct[] array = new MyStruct[10];

Now the Struct MyStruct will automatically get the default(MyStruct) in the array even though its not explicitly constructed. If you want to know more why struct does not support default constructor, feel free to read the article I posted

In C# 6.0 the parameterless constructor is allowed. This is also a trick made by the compiler. It actually replaces the default constructor with the parameterless constructor passed in when the new operator is used to construct the object.

So if you say,

MyStruct s = new MyStruct();

The .NET will call the parameterless constructor for you. 

Conclusion

There are lot more things coming with the new framework, new concepts, technologies etc. which I will cover one after another. Here is everything that are coming with C# 6.0 which is expected soon.

C# 6.0 Language features and its internals Part 1

C# have been one of the most evolving language in recent times. It was not more than a couple of years when some of the coolest features were introduced with C# 5.0 and today we have announced the next version of C#. In this post we will try to look deep into these features and try to see what exactly is coming in the new version. I would go deeper than just demonstrating the feature so that you are well acquainted on what exactly you would be getting from these features.

1. Auto Property Initializer
2. Expression bodied Function
3. Static Class Uses
4. String Interpolation

More in Part 2 of the post.


Feature 1 :  Auto Property Initializer

Auto properties are not new to C#. It was there since C# 3.0. The auto properties does not require a backing field to be defined which was done automatically during compilation. So as a coder, you can get a ready-made property without writing much of code. As auto properties does not have backing field exposed, you cannot initialize the backing field during object initialization, rather you have to initialize explicitly in constructors.


    public class AutoPropertyInitialier
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string FullName { get; set; }

        public AutoPropertyInitialier()
        {
            this.FirstName = "Abhishek";
            this.LastName = "Sur";

            this.FullName = this.FirstName + " " + this.LastName;
        }
    }
You can see in the above code block, the FirstName and LastName were Auto - Implemented properties, and both of them were initialized during constructor call, as the backing fields are not exposed for them. Think of a situation when your class is pretty big and you want to introduce a new property, you need to again initialize it inside constructor. This is the pain of the developer.

With C# 6.0, the initialization of auto-implemented properties is damn easy. Take a look into the code below :


    public class AutoPropertyInitializer
    {
        public string FirstName { get; set; } =  "Abhishek";
        public string LastName { get; } = "Sur";

        //public string FullName { get; } = this.FirstName + this.LastName;

        public string FullName { get; }

        public AutoPropertyInitializer()
        {
            this.FullName = this.FirstName + " " + this.LastName;
        }
    }

Here the properties FirstName and LastName were initialized directly after the declaration. You can notice the LastName were intentionally made readonly by not mentioning the setter. The backing field produced for a readonly property is also a readonly variable.

The FullName though is initialized inside constructor as the object initialization works before the constructor call, and hence initialization cannot evaluate "this".

In the above image, the C# representation of actual IL is shown which clearly indicates that the properties do have their backing fields. You can also notice the backing fields for property LastName is defined as readonly. The auto-property initialization is handled very cautiously during compilation and is abstract to you and relieves some of the pain points on writing un-necessary code. 


Feature 2 : Expression bodies functions 

Similar to Auto property initialization, C# 6.0 also comes up with expression bodies functions a long awaited feature. Expression bodied function is also a syntactic sugar implemented in the language which adds the flexibility on how you define member functions. 

Lambda expressions are not new to the language, but you might already know you cannot assign a lambda to a member function if the member function is not defined with a delegate. But if you read my internals to Lamba expression, you already know that for each lambda declaration the compiler creates a backing function body, but that function body cannot be exposed to class level. C# 6.0 enhances the language to allow you to define a member function with lanbda expressions. 



    public class ExpressionBodiedFunction
    {
       
        public string WelcomeMsg(string name) => string.Format("Welcome {0}", name);

        public string HelloMsg => "Abhishek";

        public void Print() => Console.WriteLine(this.HelloMsg);

    }
In the above code block the WelcomeMsg is a member function that takes a string argument and returns a string. As per lambda rules, a lambda which has a return statement does not require a return keyword, hence the WelcomeMsg returns the expression with string.Format.

The second property is HelloMsg which is a property like method where the getter of the property HelloMsg will return the string "Abhishek". Remember, as property is also auto-implemented, the get keyword is also automatically evaluated by the compiler.

The last method "Print" is a void method and hence require a non-returning expression. The Console.WriteLine calls the property HelloMsg to print "Abhishek".

Now how does the compiler handles the lambda now without an explicit declaration of delegates ? Well, the answer is simple. The compiler re-writes the lambda into a full functional method body.

Here the WelcomeMsg, HelloMsg and Print after compilation is just a class level methods. The compiler entirely re-written the class into a strongly typed method bodies.


Feature 3 : Static class uses

The C# language teams identified the developers pain points very well, and implemented the Static class uses in the language. If you are using Static types it is always a nice to have feature in the language such that we can omit the repetitive static method call.

For instance, say I want to print a number of lines on screen, using Console.WriteLine. How about if we don't need to mention Console each line when we call WriteLine ? Static class uses does the same thing. Static class uses also recognize extension methods, hence if say a static class defines extension methods, if you add it, it will automatically recognize the extension methods as well.


    using static System.Console;
    using static System.Linq.Enumerable;

    public class UseStatic
    {
        public void CallMe()
        {

            WriteLine("Hi");

            var range = Range(10, 10);
            var check = range.Where(e => e > 13);
            // Static extension method can 
            // only be called with fulll representation
        }
    }


In the above code the WriteLine is automatically detected as we added the head using static statement. The Range is also declared inside System.Linq.Enumerable which is automatically determined and Where is an extension function. The static uses automatically recognized the extension methods as well.

If you look at the internals of the static uses, the compiler rewrites the static type calls on every occurrences of its method call.

In the actual IL, you can see, the WriteLine is padded with its appropriate type Console and Range is also associated with Enumerable. The re-writing is done by the compiler.

Feature 4 : String Interpolation 

String interpolation is another interesting feature introduced with recent version of C# 6.0. Interpolation is not new with strings. We can do string interpolation using string.Format before, but the problem is the code looks really ugly when using interpolation constructs.

For instance,

string myString = "FullName :" + p.First + " " + p.Last;
string myString = string.Format("FullName : {0} {1}", p.First, p.Last);
Here the first instance, is normal string concatenation. This creates an issue with multiple memory allocation if not string interned. The second statement uses string.Format to format a given string and replaces the {} arguments with the proper arguments as parameter to the method. Now while dealing with multiple occurrences of these kind of string placeholders might look very ugly and unmaintainable and error prone.

C# 6.0 comes with a new technique where the string interpolation can take place in between the strings, or rather than putting numeric placeholders, you can use the actual values.


string myString = $"FullName : {p.First, 5} {p.Last, 20}";
Console.WriteLine(myString);

string my2ndString = $"FullName from EBF = {this.EBF.FullName}";
Console.WriteLine(my2ndString);

Here the string need to be started with a $ sign which indicates that the new kind of string interpolation to occur. The {p.First, 5} will be replaced with the value of p.First aligned to 5 characters.

Now what does the compiler do when these kind of interpolation is encountered. Well, you might be surprised to see, that the string is actually replaced by a call of String.Format during compilation.

So here you can see the actual statement after compilation is nothing but a string.Format call. So string interpolation is also a compiler trick. 


Conclusion

So whatever we have seen in this post are few compiler trick introduced to enhance the language C# 6.0. There are few more features introduced which I will discuss in coming article.

Play an Office 365 Video from a Universal Windows App in Windows 10

I’ve had a personal interest in figuring out how to play videos from the Office 365 Video Portal in a Univeral Windows App (UWP) in Windows 10 since Microsoft Ignite.  In reality, the process isn’t that difficult, but there wasn’t a lot of details out there on how to put the pieces together until recently.  Today, I am going to walk you through how to retrieve the first video in a channel and play it using a MediaElement
Today, I combined elements I learned from Richard DiZerga’s Universal App blog postChakkradeep Chandran’s Ignite session, as well as Andrew Connell's MVC Sample.  Special thanks to all of them for having the pieces I needed to put all of this together.  Since this is a Universal app it should work across multiple devices in theory.
This app could easily be extended to create a nice interface to browse a channel and pick a video.  If you’re familiar with data binding in WPF though that shouldn’t be hard for you, so I won’t cover that today.  We’re simply going to look at the necessary API and REST calls to get the secure playback URL.  Once we have that URL, we can have the MediaElement start playing the video.
Getting started
First, you’ll need to have installed Windows 10 as well as the final version of Visual Studio 2015.  We’re also assuming you have an Office 365 tenant, the Video Portal turned on, and you have some videos uploaded.  If you have never created a Universal Windows App before you can find it under your favorite programming language –> Windows –> Universal –> Blank App (Universal Windows).
O365VideoVisualStudioNewUniveralProject
Playing a video from the Office 365 Video Portal involves several steps.  If you know some of the values already along the way (such as the Video Portal URL), you can skip some steps.  I am going to include all of them (which means this blog post is going to be long).  The steps we need to go through are:
  1. Authenticate with Azure Active Directory / Office 365
  2. Access the Discovery Service to get the RootSite ServiceResourceId
  3. Determine the Video Portal Hub Url (i.e.: https://mytenant.sharepoint.com/hub)
  4. Get the list of channels
  5. Get the videos inside a channel
  6. Get the video playback URL
As you can see, that’s a lot of service calls.  Caching is a good thing.
Connecting to Office 365
There are no shortage of ways to authenticate with Office 365 and Azure Active Directory.  Windows 10 introduces a new way called the Web Account Provider.  This will provide us our token that we can pass to the Discovery Service as well as give us tokens to other services such as SharePoint or Outlook.  It will prompt the user to enter his or her credentials if we don’t have a token yet as well.
To connect to Office 365 bring up the context menu on the project in Solution Explorer and choose Add –> Connected Service.  Select Office 365 APIs and then click Configure.
O365VideoConnectedServiceOffice365API
The nice thing about the Connected Service dialog in Visual Studio 2015 now is that it takes care of all of the manual Azure Active Directory application setup.  You don’t need to go manually copy a ClientId, secret, permissions, or anything.  This makes the new developer experience much better.
Now, you need to specify the domain of your tenant (i.e.: mytenant.onmicrosoft.com).
O365VideoConnectedServiceDomain
Clicking Next will prompt you for authentication.  Enter your Office 365 credentials and then you can proceed to the next step.
O365VideoLogin
Now, we need to tell Visual Studio to Create a new Azure AD application to access Office 365 API services.  This will register the new application in Azure AD and then we can request permissions.
O365VideoConnectedServiceNewApplication
On the next six steps of the Wizard, we set the permissions that the app requires.  For the purpose of playing a video, we don’t need access to Calendar, Contacts, Mail, or My Files.  For Sites, we need the following permissions:
  • Read and write items and lists in all site collections
  • Read and write items in all site collections
  • Read items in all site collections
O365VideoConnectedServiceSites
For Users and Groups, select the following permissions:
  • Sign you in and read your profile
O365VideoConnectedServiceUserGroups
Finally, hit Finish and Visual Studio will add the connected service to your project.
Designing the Page Layout
Now we’ll edit MainPage.xaml and add our controls to it.  I kept this simple by just adding a Button control and a MediaElement.  You can arrange them as you like.
O365VideoMainPageXaml
Authenticating with Web Account Manager
Before we get too far, I am going to create a folder for the Models.  I am going to skip a formal Controller class today since we’re not doing any real data binding.  Normally you would have multiple controllers to pull up a list of channels, videos, etc.  We’ll use a repository class, VideoRepository, that will connect to Office 365 and retrieve our data and our models we’ll use to deserialize the jSon that comes back from the REST API. 
The VideoRepository class will also handle authentication.  We’ll add the following using statements.
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.Office365.Discovery;
using Microsoft.Office365.SharePoint.CoreServices;
using Windows.Security.Authentication.Web.Core;
using Windows.Security.Credentials;
using Newtonsoft.Json;
The first method we will create is GetAccessTokenForResource.  If you have looked at other Universal App Samples, this should look fairly similar.  The purpose of this method is to attempt to get a token silently (without prompting the user).  If it can’t, then it it will show the the Office 365 login and the user can login which will provide the token. 
public async Task<string> GetAccessTokenForResource(string resource)
{
    string token = null;

    //first try to get the token silently
    WebAccountProvider aadAccountProvider
        = awaitWebAuthenticationCoreManager.FindAccountProviderAsync("https://login.windows.net");
    WebTokenRequest webTokenRequest
        = new WebTokenRequest(aadAccountProvider, String.Empty, App.Current.Resources["ida:ClientID"].ToString(), WebTokenRequestPromptType.Default);
    webTokenRequest.Properties.Add("authority""https://login.windows.net");
    webTokenRequest.Properties.Add("resource", resource);
    WebTokenRequestResult webTokenRequestResult
        = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);
    if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
    {
        WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
        token = webTokenResponse.Token;
    }
    else if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
    {
        //get token through prompt
        webTokenRequest
            = new WebTokenRequest(aadAccountProvider, String.Empty, App.Current.Resources["ida:ClientID"].ToString(), WebTokenRequestPromptType.ForceAuthentication);
        webTokenRequest.Properties.Add("authority""https://login.windows.net");
        webTokenRequest.Properties.Add("resource", resource);
        webTokenRequestResult
            = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
        if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
        {
            WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
            token = webTokenResponse.Token;
        }
    }

    return token;
}
Let’s look at some of the highlights.  First we get our aadAccountProvider by calling WebAuthenticationCoreManager.FindAccountProviderAync().  This is the call into the Web Account Manager that I have been talking about.  You always pass it the https://login.windows.net (at least for this exercise).  We then need a WebTokenRequest.  This is where the ClientId of the application comes in.  Remember Visual Studio created this for us when it registered our app with Azure Active Directory.  Theresource property is where we pass in the Uri to the service we want to access.  On our first call this will be the Uri of the discovery service.  On subsequent calls it will be the Uri we get for accessing things in SharePoint.
Next, the method tries to silently authenticate the user.  This method would return with a Success result if the user has authenticated inside this application before. 
WebTokenRequestResult webTokenRequestResult
    = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);
If the user already has a token, then we are done.  Otherwise user interaction is required. TheRequestTokenAsync call on the WebAuthenticationCoreManager is what actually prompts the user for credentials.  Ultimately, this method returns a token for the resource you asked for.  When we run the application and click the Play button, it will prompt us for credentials.
O365VideoCredentialPrompt
After you authenticate, you will get prompted to grant permissions to the app.  These will match the ones we specified earlier when adding the Connected Service.
O365VideoCredentialPrompt
Calling the Discovery Service
We’re going to call the Discovery Service to determine the ServiceEndpointUri for the RootSite capability. We’ll do this in a new method called GetSharePointServiceEndpointUri. We do this by accessing for an access token from our GetAccessTokenForResource passing the URL https://api.office.com/discovery
string accessToken
    = await GetAccessTokenForResource("https://api.office.com/discovery/");
DiscoveryClient discoveryClient = new DiscoveryClient(() =>
{
    return accessToken;
});
After we get a DiscoveryClient, we can call DiscoverCapabilityAsync.  This method also stores the access token used for accessing resources in the variable sharePointAccessToken.  It also stores theServiceEndpointUri in the variable sharePointServiceEndpointUri.  We’ll use this URI for the subsequent REST calls.
CapabilityDiscoveryResult result = awaitdiscoveryClient.DiscoverCapabilityAsync("RootSite");
sharePointAccessToken = await GetAccessTokenForResource(result.ServiceResourceId);
sharePointServiceEndpointUri = result.ServiceEndpointUri.ToString();

return sharePointServiceEndpointUri;
Remember, the full source code is available in GitHub.
Get the Video Portal Hub URL
If you have worked with Office 365, you probably know that it’s pretty easy to guess what the URL to the Video Portal Hub will be (the hub is the root site collection of the Video Portal).  Since we want to do things right though, we’ll go through the Video Service’s Discover endpoint to determine the URL.  In fact, once we construct these next two methods, the rest will be very similar.
We’ll create a new method called GetVideoPortalHubUrl.  The first thing we’ll do is callGetSharePointServiceEndpointUri to authenticate and return us the endpoint for working with SharePoint.  We append VideoService.Discover to the Uri returned by our method.  How did we know this was the URL, it’s in the Video REST API reference (still in preview).
var requestUrl = String.Format("{0}/VideoService.Discover"awaitGetSharePointServiceEndpointUri());
We then, create a function that returns an HttpRequestMessage using the requestUrl.
Func<HttpRequestMessage> requestCreator = () =>
{
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
    request.Headers.Add("Accept""application/json;odata=verbose");
    return request;
};
Then, we create a new httpClient and pass it, our access token, the HttpClient, and the RequestMessage to a custom method we will build named SendRequestAsync.   This piece is based upon other’s code so I didn’t really tweak it since it works.  After our call to that method, we’ll deserialize the jSon that comes back.  I borrowed several of AC’s helper classes from his MVP example here.
Let’s take a look at SendRequestAsync.  We’ll start with a using blog to get our HttpRequestMessage
using (var request = requestCreator.Invoke())
We’ll then need to add the necessary headers.  First, we add an AuthenticationHeaderValue with thesharePointAccessToken we got earlier.  We also add another header, X-ClientService-ClientTag.  I don’t know if this is required but Chaks included it in his examples.  I updated the version to match the current version reported in the Connected Service wizard.
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Headers.Add("X-ClientService-ClientTag""Office 365 API Tools 1.5");
Then we invoke the request using httpClient.
var response = await httpClient.SendAsync(request);
The method then returns the response assuming it’s successful.  The example that Chaks provided will actually make a second attempt to call the service if the user isn’t authorized.  You can optionally include that if you like.
Now going back to our GetVideoHubUrl method after we successfully got a response back.  We now need to parse the JSON that came back into a usable object.  This is where Newtonsoft.Json comes in.  We use the models that AC provided in the MVC project. In this case we serialize the responseString into an object of VideoServiceDiscovery.  Now, we can get the VideoPortalUrl for our subsequent REST calls.
string responseString = await response.Content.ReadAsStringAsync();
var jsonResponse = JsonConvert.DeserializeObject<VideoServiceDiscovery>(responseString);
videoPortalUrl = jsonResponse.Data.VideoPortalUrl;
Get the video portal channels
Now that we have our Video Portal Hub URL, we can retrieve the list of channels.  The Video REST API Reference tells us we need to append /_api/VideoService/Channels to the Video Portal Hub URL which we just retrieved.  We’ll create a new method called GetVideoChannels which will look similar toGetVideoPortalHubUrl expect the requestUrl used and the JSON serialization.
var requestUrl = string.Format("{0}/_api/VideoService/Channels", videoPortalUrl);
Since we return multiple channels, we loop through the results and add new VideoChannel objects to the list. 
string responseString = await response.Content.ReadAsStringAsync();
var jsonResponse = JsonConvert.DeserializeObject<VideoChannelCollection>(responseString);

var channels = new List<VideoChannel>();

foreach (var videoChannel in jsonResponse.Data.Results)
{
    var channel = new VideoChannel
    {
        Id = videoChannel.Id,
        HtmlColor = videoChannel.TileHtmlColor,
        Title = videoChannel.Title,
        Description = videoChannel.Description,
        ServerRelativeUrl = videoChannel.ServerRelativeUrl
    };
    channels.Add(channel);
}
At this point, you have enough data you can start doing some data binding.  As I mentioned earlier, I am skipping that since data binding in a Universal Windows App for Windows 10 is quite similar to what was there in Windows 8.1  For our example, I am simply going to pass the Channel Id into our next method to retrieve a list of videos.
Getting the list of videos in a channel
Now that we have a list of Channels, we can make another Video REST API call to get a list of videos in our new method GetVideos.  We build our requestUrl by appending/_api/VideoService/Channels(‘<channelid>’)/Videos.  Remember we got the Channel Id from our last API call.  Now this simply returns the metadata about the video.  After this, we still have one more call to get the Playback URL.
var requestUrl = string.Format("{0}/_api/VideoService/Channels('{1}')/Videos", videoPortalHubUrl, channelId);
The rest of the method is similar to GetVideoChannels
Get the video playback URL
For the purpose of our example, we’re also going to simply play the first Video in the Channel.  To get the Playback URL, we’ll need the Video Id as well as the Channel Id we retrieved earlier.  When it comes to streaming, we have a choice of either Smooth Streaming or HLS Streaming by specifying thestreamingFormatType parameter on the Video REST API call.  HLS streaming requires one fewer API call so we are going to use that for the example today.  You may want to use Smooth Streaming for your application.  To use HLS Streaming, specify a value of 0.
var requestUrl = string.Format("{0}/_api/VideoService/Channels('{1}')/Videos('{2}')/GetPlaybackUrl('{3}')",
    new string[] { videoPortalHubUrl, channelId, videoId, streamingFormatType.ToString() });
The REST call will return a playback URL which we can then assign to the MediaElement
Playing the video
On the click handler of the Play button we added in the beginning, we make our calls into theVideoRepository class.  Once we get the Playback URL we binding it to the MediaElement and the video will start playing.  I also set a few parameters to turn on the transport controls and enable full screen mode.  You can set those as you like.
private async void button_Click(object sender, RoutedEventArgs e)
{
    VideoRepository videoRepository = new VideoRepository();
    string videoPortalUrl = await videoRepository.GetVideoPortalHubUrl();
    var videoChannels = await videoRepository.GetVideoChannels();
    string channelId = videoChannels[0].Id;
    var videos = await videoRepository.GetVideos(channelId);
    string videoId = videos[0].VideoId;
    var videoPlayback = await videoRepository.GetVideoPlayback(channelId, videoId, 0);

    mediaElement.Volume = 0;
    mediaElement.AreTransportControlsEnabled = true;
    mediaElement.IsFullWindow = true;
    mediaElement.Source = new Uri(videoPlayback.Value);
}
There you have it a (somewhat) quick and dirty way to play a video from the Office 365 Video Portal in Windows 10.  This should work on Windows 10 Mobile as well.  Here is what our app looks like when playing a video.
O365VideoAppPlayback
Source Code
As promised the source code is available on GitHub.  I may extend it in the future to include all of the data binding and improve the look.  Feel free to contribute to the repo as well.  If you make use of any of the code, you’ll want to add error handling of course.
Feel free to ask me any questions by leaving a comment.