Tuesday, June 21, 2016

Microsoft Graph - Easy to switch

The purpose of this article is to learn how much it is easy to switch your application from using multiple Offie 365 service end points to one end point - graph.microsoft.com. This will make easy to switch the context of applications using same end point and without requiring authentication token against each end points.

It's been a while since Microsoft started to focus on Office 365 development platform.
Office 365 has a mix of products like Exchange, SharePoint. Microsoft has been adding many new products in Office 365 suite recently.

When Initially development started, each product has its' own development APIs. Like 
· For Exchange, use EWS or REST APIs.
· For SharePoint, either uses client side object model or REST APIs.
· For Lync becoming Skype, some of the Skype APIs were available.

Now, consider a real-time customer scenario where you have to access email, calendar, tasks and OD4B service from one application and in a sequence. 
In this case, the programmer has to write multiple sets of APIs across different platforms. Moreover, each time the platform changes, the programmer has to handle authentication token against end point.
To solve this challenge, Microsoft introduced Unified APIs in the preview. This was released around Mid-2015. The intention was to build a unified model to query across products from one end point. Since this was in preview, not ready for production use, a lot of developers did not build the application using this.
A lot of developers have built the application using the previously recommended and supported model. Now it is a good time to switch the code to Microsoft Graph API.
Let's get started in action.
When you configure the project with Office 365 API, either the native or web application gets registered with Azure AD. This registration will add details like client id, client secret, tenant id, the domain in the configuration file of the application.
I am considering ASP.NET app here. It can be MVC or web forms. 
1. First thing, you already have registered your app with Azure AD and set the applications permissions.
2. You should change the property SSL Enabled to TRUE if this is not done.
3. Now let's add Microsoft Graph permissions on the app.
a. Go to Azure Management Portal and sign in using the organizational account. ( I generally do sign in using global admin user account).
b. In the left-hand navigation, click Active Directory.
c. Select the directory you share with your Office 365 subscription.
d. Locate and select the Application tab on the header/options bar.
e. Select the application you created for this lab.
f. Open Configure tab
g. Scroll down to the permissions to other applications section.
h. Click the Add Application button.
i. In the Permissions to other applications dialog, click the PLUS icon next to the Microsoft Graph option.
j. Click the CHECK icon in the lower right corner.
k. For the new Microsoft Graph application permission entry, select the Delegated Permissions drop-down on the same line and then select the permissions required for your application. (screenshot is for reference only, permissions should be selected based on the required scope)
l. Click the Save button at the bottom of the page.

4. Now in your Visual Studio solution, add a help class which will help to build the strings from configuration file quickly. Example - 
public class SettingsHelper
   {
       public static string ClientId
       {
           get { return ConfigurationManager.AppSettings["ida:ClientId"]; }
       }
 
       public static string ClientSecret
       {
           get { return ConfigurationManager.AppSettings["ida:ClientSecret"]; }
       }
       public static string AzureAdInstance
       {
           get { return ConfigurationManager.AppSettings["ida:AADInstance"]; }
       }
 
       public static string AzureAdTenantId
       {
           get { return ConfigurationManager.AppSettings["ida:TenantId"]; }
       }
 
       public static string GraphResourceUrl
       {
           get { return "https://graph.microsoft.com/v1.0/"; }
       }
 
       public static string AzureAdGraphResourceURL
       {
           get { return "https://graph.microsoft.com/"; }
       }
 
       public static string AzureAdAuthority
       {
           get { return AzureAdInstance + AzureAdTenantId; }
       }
 
       public static string ClaimTypeObjectIdentifier
       {
           get { return "http://schemas.microsoft.com/identity/claims/objectidentifier"; }
       }
   }
 
5. Now, let's add a function call to get the access token for logged in user for Graph API authentication
 
public async Task<string> GetGraphAccessTokenAsync()
{
   var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
   var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;
 
   var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
   var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
 
   // create auth context
   AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureAdAuthority, new ADALTokenCache(signInUserId));
   var result = await authContext.AcquireTokenSilentAsync(SettingsHelper.AzureAdGraphResourceURL, clientCredential, userIdentifier);
 
   return result.AccessToken;
}
6. Based on your application type (MVC/Webforms), add the CRUD functions in your form/controller class.
7. In my ASP.NET forms application, I have added the function call as in Page Load 
RegisterAsyncTask(new PageAsyncTask(GetUserFiles));
And definition was
public async Task GetUserFiles(){}
9. Implementation  for reading the files from OneDrive for business as 
var accessToken = await GetGraphAccessTokenAsync();
           var restURL = string.Format("{0}me/drive/root/children", SettingsHelper.GraphResourceUrl);
 
           try
           {
               using (HttpClient client = new HttpClient())
               {
                   var accept = "application/json";
 
                   client.DefaultRequestHeaders.Add("Accept", accept);
                   client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 
                   using (var response = await client.GetAsync(restURL))
                   {
                       if (response.IsSuccessStatusCode)
                       {
                           var jsonresult = JObject.Parse(await response.Content.ReadAsStringAsync());
 
                           string filesInfo = string.Empty;
                           foreach (var item in jsonresult["value"])
                           {                                
filesInfo = filesInfo +  item?["name"]?.ToString() + Environment.NewLine ;
                           }
                           txtOutput.Text = filesInfo;
                           //lblGraphSuccess.Text = "Successfully request using graph";
                       }
                   }
               }
           }
           catch (Exception el)
           {
               //Handle Exception your style
           }
10. Same way you can apply other APIs and build update/delete methods.

This will help you to get started changing your code from individual end points to one unified end point.
Feel free to post comments if you have any question.
For details on implementation differences, you can look at below articles and git repos

Sunday, November 29, 2015

A day in developer's life

I got an opportunity to present in Microsoft Australia Ignite 2015 conference. I love writing the program as being developer by passion.
I thought to utilize this opportunity and focus on the new development changes which can help developers, interns help customer to quickly deliver the solution for business problems.
I would like to take a different step and want to message out that with new tools and solution style, we can also go and build SharePoint environments also easily.

You can find the recording and presentation at this channel9 link.

My talk is also being referred by Official SharePoint twitter account. You can find the reference at this link.


and they did it again, find link here

Looking forward to your comments and let me know if you would like to know more about specific area.

Thank you.

Thursday, September 17, 2015

Collab365 - Global Conference

Recently, I have been engaged in doing presentation in community.

In continuation, I have been selected as speaker at Collab365 - Global Conference. You can find more information on their home page.

Sharing few quick links and details below -

When it's happening - 7 & 8 Oct 2015.
Where it is? - At your desk. It is virtual, you can join from anywhere with good internet speed to catch live sessions.

Speakers - A big line of speakers including MVPs and other leaders in the technology across the world. Speaker list is available here.

Agenda - https://collab365.conferencehosts.com/sitepages/agenda.aspx

My session is about how we can bring more productivity to end user still doing the custom development. We may need to look at the different options available in Office 365 Dev and Office Dev along with SharePoint Dev.

Session details - https://collab365.conferencehosts.com/SitePages/sessionDetails.aspx?sessionid=C365060

Register now, before it is too late.

Monday, May 11, 2015

SharePoint 2016 – What is in it?


Note: the information in this blog post is based on the information presented and available on public forums. The actual product SharePoint 2016 can have difference from what is available. Please do take time to check the new features when the product is released.
The same article with updated by other community member is also available at Technet Wiki.

Past few weeks been really busy, catching up Build and Ignite conferences (virtually through channel 9). One of the session which I have been waiting was What’s new in SharePoint 2016.

After the session, I thought to pin down my thought which might be helpful for quick summary to look out for what to expect in SharePoint 2016 (release is still a year later, a lot can change).

I would love to make points which makes it easier to read rather than reading the entire paragraph.
·       Release milestones: Public beta – Q4 2015, public download – Q2 2016 and a release candidate (RC) in between.
·       The design, development and maintenance for SharePoint 2016 going to inherit from cloud DNA.
·       Focusing on content management, team collaboration, user experience across devices and how the cloud can be blended into existing on-premises scenario.
·       New and improved capabilities will be delivered focusing on
o   Improved User Experience
§  Improved mobile experience
§  Personalized insights
§  People-centric File storage and collaboration
§  Power of Office graph and Delve (via hybrid)
o   Cloud-inspired infrastructure
§  Improved performance and reliability
§  Hybrid cloud with global reach
§  Support and monitoring tools
§  Simplified user experience and integration with products like next version of Win Server, SQL Server, Exchange Server 2016.
o   Compliance and Reporting
§  New DLP
§  Enable data encryption
§  Improved Analytics and reporting
·       Microsoft taken SharePoint online, modified to suite on-premises. Components which were not available are back ported.

New information available for SharePoint 2016 can be classified in 4 categories –
1.       Management of platform
·       System requirements
o Hardware Requirements
Installation Scenario
Memory / RAM
Processor
Hard Disk
Single Server*
16-24 GB
64-bit, 4 cores
80 GB
Farm Server
12-16 GB
64-bit, 4 cores
80 GB
Database Server
Refer system requirement for 64-bit version of SQL Server 2014 Service Pack 1 or SQL vNext
*There is no built in SQL Server. You need to install a separate SQL Express/Developer or any other edition even for development server.
o Software Requirements
§  Any one of Windows Server 2012 R2 | Windows Server 10
§  Windows Management Framework 3.0
§  Application Server Role
§  Web Server (IIS) Role
§  Microsoft .NET Framework 4.5.2 (in on Windows Server 10, then Microsoft .NET Framework 4.5.6)
§  Update for the .NET Framework 4 (KB2898850)
§  Microsoft SQL Server 2012 Native Client
§  Microsoft Identity Extensions
§  Microsoft Sync Framework Runtime v1.0 SP1 (x64)
§  Windows Server AppFabric v1.1 (MS is planning to end AppFabric, but it will be supported for SP 2013 and 2016).
§  Windows Identity Foundation v1.1
§  Microsoft Information Protection and Control Client
§  Microsoft WCF Data Services.
·       Upgrade and Migration
o Upgrade path is from 2013 to 2016
§  Upgrade 14.5 mode site to 15 mode and then upgrade
§  Allow the same database attach upgrade process
o Migrate Content to 2016 (using migration APIs or partner tools)
·       Auth N-Z
o Windows Identity over SAML claims
o Trying to normalize on oAuth/OpenID standards
·       SMTP Connection
o Allow using non-default ports
o Allowing to use STARTTLS connection encryption.
2.       Reliability, Performance and scalability
·       Moving from SharePoint 2013 based job enable / disable to predefined set of logic executing on a machine (Termed as MinRole Topology)
·       New Server Roles in SharePoint 2016
o Special Load – custom service applications, services, third party components which are outside of MinRole Topology
o Web Front End – services end user requests. Servers are optimized for low latency
o Search – service application provisioning, indexing service and other search components.
o Application – services backend jobs or requests triggered by backend jobs. Servers are optmized for high throughput
o Distributed Cache – servers distributed cache for the farm.
o Single Server Farm – for development purpose, configure (excluding SQL Server) all services on one server.
·       New Service categories in SharePoint 2016
o User Services
o Robot Services
o Caching Services
·       Server Role and Health Analyzer
·       Patching Updates
·       Improvement in boundaries and limits
o Content DB size up to TB’s (not yet identified the limit)
o 100K sites per site collection
o List view threshold > 5000 items
o Upload file size up to 10 GB and removed character restrictions
o Search scaling up to 500 M items.
·       Better File Performance
o Use BITS (Background Intelligent Transfer Service) to better file performance
·       Fast Site Creation
o Create faster site collections at database level using the standard site template saved as site.
o Remove feature activation overhead
·       User Profile Service
o Bi-directional sync using external FIM service. No built in FIM anymore.
·       Project Server
o Still require separate Project Server Licensing, but SharePoint and Project Server content database is merged.
·       Durable Links
o New sharing URLs are resources Id based, thus renaming file, moving file will not break the link already shared.
3.       Analytics (Insights and Data)
·       Real time data analysis on various parameters
o Usage
§  daily active users
§  Weekly active users
§  Usage by browser
§  Usage by agent
§  Usage by OS
o Storage
§  Storage by site template
§  Daily storage
§  File type
§  Storage breakout
o Health Reports
o Network
o Portals
4.       Cloud Experience
·       Compliance Center
o This showcase the feasibility of bringing same compliance system to on-premises which works well in O365 with Azure RMS.
o Discover and preserve with hybrid eDiscovery.
·       Cloud Search Service Application
o This unifies the on-premises and cloud data search from one search center.
o This also add value to Office Graph / Delve to extend the presence on on-premises.
o This can also leave search running in cloud only while indexing from on-premises and online.
·       Extranet
o Making easier to maintain and publish sites to Internet.
o Using O365 Identity federation services.
·       Team Sites
o Separate the data in either on-premises or in cloud
o Follow sites, documents or people in on-premises and master the information in cloud.
o Allowing ODF files creation.
·       Scenario Picker
o Hybrid deployment automation
o Select the Hybrid configuration required and use automated and wizard driven information to setup Hybdrid (forget the lengthy procedures and PowerShell scripts to run)

Thursday, February 5, 2015

Error 0x80071A90

I have been working on my laptop for setting up my development environment and update Win 8.1 Pro. I keep getting the error 0x80071A90 while doing the windows update or trying to add windows features like Hyper-V or IIS.
I searched entire MS KB base, but could not find any solid base for the error. Then I get a reference that there could be an anti-virus program which is causing problem on disk for real time scan.
I switched off the anti-virus program and everything worked well. I was able to install the updates, enable windows features like Hyper-V or IIS without much problem.

I hope this can help someone.

Wednesday, December 3, 2014

SharePoint File and Folder Name validation


Here is a quick sample on how you can validate a file or folder name before creating/uploading it in SharePoint.
Scenario in which I used this code block when I am creating a folder hierarchy in SharePoint site (on-premises or online) based on a database query and migrating files.
Based on the KB 905231, there are following characters are not allowed in the file/folder name for SharePoint.
  • Tilde (~)
  • Number sign (#)
  • Percent (%)
  • Ampersand (&)
  • Asterisk (*)
  • Braces ({ })
  • Backslash (\)
  • Colon (:)
  • Angle brackets (< >)
  • Question mark (?)
  • Slash (/)
  • Plus sign (+)
  • Pipe (|)
  • Quotation mark (")
Along with those, you have to check below conditions also:
  • You cannot use the period character consecutively in the middle of a file name.
  • You cannot use the period character at the end of a file name.
  • You cannot start a file name by using the period character.
  • If you use an underscore character (_) at the beginning of a file name, the file will be a hidden file.
Extra conditions:
In addition, file names and folder names may not end with any of the following strings:
  • .files
  • _files
  • -Dateien
  • _fichiers
  • _bestanden
  • _file
  • _archivos
  • -filer
  • _tiedostot
  • _pliki
  • _soubory
  • _elemei
  • _ficheiros
  • _arquivos
  • _dosyalar
  • _datoteke
  • _fitxers
  • _failid
  • _fails
  • _bylos
  • _fajlovi
  • _fitxategiak
In My code block, I am not considering the extra conditions.
You can pass the required file/folder name which need to be validated to the function, and function will let you know if that is a valid name.

public static bool NameValidate(string strName)
{
bool isValidFileName = true;
var match = (new Regex("[ ~ # % & * { } : < > ? / + | \" \\\\ ]|\\.\\.|^\\.|^[_]|\\.$")).IsMatch(strName);
if (match)
{
//Invalid file name.
isValidFileName = false;
}
else
{
    //Valid file name.
}
return isValidFileName;
}

Else you can also use below options if you have to replace each occurrence of characters and fix the name –
char[] filenameChars = fileORFolderName.ToCharArray();
     foreach (char c in filenameChars)
     {
         if (!SPEncode.IsLegalCharInUrl(c))
fileORFolderName = fileORFolderName.Replace(c.ToString(), "");
     }

 In above the reg ex can be broken as:
[ ~ # % & * { } : < > ? / + | \" \\\\ ]Any one of the chars anywhere in the name (last \\\\ represent one backslash \)
\\.\\.. .( double Dot) consecutive dot occurring in the name
^\\.. (Dot) at the start of name
^[_]_(underscore) in the beginning of name
\\.$. (Dot) at the end of name




Feel free to share your comments.

Saturday, April 28, 2012

FAST Search 2010 on Taxonomy

Recently during my work, I got to build the query string for FAST Search 2010 for SP 2010. The refiner was the managed metadata column.
When we compare the enterprise search  result query string and FAST search query string, we see that FAST search has alphanumeric string after the "r" parameter.
Enterprise search has string as : r=%22owstaxIdColName%22%3D%230b37b7b2%2D0079%2D402b%2D8342%2D3aac932037ec%3A%22EMEA%22, which is : r="owstaxIdColName"=#0b37b7b2-0079-402b-8342-3aac932037ec:"EMEA".
While when same query string come as : r=%22owstaxIdColName%22%3D
AQRFTUVBCG93c3RheGlkABgDXiJvd3N0YXhpZFRlc3RUYWcjMGIzN2I3YjItMDA3OS00MDJiLTgzNDItM2FhYzkzMjAzN2VjIiQ%3D in FAST Search 2010 for SP.
Now challenge is how to build the query string in FSAT search. For this I referred the referenced articles and got a lot of ideas from Mikael.
I downloaded the attached refinementtokenencoder.cs. In the code, there is a refinement class.When you pass the existing alphanumeric string, you will get the components in the string as.
refinement.ManagedPropertyName.
refinement.RefinementName.
refinement.RefinementValue.
Since you know what was selected refiner, and you got the components of string. Now you pass your own components and use RefinementTokenEncoder.GenerateToken(refinement) to get the base64 string for FAST Search 2010.
I have tried this and worked perfectly for one refinement.it is easier than writting long FQL query and customizing core search web part to enable FQL for managed metadata column.

This can help when we have associated taxonomy with documents and just want to filter the documents associated with taxonomy. No need to enter any search keyword also.

I will put next blog on multiple refinement.

Reference:
http://msdn.microsoft.com/en-us/library/ff625182.aspx
http://techmikael.blogspot.in/2011/08/creating-refinement-query-parameter-for.html