Programar para SharePoint hoy (I): el legado

En esta serie de posts intentaré hacer un resumen de las posibles opciones que tiene un desarrollador (o desarrolladora) para programar una aplicación que tenga que comunicarse de algún modo con SharePoint, en cualquiera de sus variantes.

<ModoAbueloCebolleta>
En los tiempos en los que los dinosaurios vagaban por la Tierra, el ser humano vivía en cuevas y SharePoint era novedad todavía, para programar tenías dos opciones. Cada nueva versión de SharePoint traía algún modo nuevo, así que hoy en día tenemos bastante elección y a veces se hace difícil saber que enfoque es el mejor para una situación dada. Por favor…que viejo me siento contando batallas. ¡Que alguien me sacrifiqueeeee!
</ModoAbueloCebolleta>

El legado

Desde que SharePoint corre sobre .NET Framework (es decir desde su versión 2003), hay dos métodos de desarrollo que están todavía presentes sin muchos cambios. Son el “full-trust code” (FTC) y los servicios web SOAP (o ASMX).

Legacy rusty chain and padlock

Full-Trust Code o SSOM (Server-Side Object Model)

Full-Trust Code o SSOM es el modelo de programación de SharePoint donde nuestro código se ejecuta dentro de los procesos de SharePoint (IIS y/o servicios Windows), como una parte adicional al propio código de Microsoft, para lo bueno (la velocidad) y lo malo (hundir el rendimiento de SharePoint mismo).

Este es el modelo “clásico” de los programadores SharePoint “de los de antes”. Si eres uno de ellos, tengo una mala noticia y otra buena.

La mala es que este modelo es cada vez menos relevante en los desarrollos de SharePoint. Así que si tu idea de especialización era focalizarte en código de SharePoint y te memorizabas las listas de los objetos que empiezan por SP*, tendrás que reciclarte, ¡y pronto!

La noticia buena es que FTC no desaparecerá. Siempre habrá alguna funcionalidad que es necesaria para los desarrollos de SharePoint on-premises, y no habrá otra solución tan elegante y eficiente que el código de SharePoint en el mismo servidor de SharePoint. Vaya..que saber SSOM será el equivalente de programadores COBOL en el siglo XXI.

Las limitaciones serias de este modelo son tener que desplegar en los servidores de SharePoint (y dar ataques al corazón a los administradores de sistemas cuando les explicas que necesitas un Visual Studio en el servidor), usar autenticación implícita (tu código se ejecutará con los permisos del usuario actual) y que no es compatible de ninguna manera con SharePoint Online de Office 365.

Los servicios web SOAP

Evidentemente, alguien siempre ha tenido la necesidad de integrar SharePoint con otros sistemas (¿qué otros sistemas hay? diría algún SharePointero “de los de antes”). En los tiempos en los que nació SharePoint, eso significaba usar el lenguaje universal de la web: los servicios web SOAP (o ASMX, por la extensión del fichero ASP.NET en los que se programan).

SharePoint incluye una capa de servicios web SOAP, accesibles a cualquier plataforma que sepa hacer una llamada SOAP (y que pueda autenticar el usuario correctamente, claro está). Las operaciones que expone son bastante de bajo nivel, y con muchos parámetros obligatorios, y para muestra sólo hay que mirar la documentación de los estándares. Hablando en claro, son prehistóricas.

Hoy en día han quedado bastante en desuso ya que el modelo de REST API los hace casi obsoletos. Sin embargo, es posible que todavía haya cosas que se pueden hacer con los servicios web y con la API REST no, así que es posible (pero no probable) que tengas que recurrir a ellos.

En el siguiente post expondré las opciones modernas de desarrollo con SharePoint.

SharePoint Saturday Barcelona 2016

Después de organizar el primer SharePoint Saturday Barcelona el año pasado, y colaborar en la organización del SharePoint Saturday Madrid este año, los miembros de SUG.CAT volvemos a la carga con el segundo SharePoint Saturday en Barcelona. Se ve que esto de masoquismo organización de eventos nos va.

SPSBCN logo

Este año el SPS Barcelona se hará el sábado día 1 de octubre y volvemos a contar con Institut Químic de Sarrià para el espacio del evento.

¿Qué es un SharePoint Saturday?

Los SharePoint Saturday (o SPS) son eventos tipo conferencia, gratuitos y celebrados siempre en un sábado. Suelen tener varios “tracks” en paralelo y ponentes de gran nivel, con preferencia para los ponentes locales y personas destacadas en la comunidad que lo organiza.

SPSBCN 2015

¿Os he dicho que es totalmente gratuito? Hay conferencias de SharePoint con una agenda como la de SharePoint Saturday y que cobran entradas de 200-300 €.

¿Por qué debería asistir?

Depende de tu rol.

Si eres un técnico, administrador o desarrollador de SharePoint/Office 365 lo deberías tener claro: para aprender de otros compañeros, compartir historias e ideas y socializar.

Si eres un jefe de proyecto o de unidad de SharePoint, puedes ver lo que se ha hecho en otros sitios y coger ideas.

Si eres un usuario de SharePoint, principiante o avanzado, seguro que habrá sesiones en las que aprenderás que más se puede hacer. También tendrás un sitio donde preguntar tus dudas y aprender.

Si estás buscando gente de SharePoint/Office 365 para tu empresa o tu cliente, estás de suerte: todos los que te interesa van a estar allí.

¡No te lo pienses tanto y apúntate ya! Te esperamos el día 1 de octubre.

¿Qué hemos aprendido del año pasado?

La ventaja de haber pasado por el primer SharePoint Saturday el año pasado es que ya tenemos experiencia y sabemos que esperar. Este año hemos hecho una serie de mejoras:

  • Evitar que coincida con un partido del Barça o con un megapuente de vacaciones
  • Mejorar la logística para los sponsors
  • Reservar un espacio en la agenda para invitar a ponentes que no se suelen ver en eventos, para mejorar la representatividad y diversidad

Eso sí, seguro que este año volveremos a hacer algunas cosas mal (sin intención, claro), para mejorarlas el año que viene.

Más detalles sobre el evento

Speaking at SharePoint Konferenz Erding 2016

Last week I was in Germany, in the little village of Erding (near Munich), delivering two sessions at SharePoint Konferenz 2016. It was a very good event with fantastic speaker lineup and nice environment.

SPKonferenz banner

My two sessions were Extending Authentication and Authorization and High-Trust SharePoint Add-Ins for On-Premises Development.

SPKonferenz Keynote
SPKonferenz Keynote Speakers

Extending Authentication and Authorization

In this talk I focused on explaining the architecture of claims identity in SharePoint. From there I went to explain how to extend the claims with custom claim providers, together with the explanation on how to use other identity providers such as ADFS or Thinktecture Identity Server with SharePoint. I had a fairly good Q&A session after my talk.

You can find the sample claim provider code at http://bcned.in/ClaimProvider.

High-Trust SharePoint Add-Ins for On-Premises Development

My second session was focused on how to build on-premises apps/add-ins (high-trust or S2S) using certificate authentication instead of OAuth-brokered authentication. I highlighted some of the challenges and also some of the extensibility points that we don’t have in low-trust apps. Again, I had nice Q&A time after my talk.

Talking about Claims and Claim Providers at ESPC15 in Stockholm

Last week I was in Stockholm for the annual European SharePoint Conference 2015. A little bit tired after being in USA for MVP Summit the previous week, but happy to meet my dear SharePointers and get to know some new ones.

Me at ESPC15
Me at ESPC15

My talk was about “Extending Authentication and Authorization”. I talked about claims, the underpinning of all thinks AuthN and AuthZ in SharePoint 2013. My demo was a custom claims provider that exposed dummy claims in People Picker that were used to protect confidential document from normal users.

I also demoed the federated authentication with SharePoint and ADFS.

My Session announced at ESPC15
My Session announced at ESPC15

You can find my slides on the ESPC15 website or on SlideShare. The demo claims provider code is also available on my OneDrive.

Special thanks to Spencer Harbar for coming with the claims as boarding pass analogy in the first place. It’s a great explanation tool.

Organizando el primer SharePoint Saturday Barcelona

SPSaturday_square

En los últimos meses desde SUG.CAT estamos inmersos en la organización del primer evento en el formato de SharePoint Saturday.

Desde hace ya un tiempo andamos comentando internamente que sería un reto importante poder organizar un evento de estas características en Barcelona (y en España), pero que a la vez comparándonos con el resto de los grupos de usuarios de Europa vemos que podemos hacerlo. Por eso nos líamos la manta a la cabeza y empezamos a movernos para convertirlo en realidad.

¿SharePoint Saturday, mandeeee, lo cualooo?

Los SharePoint Saturday (o SPS) son eventos tipo conferencia, gratuitos y celebrados siempre en un sábado. Suelen tener varios “tracks” en paralelo y ponentes de gran nivel, con preferencia para los ponentes locales y personas destacadas en la comunidad que lo organiza.

Nuestro SharePoint Saturday inaugural se hará el sábado 26 de septiembre de 2015 en las instalaciones del Institut Químic de Sarrià (IQS). Nos haría ilusión llenarlo con 200 personas del mundillo SharePoint, entre desarrolladores, usuarios, administradores, jefes de proyecto y demás perfiles que directa o indirectamente estén relacionados o bien con SharePoint o bien con Office 365 y Azure.

¿Qué necesitamos ahora?

Necesitamos apoyo en tres frentes:

Patrocinadores

Tenemos abierto el call for sponsors para que las empresas que estén interesadas en tener presencia en el evento puedan patrocinarlo. Los niveles de patrocionio son 3: Gold, Silver y Bronze. Además, existe la opción de patrocinio Raffle, es decir de aportar un regalo que se sorteará entre los asistentes.

Si tu empresa podría estar interesada, ponte en contacto con nosotros en Twitter o en la web, por favor.

Ponentes

También tenemos el call for speakers donde los ponentes potenciales pueden proponer sus charlas. Las charlas serán preferentemente en inglés (para que los visitantes del resto de Europa puedan acudir también), pero si no te manejas bien en ese idioma no te preocupes, tenemos un lugar para tí también.

Publicidad

Sobre todo lo que necesitamos es que todo el mundo que tenga interés en SharePoint u Office 365 sepa que el día 26 de septiembre tiene una cita. Si tenéis amigos o compañeros de trabajo a los que les pueda interesar, haced correr la voz para que podamos llegar a esas 200 personas de asistencia que nos marcamos como reto.

Más detalles sobre el evento

SharePoint App Catalog And Missing Apps

Another weird SharePoint app bug happened yesterday. The solution was fairly easy once you know what’s going on, but it’s just weird altogether.

SYMPTOMS

You have a custom app in your SharePoint 2013 App Catalog.

A custom app inside app catalog under Apps for SharePoint
A Custom App Inside App Catalog

You want to add this app to a SharePoint site.  You can’t find your app in the “From Your Organization” section when you click at “Add an app” in a site.

The App Is Missing From "Your Apps"
The App Is Missing From “Your Apps”

CAUSE

I first suspected that the current user doesn’t have permissions to add an app. However, the user is the site collection administration and thus has the permission to install an app.

Yet…a slight detail. The App Catalog site is, well, a SharePoint site. With its own permissions. And, by default, containing only the user who created the catalog in the first place (the system admin).

So, the current user, although a site collection admin, doesn’t have permissions to read from the app catalog. (This is the weird part, as I expected SharePoint to do the reading using a system account behind the scenes.)

SOLUTION

Add the users that should be able to install your custom apps to the site permissions of the App Catalog site, with Read permission level. In my case it was “Dani Alves” (yes, I’m a Barcelona fan).

Adding Read Permissions to the App Catalog

Now, the app is visible in “Your Apps” when you try to add it to a site. Yeah!Custom App Is Now Visible

What I Learned at SharePoint Saturday Stockholm

As I mentioned in my previous post, last weekend was well spent with the SharePoint Saturday crowd in Stockholm, Sweden. In this post I want to highlight what I have learned from it. It was very difficult to choose which session to attend , as I had my own session to worry about.

What I learned at SharePoint Saturday Stockholm 2015

JavaScript

There were two very good sessions about JavaScript in SharePoint.

The first one was called “SharePoint JavaScript, Doing It Right” and it was presented by Hugh Wood, very knowledgeable guy from Rencore (by the way, they are the makers of SPCAF, pay them a visit). He summarized his detailed posts on SharePoint JS inner workings. If you haven’t read them before, you don’t know what are you missing.

The other session was called “Mixing power of CSR with flexibility of KnockoutJs: three examples” and it was presented by Andrei Markeev. I couldn’t attend it but I spoke with Andrei and I am really looking forward to see the slides and the sample code. Andrei’s GitHub repository has some very good things to have in SharePoint arsenal: a CSR live tool (Cisar) and CAML JS console.

Workflows

The second thing I learned in Stockholm was just how awesome is the new workflow development experience with Visual Studio. SharePoint 2013 and Office 365 workflows use the new, external engine and all the calls are client-side code, either JS in SharePoint or REST API on your servers.

The session was called “Advanced SharePoint Workflow Scenarios” and was flawlessly presented by Paolo Pialorsi from PiaSys. If you haven’t heard about Paolo, which is very doubtful, he is the guy who wrote The Book on SharePoint Development and he’s one of the brightest SharePoint people I know. Check his slides and source code, there is a trove of information there. Grazie, Paolo!

Full-Trust Code to SharePoint Apps Transformation

Another session I liked was called “Transforming SharePoint Farm Solutions to the App Model” and presented by another Rencore genius and one of the founders of SharePoint Saturday Stockholm, Matthias Einig. He outlined the SharePoint development roadmap and the main obstacles from moving to the cloud. I think that it was a sober assessment of the state of SharePoint development right now.

 

Were you at SharePoint Saturday Stockholm 2015? What did YOU learn?

SharePoint Code Maintainance and Unit Testing Talk at SPS Stockholm

Last weekend I have attended another SharePoint Saturday, this time in Stockholm. The weather was nicer than the last year, and the attendance was over the top: 300 attendees to learn about and discuss SharePoint topics from the expert speakers.

The speaker lineup for SharePoint Saturday Stockholm

My talk was about how to build SharePoint code that’s both maintainable and testing-friendly. I have approached the talk from the coarse to finer detail, from the distribution of the solution components into SharePoint to the dependency injection mechanisms and principles of SOLID and GRASP object-oriented design.

Me speaking about maintainable and testable SharePoint codeThe attendees at SharePoint Saturday Stockholm

The demo I shared with the attendees was a very simple SharePoint provider-hosted app in ASP.NET MVC that displays the user full name and the login username. I started with a very coupled code that all sat in the Index action in the controller and I ended with a testable design that had the SharePoint ClientContext dynamically injected to the service at runtime, dutifully abstracted behind an interface. I used Unity IoC container and Moq for mocking the dependencies in the tests.

You can find the slides at my SlideShare page, as usual, and the source code for the demo (in a form of a Mercurial repository) on my OneDrive. I have received some very good comments about the topic and the techniques mentioned in the session.

If you have attended my session at SPS Stockholm, I have questions for you.

  • What have you liked most?
  • What haven’t you liked at all?
  • What could be done better?

Let me know how can I improve the talk for future events.

Where Are You Going, SharePoint?

I would like to do a short retrospective look to the rapidly-changing landscape of SharePoint in the last few years, followed by a personal opinion on the future of SharePoint. It is a fairly long rant piece, so it is advised to have at least 15 minutes at hand to read it throughly.

Note: It is obvious to me but won’t hurt to mention that everything mentioned here expresses my own opinion and my own opinion only. 

How SharePoint has evolved from 100% on-premise to hybrid and cloud

In the early years of SharePoint development, in the early 2000’s, the development on the SharePoint platform was restricted to the server-side code. You could only code what you could put inside the SharePoint box. Of course, the server object model let you do all sort of things, as it is the same model that was used internally by SharePoint (at least a significant portion of it). But, you were responsible for the performance and side-effects of that code as it was run inside the SharePoint very own IIS process or service. As long as you did your homework, the future was bright for you.

For the less prone to scare the IT people by stubbornly insisting on putting custom code in the SharePoint box, there was a second option: the ASMX web services. Clumsy as they were, they were the only option if you couldn’t (or wouldn’t) put your custom code in SharePoint servers.

Over the years, that approach was good and great. Best practices and guidance began to evolve and we saw less and less SharePoint "crime scenes" (as Matthias Einig puts it).

And then, Microsoft began hosting its own product, by launching SharePoint Online inside its BPOS (Business Productivity Suite).

Suddenly, Microsoft began feeling how it was to actually host SharePoint. They began to experience the same nightmares IT admins over the world had to experience when they wanted to patch their SharePoint servers. They weren’t shielded any more from the customers running SharePoint: they were the customer running it and they were responsible for their tenants and their SharePoint data.

 

image

SharePoint Online administrator Installing cumulative updates

During the first teething years of SharePoint Online, one thing emerged clear and painfully clear. It was the insight that what worked for a single datacenter doesn’t work for cloud environment, with multiple tenants. The customizations wouldn’t scale and what’s even worse, they would break with the frequent updates to the SharePoint version on Microsoft servers. Even with the stop-gap measure of sandboxed code, the customizations that involve code didn’t behave as Microsoft wanted for their hosting environment.

In other words, during the golden years SharePoint allowed massive customization with server-side code. You could build web parts, web controls, timer jobs, application pages and all sort of server-side extensions. You were allowed to shoot yourself in the foot and bring your SharePoint to a halt, because it was your own datacenter. You (or hopefully your governance committee) would decide what was more important. Also, you could put arbitrary code in your customizations and be happy with it. However, when you depend on your SharePoint servers running smoothly and flawlessly, it is only possible with plain-vanilla SharePoint structures with no customization. As careful as you were, there was always a penalty for your custom code. As for the security of that code, things such as CAS policies were a step in a right direction but many customers just turned their code trust level in web.config to Full and live with it.

How scalability and performance have taken precedence over customization

But, not Microsoft. Microsoft could not allow SharePoint Online to fail. Also, the prospect of selling monthly licenses instead of a one-time license was meant to inject significant cash flow into Microsoft Office Division balance sheets. Between the need of the "less desirable" one-time customers (who wanted custom code) and the need of Microsoft SharePoint Online cash cow (who wanted scalability and performance), the scales tipped to the side of the scalability (pun not intended).

So, things such as client object model and finally  "cloud application model" came to be. Your code was allowed, as long as it run outside SharePoint. The infrastructure was put into place to allow your code to call into SharePoint without the need for explicit credentials. Your calls to SharePoint were carefully securized, throttled and channeled to allow for non-customized SharePoint parts to run without being blocked or delayed.

SharePoint erred on the side of the performance, banishing server code on cloud deployments and slowly banishing (or deemphasizing) even the declarative customization. As long as you are fine with the evolving standard SharePoint Online features, you are good to go. Want more? Plug in an app, even if the client object model didn’t allow for all the richness of the functionality that server object model did. Your application would run on your servers, consuming your resources and leaving their SharePoint instances out of your bad influence.

What’s the future for on-premise SharePoint customers?

But, what Microsoft doesn’t seem to get (or does seem to ignore) is the reality of the corporate customers. SharePoint was never a software for small companies. Yes, you could run a SharePoint Foundation (or Windows SharePoint Services before that) and it was free, but the need for the corporate-scale collaboration and knowledge management that SharePoint ushers is something that goes with the medium and big companies, as it breaks department silos and culture barriers. Also, the hefty price tag for the SharePoint license didn’t help.

Now, SharePoint Online as part of the Office 365 package is affordable. Even smaller companies could take advantage of it. But, are they doing it? In my experience, the vast majority of the Office 365 customers in small companies are more interested in Exchange Online, because running a mail infrastructure is something every company does, small and big, while running SharePoint is something that is not everyone’s piece of cake. Whenever I listen to Microsoft marketing machine trumpeting about "millions of Office 365 users" I can’t help asking myself how many of them are only using Exchange Online out of the whole Office 365 package. (Answer: I don’t know but I imagine that a vast majority).

So, here we have Microsoft cranking out new features to suit their "imaginary" customers that want wizards, flashy UI and shiny settings, while the real SharePoint customers with deep pockets are placed between a rock (declining investment in new on-premise features) and a hard place (the fact that Office 365 deployments customization options are limited at best). They need freedom to customize their SharePoint to suit their needs, and right now the capabilities of the app model and Office 365 app model are just not enough. Not to mention the need for UI customization, which is the first thing that corporate customers want. They now have to jump through hoops just to deploy and keep their master pages, CSS and JS files from breaking with each SharePoint Online update. Not good.

As a side note, the need of the on-premise clients for top-of-the-notch social without hassle was the driver that made Beezy, the company I work for, possible. If that capabilities were available on SharePoint Server, we would be out of business even before starting.

That has been by experience with the SharePoint customers that are more or less "invited" to become Office 365 customers. Only a few of them venture into the hybrid world of connecting their on-premise farm with the Office 365 farm. In the future, this number will increase, but will it ever be so overwhelming as to dispense with the on-premise SharePoint. My opinion is that it won’t. We won’t see the end of on-prem SharePoint in the foreseeable future.

image

What lies ahead?

Why I so firmly believe this? First, the cloud is not fully parring the on-prem world. I know that SharePoint is just the "expression" of the solution for a business need, but right now going to the cloud makes you lose certain flexibility (in the depth of your customization) and gain another flexibility (on the deployment and operation costs). So, there is still a gap between what cloud enables you to do and what SharePoint Server enables you to do. In the future I believe that the gap will be closing, but not disappearing. Yet, the cloud will allow us to plug-and-play different services and technologies to build our solutions. It will widen our choice of options, not narrow it down.

I think that we will see more and more hybrid deployments but there will always be on-premise deployments with workloads that are only suitable for that scenario. Conversely, there will be (and there are) cloud-only scenarios such as machine-learning powered Delve and Outlook Clutter that can’t be deployed on-premises as it requires some really BIG data (pun intended) to work properly. But, for a big company with their own processes and dynamics, I just can’t see a cloud-only environment, no matter how hard I try to imagine.

However, the love SharePoint Server got from Microsoft during the last decade has gone to the new, cloudy sweet-heart: SharePoint Online. It is a fact.

I would like to imagine the future SharePoint Server (call it vNext or 2015 or whatever) to be more like Windows 8 than Windows XP. Windows XP had to be replaced with Windows Vista and it was a fairly traumatic deployment. But, Windows 8 was "updated" to Windows 8.1 with little or no hassle, and you ended up with very different Windows. In another times, it maybe would be called Windows 9 and would have to be deployed in a "traumatic" fashion. In the same light, I can imagine future SharePoint getting periodic updates (as Windows or Visual Studio do), with new and enhanced features, not only bug fixes. I can imagine that the main development branch is the cloud one, and that not all the features can translate to the on-premise version, but I can’t imagine a reason for not having that kind of quick, iterative development for the cloud that "trickles down" to the SharePoint Server periodically. Gone are the days of 3-year cycle for SharePoint Server, the cycle is now merely couple of weeks long. It is perfect for the cloud, but I think (and hope) that it will also add enhancements to the on-premise customers. Let’s face it, SharePoint is a fairly mature product with a broad set of features. What corporate customer need is not to have the latest eye-candy, "sexy" features but fixing the long-standing pains of basic, staple SharePoint features. I’m not saying that there is no value in the new features, there certainly is. However, there is no excuse for having half-baked functionality any more in SharePoint, online or not.

What’s the future for SharePoint specialists?

In the end, where it leaves us, the SharePoint developers, architects, consultants, Power Users, customizers and so on?

It is normal to feel a certain amount of dizziness and feeling of being let down. Microsoft messaging to the customers is something chronically ambiguous, although the transparency set by some of the teams in Microsoft is exemplary in the last years. They are improving. But still, giving mixed signals or flatly ignoring the rightful questions of the corporate users is making them question whether Microsoft commitment can be taken seriously. (Yes, I mean Silverlight and sandbox solutions and autohosted apps and so on).

Well, let’s face it: the world is changing. It never stopped changing. We can’t cling in the comfort zone anymore, if we ever did. I think that the pace of technological change has accelerated and with it comes a natural reluctance to change (I explain some of it in my Pluralsight course about human behavior). We have to embrace that change.

What does it mean? It doesn’t mean drinking the Microsoft Kool-Aid and firmly believing their marketing messages. They have all the right to send whatever signals they want, but we SharePoint specialists are paid to assess and advise our clients about their technology, not to repeat it like trained parrots. In many cases the message is perfectly valid, but in many cases it is not and we should know better. As I said before, SharePoint (and Office 365) were, are and will be the tools to build solutions for business needs. Not the solutions themselves. Sometimes, we lose track of this simple fact.

It means that we should learn, practice and keep raising the bar. We are on the front line of technology and we should be prepared. Luckily, it has never been more easier to learn new things and find guidance (The OfficeDev PnP team is just the example of that). Dedicate some time to play with the cloud, to experiment with apps, JavaScript and hybrid environments, to fiddle with Delve and Office Graph and to keep pushing the envelope. You will be acquiring new tools to build your technological solutions to business problems. That’s your job as a technology specialist.

What are your opinions? I’m eager to know them.

All images provided by Freeimages.com.

High-Trust SharePoint Apps, Token Lifetime and MemoryCache

In the last months I have been busy working on a project that includes high-trust on-premises SharePoint 2013 app that is accessed by many people at the same time. Each user is issued an access token that authenticates the user and points to his or her SharePoint site.

The problem that began surfacing is that by default high trust access tokens have a lifetime of only 10 minutes. So, as we cached the token in memory, after 10 minutes SharePoint would start giving 401 Unauthorized errors, due to the token being expired.

Extending the lifetime of the access token

The solution to the problem involved increasing the lifetime of the access token to 60 minutes. This is a fairly simple change in TokenHelper.cs file.

Find the IssueToken private method in TokenHelper.cs and in the "Outer Token" region, change the line that creates the JWT token to this:

MemoryCache

In addition, we have added a MemoryCache single instance in-memory application cache (available in NET 4.5). The access tokens are added to the cache with an absolute lifetime of 60 minutes, so they will expire at the same time as their lifetime in SharePoint. Once evicted from the memory cache, the access tokens are recreated with an additional 60 minutes of lifetime and stored in the cache again.

Bonus: Refactored for reusability and testing

In order to make our code simpler and more understandable, we added the caching capability as a provider, exposed by the ICachingProvider interface. The ICachingProvider interface exposes the operation for getting an object from the cache with a specific key. We wanted the code to be reusable not only for tokens but for all suitable situations.

The operation GetFromCache is a generic method that allows the user to get a typed object from the cache by providing a string key and a type. Moreover, the operation requires a fallback method. This fallback method is a generic Func<T> that returns an object of type T. The cache implementation then uses the function delegate (a lambda expression, in most cases) if the specified key is not found. By invoking the delegate, we get the object from its source (as if there were no cache) and store it in the cache with the given key.

The full CachingProvider code is displayed here. There are two auxiliary methods to add and retrieve items from the cache. In order to avoid concurrency exceptions, the access to the MemoryCache instance is protected under a lock object called padLock.

One added bonus of having an interface is that we had two implementations of the interface: CachingProvider (the normal caching service) and DummyCachingProvider (that simply bypassed the cache and returned the result of the Func delegate invocation). In this way we could disable caching by injecting the correct instance of the caching provider and also it benefitted unit testing as we could test both the cached and non-cached code paths.