Sharepoint Apps Introduction_v1

44
Sharepoint Apps Introduction Introduction d in this chapter, I'll be talking about SharePoint 2013 Apps. In this series of chapters we'll start with a crawl-walk-run approach. We'll start with the basics, and then we'll keep diving into deeper, and deeper, and my aim here is to give you a good practical insight into why Microsoft created apps. Are they any good? Or bad? And we'll get a pretty good balanced approach and view on the limitations of the platform as well, and I also like enough hands on experience to see what is it like writing an app, deploying it, maintaining it, upgrading it, and so on and so forth. So, without much further ado, what have we covered so far? So far, everything that I've talked about on my various chapters on Pluralsight about SharePoint 2013 have been about SharePoint solutions, WSB files, farm solutions, or sandbox solutions. Farm solutions that were introduced in SharePoint 2007, they worked in 2007, 2010, 2013. Sandbox solutions were introduced in 2010. They still work in 2013. Everything that I'm talking about is also covered here in my book in SharePoint 2013 Planet of the Apps. This is available on Amazon.com. I've pasted the link up there for you, sp2013apps, bit.ly/sp2013apps. Why did Microsoft Create Apps? When Microsoft introduced SharePoint 2013 to us, and by that I mean the beta, when they first introduced the beta to us, they basically introduced it with this paragraph. They said, "Use SharePoint as an out of the box application whenever possible." They are encouraging you to not modify it as much as possible. Practically speaking though,custom code is a necessary evil, because the customer wants a hammer, and here's a plier. Not going to work. Customers want, you know, people have been used to, for good or bad reasons, they are used to getting exactly what they want, and customers sometimes are picky about how one particular button operates, and so on and so forth. And if you work with SharePoint long enough, you'll know that not everything in the UI, and the way it behaves can be intuitive to the end users, even to us sometimes. So, for very good reasons, customers, they want more control on the UI, and the functionality. So custom code is not going away. You might hate developers, but we're here to stay. But, custom code is the number one cause for support issues. It is the number one cause for upgrade issues. You can't avoid custom code. So, Microsoft needed to give us a way to write custom code, but to be able the do so while keeping thingsreliable and predictable. Because, people weren't upgrading from SharePoint 2007 to 2010, and then 2010 from 2013, because they weren't sure what that would do to, guess what, their custom code. The custom code was a number one upgrade blocker. So, Microsoft wanted to give us a mechanism where we could upgrade with confidence. We could apply new patches with confidence, and we could deploy custom code with confidence that nothing was going to be broken on the SharePoint server. And to solve that problem, basically the apps model was introduced. And, while they were solving that problem, they solved a bunch of other problems to go with it. For instance, everybody in the Microsoft world is raving about how cool MVC is. Well, as a SharePoint developer, we can't use MVC. Not really. If you write apps, you can use MVC. Or, if you're a PHP developer, perhaps you already have an existing product that you don't want to rewrite completely for SharePoint. Apps allow you to basically take any product, or technology, and as long asit's a source code for it, doesn't matter what language, you can turn them into SharePoint apps, and start taking advantage of the amazing functionality that SharePoint has. IGATE Sensitive

description

Sharepoint apps

Transcript of Sharepoint Apps Introduction_v1

Page 1: Sharepoint Apps Introduction_v1

Sharepoint Apps IntroductionIntroduction

d in this chapter, I'll be talking about SharePoint 2013 Apps. In this series of chapters we'll start with a crawl-walk-run approach. We'll start with the basics, and then we'll keep diving into deeper, and deeper, and my aim here is to give you a good practical insight into why Microsoft created apps. Are they any good? Or bad? And we'll get a pretty good balanced approach and view on the limitations of the platform as well, and I also like enough hands on experience to see what is it like writing an app, deploying it, maintaining it, upgrading it, and so on and so forth. So, without much further ado, what have we covered so far? So far, everything that I've talked about on my various chapters on Pluralsight about SharePoint 2013 have been about SharePoint solutions, WSB files, farm solutions, or sandbox solutions. Farm solutions that were introduced in SharePoint 2007, they worked in 2007, 2010, 2013. Sandbox solutions were introduced in 2010. They still work in 2013. Everything that I'm talking about is also covered here in my book in SharePoint 2013 Planet of the Apps. This is available on Amazon.com. I've pasted the link up there for you, sp2013apps, bit.ly/sp2013apps.

Why did Microsoft Create Apps?

When Microsoft introduced SharePoint 2013 to us, and by that I mean the beta, when they first introduced the beta to us, they basically introduced it with this paragraph. They said, "Use SharePoint as an out of the box application whenever possible." They are encouraging you to not modify it as much as possible. Practically speaking though,custom code is a necessary evil, because the customer wants a hammer, and here's a plier. Not going to work. Customers want, you know, people have been used to, for good or bad reasons, they are used to getting exactly what they want, and customers sometimes are picky about how one particular button operates, and so on and so forth. And if you work with SharePoint long enough, you'll know that not everything in the UI, and the way it behaves can be intuitive to the end users, even to us sometimes. So, for very good reasons, customers, they want more control on the UI, and the functionality. So custom code is not going away. You might hate developers, but we're here to stay. But, custom code is the number one cause for support issues. It is the number one cause for upgrade issues. You can't avoid custom code. So, Microsoft needed to give us a way to write custom code, but to be able the do so while keeping thingsreliable and predictable. Because, people weren't upgrading from SharePoint 2007 to 2010, and then 2010 from 2013, because they weren't sure what that would do to, guess what, their custom code. The custom code was a number one upgrade blocker. So, Microsoft wanted to give us a mechanism where we could upgrade with confidence. We could apply new patches with confidence, and we could deploy custom code with confidence that nothing was going to be broken on the SharePoint server. And to solve that problem, basically the apps model was introduced. And, while they were solving that problem, they solved a bunch of other problems to go with it. For instance, everybody in the Microsoft world is raving about how cool MVC is. Well, as a SharePoint developer, we can't use MVC. Not really. If you write apps, you can use MVC. Or, if you're a PHP developer, perhaps you already have an existing product that you don't want to rewrite completely for SharePoint. Apps allow you to basically take any product, or technology, and as long asit's a source code for it, doesn't matter what language, you can turn them into SharePoint apps, and start taking advantage of the amazing functionality that SharePoint has.

What are we going to Talk About?

What am I going to talk about? I'm going to talk about SharePoint apps only. I'm not talking about Office apps. Now, I will say that SharePoint apps are in some ways a v1 release, and in that sense I think Office apps are a v0.5 release. These platforms need to bake further. There are, I feel, a lot of open holes in the functionality, and I'm recording this chapter in the November/October timeframe of 2013. So, I'm pretty sure Microsoft will plug a lot of open holes in thefunctionality as it sits today, but apps are something that is future proof. It is something that we should learn. If anything, we should learn it from the point of view of where things are headed, how you can take advantage of apps today, and where you should avoid apps. So, I think Office apps are, the applicability of them is, I feel, a little bit lesser. But SharePoint apps I think are more mature, and you should learn them. Now, there are open holes there, and their limitations that I hope to be able to cover in this chapter. So again, it is a v1 release. There's a lot of promise in it. I encourage you to learn it. There are some potholes in the

IGATE Sensitive

Page 2: Sharepoint Apps Introduction_v1

story, things that will bite you, but that's how the architecture is. And things that are open holes that we wish we had the functionality for, and I think we will have functionality for in the coming future.

Apps, the Golden Rules

With that, I would like to start talking about some golden rules about apps. These are things that if somebody woke you up at 3 in the morning and pinched you, and asked you about apps, these concepts, eight golden rules about apps, they should be absolutely clear to you. So, what are the apps' golden rules? Number one, apps, it doesn't matter what kind of app, apps can never run any code on the SharePoint server. You can't write C# code in apps and expect it to run on the SharePoint server. Impossible. That's a golden rule of apps. That's how they're keeping you out of the guts of SharePoint. That doesn't mean you can't do server side code. It's just that that's server side code cannot use the server side object model of SharePoint. It shouldn't. So the way apps work, is that you can click on a URL within your SharePoint server, and it takes you to a completely different URL, where the app is running from. And all your interaction with the SharePoint server now goes through that completely different URL. Now one of the most confusing aspects of apps is, people say that, well I can, this sort of tells me that I need a separate website for apps. Well, you need a separate URL. For a lot of scenarios, there's something called a SharePoint-hosted app. That is, you can write all the logic you care for completely in JavaScript. You don't need server side code. It is possible to do that. And in that scenario, the app can be served out of SharePoint. It can even run on SharePoint. It just can't run any server side code.So, your app can basically download JavaScript, runs in the browser, and then that interacts with the SharePoint server. Remember, you're not running any code on the SharePoint server. This is a very important golden rule as far as apps are concerned. How do you install apps? Well, just like your phone, they're downloaded and installed. You can discover them from the App Marketplace. You can setup such a Marketplace inside your own corporation, actually you can have more than one if you wanted. Think of that as a Corporate Catalog, or an Enterprise App Store within your company. Or, you can push the apps to SPWebs, through PowerShell, or through the SharePoint API. Because, when you make an app available, either in the Marketplace, or on the Corporate Catalog, it's basically like a menu, and users can order off of the menu. They can install an app if they find it useful. But sometimes we want to make the app available even if they haven't installed it. Think of it this way. Let's say if we've got a time registration system built in SharePoint. Well, do you have to install time registration to use time registration? No. You just want to give the user a URL, and the user goes there, and just starts using time registration. That's how to think of it. So, sometimes it is necessary to push these apps, the IT department has the ability to do that for users. Now, in the user interface, lists and document libraries are also called apps. Those aren't apps. This is something that they've done for the convenience of the end user. Let me show you what I mean. This is a simple SharePoint team site, it's running locally. I'm going to go to Site Action, and then click on Add an app, and let's see what we see here. Document Library. Custom List. Tasks. You know, these are called apps, App Details, etc., but they are not apps. They are in the object model, and inside underneath the scenes, they are SharePoint lists and SharePoint document libraries. These are apps only as far as the end user is concerned,syntactical or whatever you want to call it, but these are not apps. When I say apps, and I'm talking with developers, I'm talking in developer speak. By that, I mean a SharePoint app, I don't mean a document library. I don't mean a list.Moving on. Apps can never run from the same URL as the SharePoint site. And you should not try to get around this rule. Apps must always run from a URL different from the SharePoint site. What does that mean? Let's say your intranet is at intranet.contoso.com. Well, apps cannot come from intranet.contoso.com. They can come from apps.contoso.com,or contoso.apps.com, or something else .com, but never from intranet.contoso.com. And this distinguishing factor is crucial to the apps security model. The reason being, apps run under a limited security model. So just like you install an app on your phone, and it says, hey, this app is going to use your GPS, they're going to use your camera, or whatever,and you can say Allow or Deny. Apps in SharePoint are the same way. When you install the app, the app asks the user whose installing them. It says, hey, I'm going to write your SharePoint site, are you sure you want to trust me? And the app author basically says that my app needs these security rights, the capabilities. So, for that security mechanism to work, it is important that the app continue to run from a different URL. So, again, it was like apps.contoso.com versus intranet.contoso.com. So, that is a valid combination, but when both of them are ending in .contoso.com, perhaps they can share cookies. So sometimes you may want to take it on a completely separate domain. That depends on the application. For intranets, I guess, it is okay. Internet sites you probably want to use a different URL or something like that, depends on your situation. Again, apps are installed in a SPWeb. So remember features? You could install them on a farm, web application, site collection, and a SPWeb. Apps are always at a SPWeb level. And where you install the web is called as the HostWeb, and when you install

IGATE Sensitive

Page 3: Sharepoint Apps Introduction_v1

the app, it might, not necessarily, it might create a child site under that HostWeb. And that's called as the AppWeb. Now even though it is a child site, even though AppWeb is a child siteoff the HostWeb, it is on a completely separate URL. And there is some magic built inside a SharePoint that allows us to do that, and we would require some configuration that needs to be done ahead of time to make that happen. But, HostWeb, and AppWeb, even though AppWeb is a subsite of the HostWeb, they are in the same site collection, but they are actually on two completely separate URLs. This will become clear when I actually start writing these apps. So, what I mean by that is HostWeb is where you install the app. AppWeb is the child of the HostWeb where the app can create artifacts. And sometimes you may also have an External Web Application that is a part of your app. So the way it works is that you can have either the AppWeb, or the External Web Application, or both. So you can have one or two. And the External Web Application is required in scenarios where you do want server side code, because remember, I said apps cannot have server side code on SharePoint, but sometimes you do want server side code. In that case, you'll need the External Web Application, and in that case, the AppWeb becomes optional. You may have it, you may not have it, depends on what your app is doing. Why would you want to have both? I think it is easier to explain that when I talk about provider-hosted apps. Provider-hosted apps are the ones that have the External Web Application. So park that question in the back of your mind. Why would you want to have both the AppWeb, and an External Web Application, park that question in the back of your mind. I'll come back to that in a second. But for now, it is important to know that where you install the app is called as the HostWeb, and the app itself runs either in the AppWeb, or in an External Web Application, and either of them are on a completely separate URL. So, in brief, why would I want an External Web Application? It's when I need server side code, because I can't run the server side code on the SharePoint server. I need some other server to run this on. So, why would I want server side code, where, let's say, I have a timer job, a SharePoint timer job, and let's say equivalent of a SharePoint timer job, something that runs on its own, once every five minutes it does something to the SharePoint server. And those scenarios maybe warrant a separate External Web Application. Anytime you have a separate External Web Application that is also referred to as a provider-hosted app.And there are two kinds of provider-hosted apps. We'll get into that in a second. And apps are bound by permissions, and the identity of the app, and what the app can do, and all this whole security model, which I will talk about in more depth later, but underneath the scenes they are secured using OAuth and Server to Server Trust. Okay? Excellent. So at this point, this is the list of Apps Golden Rules. I would advise you to pause the chapter, read through this list, and make sure that each one of these eight points is crystal clear to you. This needs to be very, very clear to you. You read a lot of these things about apps on the internet, etc., and sometimes it can be very overwhelming and confusing, but you got to make sure that these eight rules are very clear to you. Pause the chapter, and I'll catch you on the other side.

Kinds of Apps

Great! So I hope those eight rules are absolutely clear to you. With that behind us, let's talk about different kinds of apps. Now, the way I understand anything is easy to, when there's a big complex topic, to say where do you start?Categorizing things within that big topic is a good way to start. So, you can categorize apps in various ways, but a very convenient way, or two different ways; either you can categorize them by their user interface type, or you can categorize them based on how they are hosted. So, when I say user interface type, remember that the app, no matter what kind of app it is, no matter what kind of app it is, it is running from a different URL. And by definition, if I was to open the browser, and if I just HTTP to that URL, I would get the full screen experience of that app. So every app supports the full screen experience. In fact, if you don't want the full screen experience, you actually have to put in extra work to preventthat full screen UI. Apps can also run as a "pretend I'm a webpart." As in users in SharePoint, they're very used to webparts. They love being able to put the page in a RIP mode, and drop a webpart, and do something useful with it. Apps can work like webparts. Now I said pretend a webpart, because a lot of things that we're used to in webparts are actually not available in apps. These webparts that run apps, are also called as app parts or client webparts. So, I'll use the term either app webpart or client webpart, to refer to an app running as a webpart. The app running as a webpart has got a lot of limitations. It's basically a glorified IFrame underneath the scenes, so I would basically say that it's pretending like it's a webpart. It's really not a webpart. And the third possible way that you can categorize apps from a UI perspective is when you launch them using a SharePoint custom action. If you watched my previous chapters, you would know that custom actions are a mechanism for us to be able to create links at various places in SharePoint, like inside actions and the ECB menu, and site settings, and so on and so forth. So you could have a button in the ribbon, for instance, that launches an app. That's a perfectly good example of a UI experience for an app. So, how do you categorize them by UI type? Full screen takes over your entire browser, runs pretend I'm a

IGATE Sensitive

Page 4: Sharepoint Apps Introduction_v1

webpart, which is a glorified IFrame, and running SharePoint as a custom action. So, running, launching the app through SharePoint is a customaction, so click on a link, and it launches the app. They can also be categorized based on how they are hosted.Sometimes apps can do whatever they need to using purely SharePoint hosted code. Using JavaScript code I mean. So, the app can be completely served out of SharePoint, and SharePoint only, because it is not running any code on the SharePoint server. It can run whatever it wants in JavaScript, but it's not running anything on the SharePoint server. No C# server side code, or VB.NET for that matter. So, that's called as a SharePoint hosted app. But sometimes you want server side code, and in that scenario, you have two subcategorizations. One is with you set up the server ahead of time. That's called as a provider-hosted app. And the other in which a server area is created for you any time the app is installed. If the app is installed 20 times, 20 server side instances are created for you. It's not as bad as it sounds, and 20 sounds like a pretty big, bad number, but the reality is they're all copies of each other, and actually when you uninstall the app, that server side area disappears, so it's actually no headache for us. It's actually a pretty good option.So that's called as an auto-hosted app. It applies only in Office 365 as of now, and when you basically install an app in Office 365, if it is an auto-hosted app, it will provision an area behind the scenes in Azure. We don't know that it's in Azure really. It's a black box to us. So it's not like we're going to see it in our Azure portal, and we'll be able to tweak it otherwise. No. It's a total black box for us. It basically creates an area in Azure for us, and the app runs over there merrily. So, the important thing to realize over here is that these two categorizations aren't exclusive to each other. So you can have a provider-hosted app that runs as a client webpart, or you can have an auto-hosted app that runs in full screen. But this is a good way for us to be able to understand categorizations of apps. So this is, again this is very important, it's a very important concept that we need to get in our minds, that apps can be categorized in two major categories, by UI type or hosted type, and under UI type you have three kinds, and hosted types you have two kinds,and one of them has two subtypes, and what those are is very important to understand. Again, all of this will become a whole lot clearer when you actually see this in action through code.

Setting up Your Environment for Apps

The next thing I'm going to briefly cover is setting up your environment for apps. And I said briefly, because I've already covered it when I talked about creating a dev machine for your SharePoint development. And when I said setting up your environment for apps, by that I mean for production, and development both. Basically, imagine that users are installing apps left and right. And I said earlier that apps run on a URL other than the SharePoint server. So, whenever the user installs an app, a new URL is created for my installation. I install this app, I get a URL. You install the same app, you get a different URL. So what is the IT department supposed to do? Every time a user installs an app, are they supposed to go and create a DNS entry for me because we have a new URL? That is impractical. To solve that problem, what you have to do, you have to create a wildcard CNAME record. Let me show you what I mean. If you go into the DNS settings here, this is my dev environment, so everything is contained on one VM, but in production you have to do this on the domain controller, or DNS. So basically I've created a Forward Lookup Zones, called apps.ws.int.My domain is S.int, and inside of apps.ws.int I have a wildcard CNAME record. And effectively what this lets me do is that if I do ping anything.apps.ws.int, it points me back to the same server that I'm running this on. So if I just say ipconfig, you see that my IP Address over here is 192.168.137.128, which is basically the same address that this anything is pointing to. So, by anything, I mean I could test things like ping Pluralsight.apps.ws.int, points me back to thesame IP Address. Ping let's say winsmarts, I can't type, there you go. It points me to basically the same DNS. Okay. So that's a very, very important consideration. This is one of the things you have to do, and you have to do some other settings. You have to do some things in Central Administration. You have to do things in PowerShell. Basically you have to provision a couple of services, and the App Management Service, and the Subscription Settings Service, simple to do these things. Again, I'm not, I'm glossing over this point because I've already talked about this in the setting up your dev machine chapter. I would encourage you to check that out, but this is how you set up an environment for apps. One important consideration that I'd like to point out though, is apps don't work with AAMs, Alternate Access Mapping. So if you have an internet facing site, and you have the site exposed on two different zones, you have to pick one zone, basically the default zone where your apps will run. You can't run them on both. Now, the March 2013 Public Update for SharePoint 2013 solves that problem. It gives you three PowerShell cmdlets that allow you to configure your apps environment for AAMs. Again, this facility is turned off by default. So, you have to turn it on using these PowerShell commands. It does require some configuration, and some thought into how you want this to work. So that's a special consideration you have to keep in the

IGATE Sensitive

Page 5: Sharepoint Apps Introduction_v1

back of your mind. So that's about how you set up your environment for apps. It is important that you do that first before you start writing apps, or deploying apps to your production environment.

Writing Apps

Speaking of writing apps, let's dive into it. So, by now I assume that you have setup you dev environment, etc. There are two ways to write apps. One, using NAPA. NAPA actually doesn't even require you to setup your dev environment, because NAPA is completely contained inside the browser. NAPA is an app that you can use to write apps, only for Office 365 for now, but still it's pretty cool. But, I said real developers don't use NAPA, because NAPA has a lot of limitations. I think if you are going to seriously start writing apps, you probably want Visual Studio, and you probablywant a good dev environment. If you're targeting Office 365 only, and all you're doing is writing apps, then you don't need the dev environment. But I think practically speaking, I think by the end of this course you will agree with me that you want a dev environment. So, let's start by introducing ourselves to NAPA first, and then we'll dive into other topics.So.

Writing Apps using NAPA

Writing Apps Using NAPA. What is NAPA? NAPA is an app that you can write to, that you can use to write apps. For now, it works only in Office 365. It is devoid of a lot of features, like it doesn't have source control, cruise control, etc., etc., etc. So it's not suitable for team development. It's good for quick, small projects, but if you want to do any heavy duty development, you probably want to use Visual Studio. But what NAPA does allow you to do is that it does allow you to export from NAPA into Visual Studio, and still continue to target Office 365. So it gives you a one time, one way export from NAPA to Visual Studio. You can't make changes in Visual Studio and put it back in NAPA. That does not work. So you can go from NAPA to Visual Studio, but you can't go the other way around. Again, as I said, it's good to get started with, but for serious app dev, you probably want Visual Studio and a proper dev machine. Now, why is NAPA useful? Imagine that there's a Mom and Pop shop who have set up Office 365, and they've done everything they want out of the SharePoint side, but, they want that one extra functionality that requires them to write a little bit of code. In that scenario, they would find NAPA very useful, because for that little bit you don't want to buy Visual Studio, install it.Visual Studio can be expensive. So it's great to get started with. So that is what NAPA is. So, let's examine how to write apps using NAPA. Now, the first thing you're going to need to be able to write apps using NAPA is, well, an Office 365 subscription, and I happen to have one, and you can get one too. So what I'm going to do, I'm going to Close this tab, which is basically pointed to my HTTP SP local, so I don't confuse the two, because they look so similar, and I have set up Office 365 subscription for me at winsmartdev.sharepoint.com. If you want one for yourself, you can go to, of course you can purchase it, but I know we're cheap, so what you can do is to go dev.office.com, click on this link here, and we go down here. You see this thing here. See this big blue nice button, Try it free, gives you a 30-day free trial, you can use that. Or if you have MSDN, you can get a one-year of free subscription. So there are ways. So, you see here that under Recent here, I have these things here. That's because, well I've been playing with the site, and right now the site is clean. I went, before starting this recording, I went in here, and I cleaned out everything out of this site. So, I don't have NAPA installed. I don't have any apps installed. Just ignore what it is under the Recent area over here. So see there's really nothing here. It's clean.

Installing NAPA

I'm going to, my aim here is to install the NAPA app. How do I go about doing that? I look for this button that says add an app. Click on it, and it says Apps You Can Add, so I've added this app before, so this is available to me. If you don't see it here, go to the SharePoint Store. Wait for it to load. If it doesn't load, okay, pay attention here, you might need to set the language and country, and all that. And then if you look in here, you see a couple of really interesting apps, and tell you what, now press right here. So you click on this, and you click on ADD IT. It might ask you to sign in at this point. I'm already signed in, so it didn't ask me again. And see, any app that you install, will present a dialog similar to this. So, this says that NAPA is going to have full control of my site collection, so don't install NAPA on site collections that have secure data on them. But, I'm going to go ahead and Trust It. This is just my dev site, so I'm going to go ahead and trust it. Now, it's installing NAPA. Give it a second.

Create a Project using NAPA

IGATE Sensitive

Page 6: Sharepoint Apps Introduction_v1

And once it installs, this link becomes available. I'm going to click on this. Working on it. And here you go! Here's my Cloud based development environment. Now I can click on this Add a New Project. Now, I previously created a project, so my previously created projects appear here. I can choose to Delete it if I want. But I'm going to click on Add a New Project, and you see that I can target these kinds of projects. So, see these icons over here, these tell you whatplatform these things can target. So you see here the Office apps. Excel has the best story really, but, you know different apps have different compatibility modes, or rather different applicability, so Content app is available only for Excel at this point. I think, consider this as one of the open hole writing Microsoft will probably expand the availability of apps to all sorts of Office applications, but as now, it isn't. But, we're talking about apps for SharePoint, so I'll choose this, and you can click on this Create button to create a starter app. I already have one, so I'm going to go ahead and open this.

Walkthrough of NAPA and Your Project

One thing I tell you is that every time I use NAPA, they move things around a little bit. They change it. It's a beta product. It's a preview. It's quite interesting to see where it's going. I think it's a very, very impressive tool that they've built. It runs completely in the browser. It's got a lot of interesting features. Now, every time I look at this again, I'm like pleasantly surprised with all the things these guys are building. So, it's got statement completion. See that. It's got basic refactoring. It's got things like context.; see this, like it's got IntelliSense with a decent help. It's got parenthesis completion. I can do things like context., like full IntelliSense with, I mean, this is pretty impressive. The fact that it's running completely in the browser, and what you can do with this, is quite amazing. In fact, what it does, is that, it evaluates your JavaScript on the fly, so I can do a function MyTestFunction, and I'm just going to go ahead and add this.And now when I come here, and I say MyTest, and see its statement completed. Right? You see that? So, it's pretty impressive that it is continuously parsing my JavaScript as I go, and it is making things available for me. That's quite amazing. You can consider this as the young kid brother of Visual Studio. The thing you see on the left hand side, can be considered as the equivalent of your Solution Explorer, or Project Explorer. It only shows you one project at the time, which is why I said Project Explorer. It shows you what's contained in your Solution package. So, you see here that I have App.css, Appicon.pmg, and I've got two aspxes and an App.js. So, if I look at Default.aspx, actually if you going to,first let me click this button here, Properties, and you see here that the Start Page is Pages/Default.aspx. Let me go back and do the code. Default.aspx is what will get launched when my app is launched. Because that's the Start Page. And inside here, I have a paragraph, ID message. I have included jQuery, and the SharePoint JavaScript files, as you can see up here, and as you can see here, that I've also included Scripts/App.js, which is this file here. So, remember this ID is message, and I have jQuery, and the SharePoint JavaScripts available for me. So things like CSOM, etc., should be available. So using jQuery, I'm using this document ready. Okay, so basically when the page body on load gets called, I say page load, getUserName gets called, this is getUserName, and in here I do context.load(user), and so basically I want to load the details of the user. And then I call context.executeQueryAsync. Look at this beautiful IntelliSense. And then I call Success method, or in the case of Success, basically if this succeeds, this method is called.And then Fail, I basically show an alert. And in the case of Success, you see here that there's a $('message').text, and I'm basically getting the name of the user, and I'm writing that inside of that message paragraph that I had. Now before we go too crazy by clicking this little button here that Runs the project, let's quickly examine what are all these other buttons on the left hand side. This over here allows me to Search for things within the project. This here allows me to set various properties, like with this Start Page, this, let me change that back, and the StandardTokens, this thing, URL Parameters, etc., that you see here. There are some StandardTokens that the object model of the SharePoint app, not object model, but the whole development infrastructure is giving us, and a StandardTokens gets replaced at runtime with some Standard Properties, like what's the host URL? What's the app's URL? What language you're running on. What version you're running on, etc. So there's a list of these tokens. You can add more if you want, and that's that.Client Web Part is this particular app can run as a web part also; pretend I'm a webpart web part. And it basically loads up an aspx, and the aspx it loads is the ClientWebPart.aspx. Again, it's passed these tokens. It's got a height and a width, and on and so forth. What Permissions does this app ask for, and so on and so forth. What Remote Endpoint it supports. So, you can configure all of that in Properties. If the app is currently deployed, you can click on Retract App to remove it from your SharePoint site. You can Open this in Visual Studio. We'll see this in action in a second. Share this Project with others. You can Publish this project to the App Store, or you can do a Quick Open, which lets you easily find a file in your project, like I just did. So, what I'm going to do now is I'm going to click this Play button. And I'm going to hold the Ctrl key down on my, because you know there's like a popup that it pops open in order to be able

IGATE Sensitive

Page 7: Sharepoint Apps Introduction_v1

to run the app. So, in your Explorer, it's probably going to block my popup, and I can't seem to find where the option for that is, to disable that. So I'm going to hold the Control key down, and hit this Play button, and it'll go ahead and package my app,Deploy it, Install it, and then Launch my browser, and hopefully my app should be running soon. So the Control key didn't work. So, I'm going to go ahead and click Always Allow from here. And now unfortunately, it reloads my browser, and I'm going to hit this Play button one more time. So you see it Uninstalls now. Installs again. Uninstall is the same as retract. And pretty soon it'll Deploy, Install, and Launch. Here we go.

URLS for Your App

So, my app is running. Hello Sahil Malik. See, that was the logic of my app that basically it was going to show me the name of the logged in user. I'm going to Copy/Paste this URL here. This is the URL of the app at the very top. And, I'm going to go back to my SharePoint site by clicking this link here, Office Dev Team Site, and click this back button, and I can discover the app by clicking this button here. So let me Copy/Paste this URL before I go back into the app again.And let's come back here, oops, here, and I go to the site Actions, Site contents. And I can find my SharePointApp1. It's right here. I can click on this and it takes me back into the app. This is how users can find the app. Since this app also runs as a client web part, what I can do is that I can Edit this page, and I can choose to INSERT this app as an App Part, and you see here that SharePointApp is present here. Or I can just click on this Web Part button, and under Apps I can find the same app. I'm not actually going to do that because we'll see that in more depth later. Anyway, so this is basically, this is how you can easily write an app, and deploy an app, and use an app, and so on and so forth.

Exporting NAPA to Visual Studio

Now let me come back to NAPA, this button here, and I'm going to click this button to be able to Open this app inside of Visual Studio. So, it's thinking, and pretty soon you see that it tries to launch something. It's a project launcher. Interesting. I'm going to click on this Run button, and it takes a couple of seconds. It thinks a little, it's basically setting up Visual Studio. Visual Studio comes up, and you see here what it just did. It went ahead and, it says sign in to Office 365, I'll do that in a second. But you see what it did here. It downloaded the entire project inside of Visual Studio. That entire app project came in here. So now I can connect it to source control if I want. And you see here, that it also hard linked it basically to my site URL, which is an Office 365 app. So, the takeaway of it here is that if I wanted to targetOffice 365 only, I don't even need to have a crazy SharePoint dev machine. If all I was doing was writing apps on Office 365, I could have done this from a Windows 8 machine. Anyway, let me go in and Sign in here. So enter username, and enter password. And now when I hit this Play button, so I'm just going to do this DEBUG, Windows, Output, so we can see what's going on. And now when I hit this Play button, what it'll do is that it'll package the app, and it'll deploy the app to SharePoint. It'll uninstall the last version, and it'll deploy the app to SharePoint in Office 365. So, I'm running everything locally over here, but I'm developing for the Cloud. That's pretty exciting. Let's give it a second. And it launches. It'll ask me to login. (Typing) And the app runs just like before, but now I'm running it, and developing it from my local Visual Studio installation. That is quite cool.

Summary and What's Next

So, a quick summarization of what we just talked about in this chapter. A very basic introduction to apps. That is how I would categorize this chapter. We looked at very little code. We understood mostly, I would say theory, as of now. We did look at some important concepts. We looked at those eight golden rules that you must memorize and be very familiar with. You must understand what each one of them mean. And we looked at how you can categorize apps, and I showed you one simple app running using NAPA. Where do we go from here? Next, we'll start writing more apps using Visual Studio, and I'm going to start by writing the simplest possible app, called as a SharePoint-hosted app, and using a SharePoint-hosted app, I will demonstrate various concepts, and try and get familiarized with the various things that we need to know about apps. A lot of those things are also applicable to provider-hosted apps and auto-hosted apps. So we'll look at those subsequently. But first we'll start getting our fingers wet by writing apps using Visual Studio for SharePoint. Thank you, and I'll see you in the next chapter.

Writing Apps Using Visual Studio

IGATE Sensitive

Page 8: Sharepoint Apps Introduction_v1

Introduction

So, in the previous chapter, I covered some basics about SharePoint apps, and in this chapter I'm going to further that discussion by taking the example of what is the simplest possible SharePoint app, which is a SharePoint-hosted app. Now the SharePoint-hosted app I'm going to write, first basically start with a crawl-walk-run approach, we'll start by writing it in a simple app that runs full screen. We'll understand how Visual Studio packages it and deploys it, how would you do in production, how things work behind the scenes, things like permissions, tokens. The idea is to get enough understanding about SharePoint apps, and once we start diving into the murkier waters of provider-hosted apps, all of these concepts that will be clear to us by then, we'll easily be able to apply them to provider-hosted apps.

Visual Studio Templates

And I'll choose to Create a new app. Now you see here that there are three different kinds of apps I can write. So, there's something called as App for Office 2013. This is that the task app, content app, runs in Office client. We're not worrying about that just yet. App for SharePoint 2013. App for SharePoint 2013 is the kind of app we'll be writing. And all the apps that I've been talking about so far can be thought of as apps for SharePoint 2013; the full screen app, client web part, provider-hosted app, not provider-hosted app, auto-hosted app. All of those are apps for SharePoint 2013. So that's the project I'll be using. And this project you see at the bottom, Cloud Business App, this is Visual Studio LightSwitch repackaged. So this is basically something that allows you to write a quick and dirty, well, I don't want to call it dirty, but a quick app that targets basically Office 365, and it's got things in it like LINQ integration, Facebook integration, and integrated to the backend database. The idea is that it shortens your development cycle, and allows you to create an app quickly enough. So, let's start with an App for SharePoint 2013. Since I'm writing the world's simplest app, I will call it Appetizer, and hit OK. Now, it gives me these various options over here. So, what kind of app do I want to write? I'm going to start with a SharePoint-hosted app. This is the simplest possible app we can write. It is wholly contained within SharePoint. We don't need to worry about an extra server behind the scenes. So, I'm going to start with a SharePoint-hosted app, and I'm debugging this on http://sp. I'm going to click on Finish here. Now while it is creating the project, let's quickly open my browser, and visit http://sp, and let's see what that looks like. (Typing) So, http://sp is a clean site, and it's a clean team site. Now, you might've heard, or read on the internet somewhere that Office, or SharePoint 2013 has introduced a new site definition, called as the Developer Site,

Developer Site Definition vs Team Site

and that is what we should be using for development. That's partly true. Not 100% true, that's partly true. I think to develop you really don't need to use the Developer Site, even though it makes one thing more convenient, which is if you want to take an app package, and deploy it by just browsing, upload, and deploy, the Developer Site definition makes that a little bit easier. However, you'll see when I use Visual Studio, I can hit F5 in Visual Studio, and it basically does that for me. So, I really don't need to use a Developer Site, and if you are using the Developer Site, it's really not a problem, so you can use whichever one you want. So I'm going to target the team site here, and I created this project.Let's quickly examine what this project looks like. I'm going to double click on this, and even though this is an XML file, it opens this tab-based editor for me. And as you can see over here in this tab-based editor, I can give a Title, and a Name, and a Version, etc. to this app.

AppManifest.xml

And you see that every app has got a Start page. So using a dropdown, I pick a Start page. I don't have any more pages in here, I've got only one, Default.aspx. So it basically tells me that this is my Start page. But there is an Elements.xml here. I thought Elements.xml had to do with WSPs. What is an Elements.xml doing in an app? Let's get to that in a second. But just remember, there's an Elements.xml here, and there is another one down here, here, and so on and so forth. But anyway, there's something called a Query string that is being sent, we're sending StandardTokens. So, if you go to my site, blah.winsmarts.com, and just Search for this, or just Search for SharePoint 2013 app replacement tokens, and you'll see that I've documented a list of all of the tokens that are available inside of Visual Studio. And for apps, as you can see, the StandardTokens that we were talking about, is basically five tokens in one.

IGATE Sensitive

Page 9: Sharepoint Apps Introduction_v1

StandardTokens and Other Query String Parameters

So what happens is that when the app gets launched, the Default.aspx is sent five things as Query string parameters. The five things are HostURL, AppWebUrl, Language, ClientTag, and the ProductNumber. So these things are sent over to your SharePoint app. So you SharePoint app can read them from the Query string, and be able to do interesting things with them. You have the ability through here to be able to tweak Permissions for your app. Also say Allow app-only permissions in Visual Studio 2012. If you've done this in 2012, this checkbox was missing. They've added this checkbox, and they've also added things like Prerequisites, like auto- hosting prerequisites, etc. But, the thing is, you still need to know what is allowed,

Setting App Permissions

and what is not allowed. Like this app-only permission doesn't make sense for a SharePoint-hosted app. So, I wish this checkbox was disabled for a SharePoint-hosted app, but it's not, so I think you still can't fly completely blind here. You still need to know some of these concepts. They'll be clear by the end of this course I assure you, but for now I'm just going to leave that unchecked. I'm not requesting any crazy permissions here, and this what my basic app looks like.See this AppIcon.png, this is the Starter location, this is the icon for my app. Basically, if I was to go into this Add an app link over here, see these icons you see over here, so the AppIcon.png would be our representation of our app's icon up here. So that's what you'll see up here. Let's go back here. Now, I'm going to Close this AppManifest.xml, and I'm going to Open this in XML View. And what you see over here is that it's basically an XML file. Over here, we can define what Permissions we want, the various Properties for the app, and something called as AppPrincipal. AppPrincipal Internal is something that you would use for SharePoint-hosted apps only.

AppManifest.xml in XML View

In provider-hosted apps, you can use it, but you shouldn't. Basically, it gives you a special principal, or an identity for the app that is accessed to anything. So, you shouldn't use it in provider-hosted apps. And you'll also see that there is something called this appWebUrl over here. AppWebUrl is, as the name suggests, the URL for the AppWeb. So when the user installs the app, this gets replaced by the newly provisioned appWebUrl. In provider-hosted apps, the token is alittle bit different. So if I go back to my blog post here, you see the appWebUrl, and the provider-hosted apps, which you'll see it'll be called remoteAppUrl. So, it's pointing to let's say your MVC app, or something like that. ASP.NET MVC, or PHP, or whatever you want. I'm going to ahead and deploy this app. Now the logic for this app is quite similar to the one you saw in NAPA. Basically there's Default.aspx, which is a Start page for my app. It's loading jQuery, etc., client side object model. It is inheriting from the SharePoint WebPartPage. It is using the default.master for its branding. So it uses a default master page, so basically it'll adopt the master page off the HostWeb, which is a the parent site here.And this page basically, this is ghostable. It includes a reference to css. There's nothing in that css, but if you need it to. Includes a link to a JavaScript that is part of our project. So if I go into Content, you will see. Sorry, not Content, under Scripts, you will see there's a file called App.js. So that App.js is where the logic for my app lives. The logic for the app is actually exactly the same as what you saw in NAPA. There's a paragraph here called message. It says initializing. And then in App.js, we're using jQuery to call getUserName when the document loads, and using CSOM, we're loading the name of the user, and we're writing that into the message paragraph. This is client side object model 101. Again, I highly recommend that you brush up on client side object model, and become experts at that. And REST API for that matter.I'm going to go ahead and hit this Play button here, and this will go ahead and deploy my app. It'll package it. Let's go to the Output tab. You see that it basically packaged it and deployed it. It's asking me to login because I'm hitting a URLthat says apps.ws.int, which is not part of my internet zone. I like to keep it that way because then I know what requests, in dev environments, I know what request is going where. So if I get prompted for credentials, it's going to the AppWeb, rather than the SPWeb, so just for dev reasons I like to do this. So let's go ahead and login. Let's pay some attention to the URLs that got created here. I'm still in Debug mode. So this is the URL for the app, and just trust me on this, the URL for my HostWeb is http://sp. You see these are completely different. The URLs are completely different. If I was to say, just for a second let's ignore the query string junk, okay. The way the app URL looks like is that there is a prefix that we decide when we basically set up apps infrastructure on our SharePoint environment, we decide what the prefix is going to be. For different tendencies, this could be different. There's an app ID, which is a hex number. It increases sequentially for every app installed on your environment, the entire SharePoint farm.

IGATE Sensitive

Page 10: Sharepoint Apps Introduction_v1

App URLs in Action

The app domain, this is what you created, the wild card seen and record for. So, what happens now is that I was to ping this URL, it points me back to the same SharePoint server. So this app is being served out of the same SharePoint server. And then it goes to /Appetizer. So essentially what's happening here is that Appetizer is a subsite of http://sp. So basically, are you saying that http://sp is the same as this? Not quite. If I was to visit this URL directly; let's try that for fun okay. So I'm going to go ahead and visit that URL directly without /Appetizer in front of it, and let's see what it does.So it's asking me to login. Let's go ahead and login. (Typing) Okay, where did that window go? Basically, it redirects me back to the Appetizer. So basically it's loading Appetizer. So, my point here is that the selected URL is not the same as http://sp. So they put some intelligence in there to redirect you back to your app. So this URL is for my app only. Now, this happens to be a subsite of http://sp. How do we know this? Let's go ahead and open SharePoint 2013 Management Shell. And we'll say $web is equal to Get SPWeb.http://sp, and I'm going to say $web.Site.AllWebs. And you see here that $web.Site.AllWebs is basically, basically tells me that there are two SPWebs contained at this location. So that's an interesting revelation. Basically this second URL is a SPWeb. That's the AppWeb, and I'm going say, well the second one,

Examining App Webs via PowerShell

it's a 0-based alright, so I'm going to say $appWeb is equal to, like that. So $appWeb, just want to make sure that I got ahold of that. I did. And now I can say $appWeb., let's say Folders. And I'm going to make a Copy of this, and I'll rename the Copy to .zip, and I'm going to Extract the zip file. And what do I see here? That is the AppManifest.xml. There is, this looks like the same format that Word, and Excel, and PowerPoint use, the open XML formats, and inside of here, there is a wsp. Interesting. Let's Copy this wsp. Let's put it over here. And I'm going to Rename this wsp to cab,because wsp files are cab files. And for us to open this, you see here, that this is just a standard wsp. In fact, it is a sandbox solution. I thought sandbox solutions are deprecated? They're not. Let me say that like once for all to make it very, very clear, sandbox solutions are not deprecated. What is deprecated, however, is client side code. That is the server side code that sandbox solutions use. User code is deprecated, but as long as your sandbox solution is 100% declarative, that is, whatever it's trying to do, it's doing it with CAML, it is perfectly okay to use sandbox solutions. Even in SharePoint 2013. Just avoid user code. Just avoid C# code in sandbox solutions. And, in this case, if you were to try and force your way to try and create server side code, it will just not run. It'll throw an error. So, you can't do that. But anyway, what you're seeing here is that there's a manifest.xml that includes a Feature.xml, and this Feature.xml uses this Element, and this Element, and this Element, and this Element, and all of these basically contain module tags to stick all of these files inside of the SharePoint Content database. So, if you open this for instance, it is putting App.css at this location.

Examining the .App File

And if you go up here, inside of the Feature, you see here that I got Pages, Scripts, Content, any of these modules are a part of this Feature, and then this Feature is a part of the package, which is the wsp. One other interesting thing you might've seen here, you see this ReplaceContent is equal to TRUE, that's pretty cool. That's a new thing they've added in 2013. So a module will override Content by default, that's useful. Anyway, so the question now is, so do we know how an app gets packaged? We know that a SharePoint-hosted app, anything that provisions an AppWeb, relies on a wsp.The question now is that let's say we've written an app, and we want to make it available to our, let's say, Enterprise App Catalog. So I want to give this dart app file, which is a zip file, but I want to give this to my IT ogre, and he's going to deploy it and make it available for all users. So, what is the end user's experience as far as discovering the app? So, first I'm going to pretend that I'm an end user, and I'll say that I want to add an app in here, that Appetizer app is really useful, so I'm going to go ahead and click on Add an app. And ideally, I would like to find Appetizer inside of here. So I can issue a Request here, or I could from my organization, I can apps inside of here, or I can go to the SharePoint Store and I can find apps here. But, as the administrator, I can handle these requests and I can make apps available for end users using the App Catalog. So, where is the App Catalog? Let's go to Central Administration. (Typing) Okay, so in Central Administration, go to the section about Apps. And here let's click on Manage App Catalog. (Typing) And you see here that I've already created the App Catalog here. Now if you haven't created it, you can create one from this page. I'm just going to go ahead and visit my App Catalog. (Typing) And if people have been issuing requests, they will show up in here. Since I don't have any requests, I can make this Appetizer app available for end users. So let me

IGATE Sensitive

Page 11: Sharepoint Apps Introduction_v1

find that app. Where was it? Nice. Right, it's over here. So I'm going to go ahead and go to my SharePoint site. I'm going to say Apps for SharePoint. And I'm going to say new app, Browse. I'm going to find the Appetizer, and I'm going to hit OK.

Deploying your App to Enterprise App Catalog

And by doing this, within this tendency, it will make this app available for all the users. And I'm going to say, A very productive app, must use! Or something like that. And I'm going to hit Save. Okay. So it tells me that this app has been made available. Now I can go in here, and, as an end user, I can hit Refresh, and it tells me that you can't add this app here. Find out why. Because I already have it on my site. So I have to first remove it. Because I was debugging through Visual Studio, so it's already there. So let's do that. So I'm going to go ahead and REMOVE it. (Typing) Click on add an app. Now let's quickly go and compare the app URLs up here as well. You see here that this app URL basically looks like this. Okay. I will write ws-, but there's a star in it is my point. This is an important limitation of SharePoint-hosted apps that you cannot predict the URL of the SharePoint-hosted app until after it has been installed. And the problem this causes is that when you're using claims-based auth. When SharePoint 2013 uses claim-based auth, so it's not when,you are using claims-based auth. When, and if you use claims-based auth, that requires passive federation, and therefore http redirects, etc. SharePoint-hosted apps cannot work in that scenario. Why? Because external STS, Security Token Services, cannot redirect back to a wildcard. They need to know what URL to redirect to. So SharePoint-hosted apps do not work with things like form-based auth. They don't work with ADFS. They don't work with Azure ACS. In fact, the only thing they work with as of now, is Windows Authentication wrapped with claims, or not wrapped claims.Actually, it can't work with classic auth, so basically just Windows Auth wrapped with claims, and that's all it can work with. It cannot work with even ADFS. So that brings me to an interesting point about the limitations of SharePoint-hosted apps.

Adding Removing Apps as an End User

Number one, the upgrade story, in general, is quite bad. It's not impossible to do upgrades, but the way you do upgrades in SharePoint-hosted apps, is that you handle these events. You go down here, sorry, up here, and let me expand this so we can read it, App Installed, App Uninstalling, and App Upgraded. And these are external web service calls. Now, if you are going to the extent of creating an external web service, that means you are creating, you're putting in the effort of setting up the web service as well. So if you need that complexity, why not just go with the provider-hosted apps? And I think you'll see that a provider-hosted app is actually a whole lot easier to do upgrades on, because you could have written the provider-hosted app in just ASP.NET, or MVC, and you don't need to write complex SharePoint decode to be able to handle upgrades. Secondly, whenever the app is installed and uninstalled, the AppWeb gets completely replaced. So any customizations, or any data that you put in the AppWeb, it is your responsibility to remember that, and re-create that after the upgrade. So the upgrade story is quite bad. Where it gets really bad is if you are doing upgrades that are storing things into the HostWeb, and then it's completely up to you. So when you uninstall the app, it is completely up to the developer to remove all those customizations out of the HostWeb.I would strongly recommend to you that you should not go crazy modifying the HostWeb from the AppWeb. Do what is necessary, but don't go nuts with it. The other thing I mentioned that cannot work with FBA, or ADFS, or basically anything that requires passive federation and redirect, so that's a huge limitation of SharePoint-hosted apps as of now. Maybe Microsoft will fix this in the future, but, as now, this is a limitation. I will talk about client web parts next, but one other limitation to point about client web parts in general. This is not just about SharePoint-hosted apps. Even if you are using client web parts with provider-hosted apps, client web parts have got some interesting navigation challenges that I'll explain more about when I go to client web parts. And then the full screen apps can also have some UI challenges because, let's come back here. Where's the app? Let me just quickly add the app again. Appetizer. Trust. Right. So, let's quickly go ahead and load this. (Typing) Now you see here that I got the SharePoint look and feel. But the page itself that I'm using actually is, it doesn't have all the paradigms that I'm used to in a typical SharePoint site. So, for instance, if I had a custom navigation that had I built in my SharePoint site, that won't come in.

Why SharePoint Hosted Apps Don't Work with CBA or FBA

The only navigation I get here is go back to the parent HostWeb, like where I launched from. Or, I have some limited ability of adding like a Help icon, and some basic navigation in here, but the apps sort of

IGATE Sensitive

Page 12: Sharepoint Apps Introduction_v1

has its own navigation, and it doesn't feel like it's a part of the same SharePoint site you came from. Secondly, whenever we write code, we want to be able to give the user a URL, and the user hits the URL, and starts using the application we're writing. What happens in this scenario is that you give the user a URL to your SharePoint site, and then tell him to look for the app. Like this. And then they click on that, and then they go to the app. So there's an extra click involved. With provider-hosted apps, you can avoid it a little bit. But, with SharePoint-hosted apps, you have to go through that extra step, because you don't know the URL ahead of time. That's the biggest issue. The third thing is that this whole area is a white canvas. It's completely in your control. That's both good and bad. It's bad because over time, which you'll see, is that a lot of people are going to invent, or reinvent the wheel in different shapes. So somebody will create a square wheel. Should I have a quick lunch here, or not. Should I create something up here, or not. People are going to create different kinds of user experiences for different apps, and there will be a lack of consistency in that. So, that's somewhat of a concern. And then, obviously one of the biggest limitations of SharePoint-hosted apps, is that they can't use any

Limitations of SharePoint Hosted Apps

server side code. You cannot instantiate an action from the server without the initiation of the user, like a timer job, or something, that is entirely in the control of the server, and it causes something to happen in SharePoint. You can't do that with a SharePoint-hosted app. Every action must be started by the end user. What if you need server side code? If you need server side code, we do something called as we write as a provider-hosted app. Now before I dive into provider-hosted apps, I would like to talk about some more concepts about apps that are applicable to both SharePoint-hosted apps and provider-hosted apps. And those concepts are client web parts, and custom actions. So the next chapter I'll be extending this Appetizer example, and I'll be writing client web parts, and I'll be writing custom actions. 

Client WebParts and Custom ActionsIntroduction

in this chapter I'm going to be talking further about SharePoint apps, and so far I've talked about basics of SharePoint apps, golden rules, etc. We saw how you can write a SharePoint-hosted app using Visual Studio, how you can package such an app, how you can deliver such an app to your IT ogre so he can deploy it. And next we're going to talk about a concept called as Client Web Parts and Custom Actions. And remember, everything that I'm talking about here is applicable to both SharePoint-hosted apps, and provider-hosted apps. So, both SharePoint-hosted apps and provider-hosted apps can work as client web parts, and can work as custom actions. But it's easy for me to demo that using SharePoint-hosted apps, so first we'll solidify our understanding using SharePoint-hosted apps, using client web parts, and custom actions with SharePoint-hosted apps, and I think you'll find it very easy to extend that knowledge to provider-hosted apps.

Different UI Options for SharePoint Apps

What exactly are these? When the app occupies the entire browser screen, that's called as a full page immersive app. That's the user experience we saw so far. But users are quite happy to use a web part. That's what they like about SharePoint, that they can put the page in a RIP mode, and they can drop a web part, and get some compelling functionality out of it. Apps can also work like web parts, but remember this is a pretend I'm a web part, as in it's not a real web part. It is a glorified IFrame, and that glorified IFrame in the SharePoint user interface looks and feels like a retarded web part, a web part that doesn't have all the facilities of what web parts have. Like, it doesn't have a very nice editor to it. There's no concept of two client web parts talking with each other, and so on and so forth. But you can put the page in a RIP mode, and you can drop the web part that contains an app, and we call it an app part, or client web part, it's the same thing. And the third scenario is a custom action, and as you know what a custom action is, it allows you to create links at various places in SharePoint, and you can launch an app using a custom action. So let's see this in action, how to write a client web part, how to write a custom action in our apps as a client web part, and a custom action. So again, why client web parts? Because users still like the idea of web parts. They want to be able to put a page in Edit mode, and drop a web part, or two over there. And users may want to customize the properties of what they deployed, and they want some functionality to change that way. You can do that with apps

IGATE Sensitive

Page 13: Sharepoint Apps Introduction_v1

also. It's a little bit more limited than what you can do with full-fledged web parts, but you can do a little bit of customization at runtime by the user with apps as well. So, again, let's look at a demo, and understand how this works.

Demo Client WebParts

So, I'm going to extend the project that I had basically created in the last chapter, which was just a simple Appetizer project, creates a simple SharePoint-hosted app. And I'm going to add a client web part to this project. And it would be a good way for me to demonstrate how to add a client web part, and the challenges you might run into it, and so on and so forth. So how do we do that? So right click, Add, New Item, and I'm going to choose to add a Client Web Part. So, let's just call it ClientWebPart1. Well, actually let's call it AppetizerCW. Let's give it a nice name. And I'm going to hit Add.So, it's asking me a question here. Its saying, do I want to create a new web part page, or do I want to pick an existing page? I'm going to go ahead, and I'll create a new page, and there's a very good reason why I'm doing this. Because, it's a user interface thing, so the Default.aspx that is selected down here, that's the only other page I have here, that Default.aspx has got a lot of other junk in it, like the branding, etc. So, I don't want that junk to appear inside of the web part, but I can demo that even by going afterwards, and I can choose to include that page, change the target for this page. So, I can demo how that page would look like in a client web part even afterwards. But for now, I'm going to go ahead and add a new client web part page, and click on the Finish button.

WebPartPages AllowFraming Control

Now one thing you'll see that immediately jumps out at us is this control up here. This control up here is basically telling us that it is okay for this page to be put inside of an IFrame. A regular SharePoint page, you can't put it inside of the IFrame. Basically, the browser won't load it. But, if you were to throw this control in there, WebPartPages Allowframing, then you could throw in this particular page inside of an IFrame, and remember, a client web part works by putting things into, by putting this aspx inside of an IFrame. Okay, so my project is completed as you see here that I've addedthis AppetizerCW, and I also went in and added some logic inside of here.

Elements.xml for the Client WebPart

So, let's quickly examine this Elements.xml that is pointing my page, my app to the client web parts page. As you see here that the page I'm pointing to is AppetizerCW.aspx. I've also added some query string variables at the end. And these query string variables, each one of these correspond to these Properties I have set down here. See this? Now, these Properties are of different data types. So they're all WebBrowsable true. They have a Name, Description, and so on and so forth, and they have a DefaultValue, like that. This is a Boolean, that's a string, TRUE, integer, and this is an enum. The idea being that whatever these Properties here show up in the editor zone when the user puts the client web part in edit mode. So, at runtime the user is able to change the color from blue to red, for instance. And whatever values the user picks, are sent in as query strings to the client web part. So one thing jumps out at me over here, is that we can't really write a custom editor, or some people call it a tool part, for a client web part. And that is true. In the current release of SharePoint, and the way it sits right now, you cannot write a compelling custom editor. So that's something to keep in mind. You can have some limited customizability, this is what you can do what I just showed you, but you can't write a custom editor. Anyway, let's go and open this AppetizerCW.aspx. I've enhanced that code a little bit as well. So let's go to Pages, and open this AppetizerCW.aspx. And what are we doing here? In this over here, what I'm doing is that I have shown an input button, and what I'm doing is that I'm reading the Color Property that was passed in over a query string, and that Color Property, I am setting the background color of my page to that Color Property passed in. So let's go ahead and Run this. (Typing)

Deploying and Running the Client WebPart

I've also modified the Default.aspx to write all the query string variables. We'll come back to this in a second. Let's go back to the SharePoint site. I'm going to put this page in an Edit mode. And I'm going to drop my client web part. So I'm going to go to App Part, or I can go to Web Part, and go to Apps, and find the same web parts, the same thing. And I'm going to click the Add button. And you see here that it shows me my client web part running over here. Looks pretty nice and clean. I'm going to Edit this

IGATE Sensitive

Page 14: Sharepoint Apps Introduction_v1

web part. And you see here that I can have this Custom Properties. I can't really control the sort order here. This is not the sort order that I had specified in my Elements.xml. So, it's basically alphabetical. And I'm going to go ahead and change this to Yellow, hit OK. And now if I Change Color, the background color changes to yellow. So I have some limited customizability in the way I can present this info. But, I'm going to do a little trick now. Let's go ahead and Delete this web part, Save, and stop editing, debugging.

UI Challenges in Using Default.aspx as Your ClientWebPart Page

Now I'm going to go and cheat a little. I'm going to go to Elements.xml, and I'm going to change the URL of my Content here, to, lets change it to Default.aspx/Pages/, let me make sure that was a page, yeah, Default.aspx. And that's basically it. So I'll just change it to Default.aspx, and let's try and Run it and see what it does. Now I'm going to try and read on this app as a client web part, and let's see how it fairs. (Typing) Now it looks like this over here. I'm going to Open a New Tab here so I can the two side-by-side. And I'm going to go ahead and put Appetizer as a client web part (Typing) on the surface of the page. And let's see how ugly it looks. Look at this. It looks awful, absolutely awful. Why? Because it looks like it's doubled up all the branding. So, the problem with this approach, now you see here that the query strings, etc., are also different.

Communication Between Parent and Client Using SenderId

We're getting in this curious little query string here called SenderId that I hadn't seen before. The purpose of the SenderId is that there's an API built inside of SharePoint that sends a SenderId, so the parent page sends a SenderId, using which the client web part can now talk back to the parent. Why would that be necessary? Now see the issue over here is that, imagine if your app was more than just one page, and you're going Back, and Next, and Back, and Next through the pages, and the user wishes to be able to bookmark the page. Well, this query string above is not getting affected with whatever you're doing inside of here. But you could do deep linking by, and in forming the top page, and having some JavaScript in here to put a hash in front of this URL, like Backbone.js, and Angular.js, these frameworks allow you to do that. For Ajax-based pages, how do you bookmark them? There're standard ways of doing that. But the SenderId, that's an example where you would use it. Another example where you can use this is, or actually you would have to use this is.

Sizing a Client WebPart

See the client webpart has a defined width and height. So it's got a Default Width and Height. This is 300 x 200 work units, pixels, 300 pixels by 200 pixels. I can't say 300%. I can't say 50%. I can't say anything else except pixels, and that's a problem, because when you can't predict the height and width of the Content, especially if the dimensions of the Content might change, then your client web part is going to show these really ugly scroll bars. I'm sure your users don't like that. So, let me actually show you one quick trick, and then we can sort of drive the point home of how bad thesescroll bars look.

Using IsDlg to Reuse AppPages in Client WebParts

So for the Appetizer, I'm going to go ahead and add that is DLG equal to 1 over here. So I'm going to say IsDlg equal to 1. And if you know from SharePoint 2010, what happens is that any page that you put IsDlg equal to 1 in front of, what SharePoint will do automatically is that it will strip out all the chrome. So like the ribbon, and all of that. Basically, anything that is decorated with a class S4-NotDlg gets removed in the rending UI. So, I'm going to use a little trick, so hopefully that will make my page look a little bit nicer. So let's wait for this to deploy. (Typing) And I want to see this as a client web part. I'll Open a New Tab here. (Typing) And I'll go ahead and drop that web part as. (Typing) Okay. So you see here that it's better than before. It's not perfect, but is better than before. I mean, I can't really scroll this very nicely. So there's a little trick how to scroll this. Basically you hold your mouse down here and scroll downwards. Not really nice, but I can at least see the values here. So, there is some scope that I have over here to be able to write one page,and use it both as the landing page full screen UI for my app, and also as a client web part. I would use concepts such as responsive design. So basically whatever resolution is thrown at me, my page will adjust itself to accommodate for that resolution. But sometimes you do need to resize the page. Sometimes you do need to be able to say, my web part is 400 pixels, and I want to get space equal to 400 pixels. How would I do that? So, the

IGATE Sensitive

Page 15: Sharepoint Apps Introduction_v1

challenge that we're dealing over here, is that I cannot specify a flexible height and width to the client web part. This has to be in pixels, and fixed at the time that I'm coding. So, if I'm thrown an example where I want to be able to dynamically restructure the size of the client web part, how would I do that? The answer is, some very little JavaScript that you need to drop on your page. So, what we're doing in this JavaScript is when the document loads, get the target, which is the parent. And then we say target.postMessage, and then we send this carefully crafted up XML structure in which we give the SenderId. And the SenderId is one of the query strings that we had received. And using the SenderId, we can say resize, and then we give our width and height to the parent, so then this code will run in the parent. And as a result, it'll resize our window. So this way, when we throw different resolutions, and different dimensions of our web part, client web part to the SharePoint page, it is able to accommodate for our page. So let's go ahead and drop that as a page right here. And as you see here, that now the width and the height of the page has been adjusted. It's sort of hard to see it this way, but if I was to developer tools, (Typing) it has automatically resized the size of my web part, as you can see. Cool. So, this is as far as client web parts go.

X-Frame-Options

So, the important thing that we learned over here is that a SharePoint page doesn't automatically allow itself to be put inside of an IFrame. It would probably give an error. And for a SharePoint page to be able to put inside of an IFrame, you need to put this WebPartPages:AllowFraming control on any particular SharePoint page. So that's an important thing that we need to remember.

ClientWebPart Limitations and Solutions

There are some challenges as you saw with client web parts. Bookmarking becomes difficult. Being able to deep link within an app becomes difficult. Resizing the client web part becomes difficult, and there are solutions to all of these problems. So there's a well-defined HTML5-based communication API using the SenderId that you can use to get around these problems. Great.

Introduction to Custom Actions

Next, let's talk about the other kind of UI that SharePoint apps support, which is being able to launch an app using a custom action. Now, where would you find a custom action launching an app useful? Sometimes you maybe want to create a button in the ribbon that says, download this list as an Excel file. Or, convert a document to a PDF. You want to put that link in the custom action, or the ECB menu using a custom action. Those are scenarios in which you probably would find writing a custom action very useful. Custom action launching an app very, very useful. So, how exactly can we enhance our app so it has a custom action that you can use to launch an app?

Adding a Custom Action to an App

So with our app open in Visual Studio, I'm going to say right click, Add, New Item, and I can choose to add either a Menu Item Custom Action, or I can choose to add a Ribbon Custom Action. So depending upon where I want my custom action to appear, I can choose to add the custom action in different places. So, in this case, I'm going to go ahead and choose to add a Menu Item Custom Action. And for fun, I will call it AppetizerCustomAction. Click on Add. So it's asking me, where do I want the custom action to appear? In the AppWeb, or the HostWeb? So, see this is interesting that I can make my custom actions appear in the HostWeb also. And I can choose to say, where is this custom action scoped to? So I can say it is in the List Template, and it is in, let's say, Custom List. So I can define where my custom action appears. I can hit Next, and I can give it text to my custom action. So, in this case, my text can be, Launch Appetizer. And I can tell it that this custom action is going to load a certain page. So, I'll say that I want to load the Default.aspx, and click on Finish. And that's it. My custom action is done. Now, so what I'm going to do here in order for me to be able to test this, I'm going to go ahead and also create a list inside of SharePoint site. So I'm going to say Site Actions, Add an app, and I'll choose to Create a Custom List, put some data in it. Because I'm hoping to see the custom action appear inside of here. (Typing) And I'm going to go ahead and deploy my custom action. (Typing) So let's click on the Start button. (Typing) And let's go ahead and login. (Typing) And you see here that the app runs as is, to be expected, but what's really interesting now is that if I go into my site, the HostWeb, and I go into this list that I've created, and I click on this button here, I see a custom action here called Launch Appetizer. And here's another way that I have the ability to now launch my

IGATE Sensitive

Page 16: Sharepoint Apps Introduction_v1

app, and the ListItem and the ListId that this action was launched from, those are passed in as query strings to my app. So now the app knows where it was launched from, so it can look at that item and do some interesting things to it.

Launching Custom Actions as Dialogs

Custom actions can also be launched, it can also launch an app as a dialog. So, right inside of here, I can say something like HostWebDialog. Now this is not going to appear in your IntelliSense unfortunately. I wish they'd added that in Visual Studio 2013, but they didn't. So I'm going to say HostWebDialogHeight is equal to 500, and I hope I'm not mistyping this HostWebDialogHeight. Yeah, looks okay. And let's say HostWebDialogWidth. (Typing) Doesn't show up in IntelliSense, that's a shame, but it works. So I'm going to hit the Start button again, (Typing) Let's go ahead and login. (Typing) And I'm going to go ahead and go to the parent site. Go Test, and I'm going to go ahead and Launch thecustom action from here. And you see here they're the same app. Just ignore this, it's just some debugging issue. But you see they're the same app, launches as a dialog now. Again, you get the SPListItemId, SPListId, just like before, but now we're able to launch this as a dialog. And that's pretty cool. So, I'm pretty sure you'll probably find some other reasons why you want to use custom actions, or client web parts, or one over another. The one thing I'll say about client web parts is that because they live as an IFrame, you should be very careful of putting secure information in them.Basically, what you have to assume is that the parent page can access anything inside of a child IFrame. So, a malicious user could hit F12 and find some sensitive data, like say if your OAuth's secured into some other system, then you need to make sure that that key is protected, and really with JavaScript, you can't 100% protect the key. So there are some considerations that you have to keep in mind.

Summary

Anyway, so you saw a quick demo of custom action, a quick summary of what we just looked at so far. We've looked at apps basics in the first chapter. We looked at NAPA in the first chapter. We looked at SharePoint-hosted apps in the second chapter, and in this module we looked at client web part, how to write one, what are the limitations of it, what are the common workarounds, and we looked at the ability to write a custom action, and the ability to launch a custom action as a dialog. So, at this point, I think we have a fairly good understanding of what apps are. But the only kind of app we have seen so far, is a SharePoint-hosted app. A SharePoint-hosted app is nearly not enough. So, practically speaking, you'll be writing also a lot of provider-hosted apps. So, everything that we've learned so far, how to write a client web part, full screen UI, custom action, all of those concepts are applicable to provider-hosted apps as well. So, in the next chapter, I'll be talking about how to write provider-hosted apps. 

Provider Hosted Apps Client Side CodeIntroduction

in this chapter I'll be talking to you about SharePoint 2013 apps, and specifically I'll be talking about the basics of provider-hosted apps. This is where you need a backend server, in addition to the pure JavaScript code that you might have. So, what have we covered so far? So far, the kind of app that I've been demonstrating to you was a SharePoint-hosted app, so everything was contained completely inside of SharePoint, and the only choice you had over there was that you had to implement your logic in JavaScript. But the advantage you had is that you didn't have to set up a server behind the scenes. Using SharePoint-hosted apps, I also demonstrated a couple of interesting concepts around UI, full screen apps, client parts, and custom actions. Those concepts apply to provider-hosted apps as well. So, I will not be covering them again, but just remember that those concepts also apply to this chapter, and whatever you can learn here as well. So what are we going to talk about next?

Kinds of Provider Hosted Apps

In this chapter, and in the next, I'll be talking about provider-hosted apps, which means apps that have server side code, or potentially a backend server that you need to set up, or is set up for you, and I'll be talking both in terms of On Premises apps, where SharePoint is installed On Premises, and in terms of Office 365, where you're running SharePoint in the Cloud. There are two kinds of server side

IGATE Sensitive

Page 17: Sharepoint Apps Introduction_v1

hosted apps. One is called as provider-hosted apps where you set up the server yourself. So you would set up the server ahead of time. This is something that you would finduseful in On Premises, or Office 365, where you set up the server. And the second is auto-hosted app, where a server side area is created for you every time the app is installed. So, the one major difference between provider-hosted and auto-hosted is provider-hosted gives you the facility of one installation of the server side code serving numerous installations of the app. But it does some with a little bit of an extra headache that you have to set up the server yourself ahead of time. Whereas the auto-hosted app is, if the app gets installed 50 times, then you have 50 server side areas provision. And it's really not that much of a hassle to manage those because all of those 50 areas are carbon copies of each other. So it's not like you have to go set each one of them up yourself. You basically make the process quite automated, and when the app is uninstalled, that area is removed for you. And, in this chapter and the next, I'll be covering again a crawl-walk-run approach. We'll be talking about the Visual Studio experience. Now behind the scenes, there's obviously a lot more going on that are things around security that are in play over here. There are things around how an app is authenticated, how is the user authenticated through the app, and all of those. I won't be covering those concepts, but let's get the basics behind us, and then I'll dive into the security aspects of the app as well.

Why Use Provider Hosted Apps?

The obvious question is, why would you want to use provider-hosted apps? Well, where you need server side code, that's a pretty good reason why you would want provider-hosted apps. Example, like a timer job, or a web service, or something like that. Now, that's not the only situation where you would want provider-hosted apps. If you want to use technology, such as MVC, ASP.NET MVC, or perhaps you have existing investments, you have a big existing application like the equivalent of an Amazon or com written, and you want that to work as a SharePoint app. So you don't want to rewrite the whole thing in ASP.NET WebForms running inside of SharePoint. You want to be able to just leverage what you have, and hook into the value, and the power of SharePoint while keeping your code outside. And, I think some of us might agree that things like TDD, and better design patterns are also possible if you use other playtrons, like SharePoint can be a little bit unwielding, even when it comes to things like automated testing, and so on and so forth. So if those things are important to you, maybe you want to use apps. Maybe your existing skill set in your company is not SharePoint. Maybe it's ASP.NET, or something else, and that's where you might want to use apps, provider-hosted apps. And also provider-hosted apps open up a lot of other scenarios for you. For instance, you get a couple of security-related scenarios, like you have something called an App Only permission. So, generally speaking, when you're working inside of apps, both the user and the app must have permission to do something for an action to succeed. That is the default behavior. But, provider-hosted apps give you yet another choice where the app can dosomething, even if the user didn't have the rights to do it. Now this is allowed only through server side code, but that is something that, because the restriction is that only server side code can do this, it is something that is restricted to provider-hosted apps. Similarly, we've got something called as "on the fly" permissions, where the app itself didn't have certain permissions, but the app can temporarily ask the user to grant the app permissions for an hour. And as long as the user has the permissions that the app is asking for, the user can grant those permissions. These are called as "on the fly" permissions, and this is also something that requires provider-hosted apps.

How do Provider Hosted Apps Work? Server Code

So the question is, how does this work? Now obviously you've got server side code involved here, but when I say server side code, or basically when I talk of any code interacting the SharePoint in SharePoint apps, I'm always talking about REST and CSOM code. So any code that we're going to write in apps that is going to talk with SharePoint is SharePoint REST and SharePoint CSOM code. So even though this is server side code, do not confuse it with server side API. But generally speaking, the way server side code would work is that the browser would make requests to your app server. This is not the SharePoint app server. The app server is the ASP.NET server, the PHP server, that you've set up on site of SharePoint. And this server can then talk into SharePoint under the predefined rights of the app. So think of it this way, that perhaps this server, or perhaps a vendor, has been given the responsibility of writing five or six apps. In that case, what happens is that every app becomes a client. Therefore it has a client ID. Also runs an app ID. And the vendor, or the server, can have an issuer ID. So, the issuer is pretrusted inside of SharePoint, and the client, or the app ID, has been given certain rights. So you have a one too many relationship between an issuer and a client. So, the reason I bring this up is because you have to trust, SharePoint has to trust the app, and the server ahead of

IGATE Sensitive

Page 18: Sharepoint Apps Introduction_v1

time. And this trust is done using two mechanisms. You can either use OAuth2, or you can use S2S trust, Server to Server trust, and it's all based on certificates, and secrets, and so on and so forth. I'll cover those details in the next chapter, but for now, just remember that some preset up has gone ahead of time into making this picture work, where the other server has been trusted by SharePoint.

How do Provider Hosted Apps Work? Client Code

The other scenario obviously is that your browser, even though it's a provider-hosted app, it wishes to use JavaScript, or some sort of client side code to be able to talk to SharePoint. In that case, the logic is actually very, very similar to what a SharePoint-hosted app would do, so you will need an AppWeb in that scenario. And your calls are proxy through the AppWeb into SharePoint. Now, there is a mechanism built over here to enable these cross-domain calls, and this mechanism is specific to SharePoint, and it is built in a way that it allows SharePoint to identify the app that was installed, and therefore not allow these requests to do more than what they should have been doing. So, the important distinction over here is that provider-hosted apps, or even auto-hosted, these apps have to choose between server side code, or client side code. So if you're using S2S trust, some people also call this high-trust apps, so if you're using high-trust apps, you're using S2S trust On Premises, then your app has to choose between server side code, or client side code. The same app cannot use both of them at the same time. Some people use a workaround where basically even ifthey want to use client side code, the proxy that requests from the server side. So I've written a CodePlex project called spwtf.codeplex.com, and you can download an example of that code from over there if you're interested.

Challenges and Questions with Provider Hosted Apps

So, this brings up a number of questions in my mind, and I'm sure yours too. You're writing this app in let's say PHP. Now, the SharePoint-hosted app that we wrote earlier, was using the Default.master page, and it was inheriting from SharePoint web part pages. So, branding that wasn't a challenge because it was just a subsite, and it would just inherit the master page being used by the HostWeb. Here it's a little bit different. Because you are literally writing this app in a completely different technology. Maybe its .NET, maybe it's not. It's certainly not SharePoint. How does branding work? How does security work? How do we make sure that the app has got certain rights to do certain things, and it doesn't get around those rights? How do we ensure that? Can I use REST, or CSOM, or both? I think I've sort of answered some of these questions already. And, can I use server side code, and client side code at the same time? So the answers are branding works with something called as the chrome control. This is a standard part of SharePoint JavaScript, and I'll be demonstrating this in this chapter. So chrome control is an important concept where you want your app website to appear like SharePoint, and understand and adapt that look and feel, you would use the chrome control.How does security work? Security works using OAuth or S2S trust. You have to register the app, or the issuer ahead of time, so that's something you have to do. Can I use REST, or CSOM, or both? The answer is yes, you can use either/or however you wish. But the only restriction you have to remember is that for high-trust apps, and by that I mean On Premises S2S trusted apps, you have to pick either server side code, or client side code; the same app cannot use both at the same time. By both, I mean server side code and client side code, both of them talking to SharePoint. You can use JavaScript. It just can't talk with SharePoint if server side code is talking with SharePoint. And there is a restriction, and why this restriction is there is it will become clearer in the next chapter.

Key differences from SharePoint Hosted Apps

So some key differences from SharePoint-hosted apps. For provider-hosted apps, you set up the server ahead of time. The URL is predictable. So you know where the app is going to run ahead of time, and that is somewhat of an advantage, because then you don't need to set up wildcard CNAME records. Now for auto-hosted apps, that's not true, because auto-hosted apps, an app area is created for you whenever you install the app. So, in auto-hosted apps, you can't predict the URL ahead of time. But for provider-hosted apps where you set up the server ahead of time, the URL is predictable. I think provider-hosted apps, or even auto-hosted apps, are a little bit easier to maintain and upgrade than SharePoint-hosted apps. So whenever I'm writing a relatively more complex project, I prefer to use provider-hosted apps, simply because of the flexibility they offer me. Like in ASP.NET, you can do ASP.NET MVC. With TFS you can do cruise control, etc., and continuous integration. It is really nice to be able to bring all of that power into SharePoint, and therefore be able to support bigger, more

IGATE Sensitive

Page 19: Sharepoint Apps Introduction_v1

complex projects that way. And there are some other security choices that SharePoint-hosted apps make available, sorry, that provider-hosted apps make available for you, like app only permissions, and on the fly permissions. So let's see some demos. What I'm going to do in this chapter is that I'll be showing you two demos. And through these demos, I will demonstrate three things to you. Number one, we'll be using REST API from client side code that is JavaScript only. Number two, we'll be using CSOM, Client Side Object Model,again JavaScript only. And in one case I will do it without any branding, and in the second case I will show the example with branding. And by branding, I mean the chrome control. Now, the reason I put branding in the CSOM project is because once you have the concepts clear, then we can sort of kill two birds with one stone. But remember that branding can obviously also be applied to REST API, and you can mix and match REST API in your JavaScript code, no problem. But I have created a couple of examples, and I'll be walking you through some practical scenarios that you'llsee that you'll run into, and we'll build the demo as go. Some of the things won't work, and I'll explain why they're not working, and I'll explain the reasoning for why I'm doing certain things.

CORS and why that does not Apply to SharePoint

A little bit of background before we dive into this. There is something called as CORS, C-O-R-S. Any of you who work with cross domain in JavaScript, you might have heard this name. CORS does not apply to SharePoint. Cross domain calls, the way SharePoint has chosen to implement cross domain calls is not the same as CORS.

Demo using Cross Domain Calls in SharePoint

The way SharePoint's cross domain calls work is completely different. What we do is that we, in the app, we know the HostWeb URL. So, from the layout's directory of the HostWeb URL, we can pull in a file called as SP.RequestExecutor.js. And then with the help of this SP.RequestExecutor.js, our page basically creates an IFrame that is hidden. And this IFrame loads a page called AppWebProxy.aspx. And imagine this that your app has already beeninstalled under certain security permissions. So let's say your app has got ability to read, but not to write. So what happens is, through SP.RequestExecutor.js, that request is funneled into the IFrame. From the IFrame, that request executes on the server. Now, at that point, the server knows that this request is coming from a certain app, and therefore it allows a certain request to succeed, or not succeed based on the permissions of the app. So, the request goes from your app, in the browser, into the IFrame, from the IFrame to AppWebProxy, and then it executes on server side, results come back, they come out of the IFrame, and there is also a return to your app. And all of this magic is done by SP.RequestExecutor.js. It sounds complex, but it really isn't. Because SP.RequestExecutor.js hides all this complexity for us. So with that background, okay, so just keep this in mind. What's happening here, there's an IFrame, there's a client side library, and we are basically sending requests into the IFrame, through which we send them to AppWebProxy.aspx, and they run on server side. And then they come back, and that's how we get our results. So, with that in mind, let's start by looking at using REST, again JavaScript only, with the no branding, a simple example using REST API with JavaScript only. So, what I intend to do is that I'm going to write a simple REST-based code over here, targeting this site here. This is a plain vanilla team site. I've removed all the default web parts it comes with, and I'm going the write a provider-hosted app. So, I'm going to start Visual Studio. I'm going to create a New Project. And I'll create an app for SharePoint 2013, and let's call this CrossDomainREST. I'm going to hit OK. Now, I'm going to choose to make this a provider-hosted app. And typically speaking, in a provider-hosted app, when we're, especially in development environments, I'll click a Next button, and I'll choose one of these options, etc., but I don't intend to write any server side code yet. We'll do that in the next lecture. But, in this particular example, I'll just hit Finish, because I really don't care about the server side code. So let's wait for this project to get created. (Typing)

Overview of a Provider Hosted App Visual Studio Project

As you can see in this project, in this solution I have two projects now. Now compare this with a SharePoint-hosted app where you had only one project. In this example, the top project over here is what packages up my app. You see there's an AppManifest.xml layer. And the second project is a simple ASP.NET site, and this is basically where the logic for my app goes. Now the code for this is written in a manner as if I was going to use server side code, which I'm not going to. So, all the server side code elements, SharePointContext.cs, TokenHelper.cs, Default.aspx, I'm just going to go ahead

IGATE Sensitive

Page 20: Sharepoint Apps Introduction_v1

and Delete these. Now typically speaking for a provider-hosted app to work, there are some additional steps you have to go through, like you have to create a certificate, and register it online. All that is necessary only if you're using server side code. So we're not going to worry about that yet. Now, in this code, just to prove that everything that I'm doing is purely client side, I'm going to go ahead and add an HTML file inside of this Pages directory. So to do that, I'm going to say right click, Add, New HTML Page. And I'm going to call it REST.html. In addition to that, I'm going to go ahead and create a JavaScript file inside of the Scripts folder. And I'm going to call this REST.js, so I think you can guess what I'm after over here. I'm going to write my logic in REST.js, and the frontend of my application is going to be this HTML file.Now what you'll see shortly is that there is a little gotcha that we have to worry about, that you really can't write an app in pure HTML, not without 0 configure at least. But we'll see what happens when we write the app in HTML. For demo purposes, this is fine, but you'll see a limitation very shortly. So, first let's start by modifying my HTML file. Let's give it a title, Cross Domain REST, and let's include these JavaScript files that we'll be using. So I intend to use jQuery, and I intend to use this REST.js file that I just created up here. Great. So that's a good start. Let's also make this file, this HTML file, as the Startup file for my app. So I'm going to go AppManifest.xml, and this Default.aspx, we just deleted it, so it doesn't exist anymore. I'm going to change this to REST.html, and hit Save. Now you see that I'm still passing in the StandardTokens, and everything else is the same as before. So now, this REST.html is going to get loaded soon as the app comes up. I'll go ahead and add a div over here, and I'll call it, let's give it an ID of listsList, and the purpose ofthis div is, or the purpose of this app is that it is going to query the HostWeb, and it is going to get me a list of all the lists that exist in the HostWeb, and it will write them out inside of this div. So the logic to do that is going to go in REST.js. So let's start writing REST.js. So the first thing I need in REST.js are two variables, to host the hostweburl, and appweburl.The next thing I need is a function that'll get called soon as my page is loaded. So, I can do that easily using document.ready element. And here, I need to fill in the hostweburl and the appweburl. Now, because the hostweburl and the appweburl are being passed into me as StandardTokens, actually you'll shortly see that the appweburl is actually not being passed in, but for now I'm just going to pretend, like it is being passed in. So, I'm going to basically extract those query string variables using a Helper method that I will write inside of my file. So I have extracted the hostweburl, and the appweburl. The next thing I need to do is that I need to load SP.RequestExecutor.js from the hostweburl/_layouts_15. And once that SP.RequestExecutor.js is loaded, then I can start executing my code. So, I can do that with these two lines of code that I just added. So you see var scriptbase is equal, so I'm getting a created URL where all the helper script files are, and I'm loading SP.RequestExecutor.js. And when that file gets loaded, it is going to call a method called execCrossDomainRequest. And this is where our logic can go.

How to Write Cross Domain JS REST API Calls

So, let's start writing our logic. First thing I have to do is that I have to create an object called as executor. Now executor is, it's not somebody who kills somebody, it's basically what, an executor takes your request from your outside of SharePoint page, and translates it through AppWebProxy, and through that IFrame, and so and so forth, and it is able to send that information along. So, how exactly does it work? We're going to say executor., IntelliSense is great, so I'm going to say executeAsync. Well, I spoke too soon because IntelliSense is not helping me here. But anyway, and I can go ahead and start writing some interesting code here. So the first thing I need is a URL. Where are we making this request? So this is going to be a simple get request, and it's going to made to a URL that looks like this. So, it's going to appweburl+_api SP AppContextSite target hostweburl. So we're getting lists of, we're targeting appweburl/_api, but we said at @target hostweburl. This is how I can tell executor.executeAsync that I intend to make a call to this hostweburl.Now, the assumption here obviously is that your app has permissions to be able to make this call. The next thing I need to be able to do is that I need to be able to tell it that it's going to use a method called GET and pass in these headers, since we're working with JSON. And then I will simply have a success function, (Typing) and I will have an error function. (Typing) There we go. Now, let's start writing the success function. Assuming that the data variable now gets our data, how do we parse that data? I can do something like var jsonobject is equal to JSON.parsedata.body, and then once I've gotten that data, hopefully this will be a list of all the lists that I care about, I can easily iterate through them, through the jsonobject.d.results object, and I can craft up this html.Text object, and put that inside of the div that is already there in my REST page. Now again, this is pure HTML.

Disabling SSL for Dev Purposes

IGATE Sensitive

Page 21: Sharepoint Apps Introduction_v1

To keep things simple, I'll also go ahead and disable SSL over here. The only difference SSL makes right now in dev purposes is that it makes my life a little bit more inconvenient, because my SharePoint site is not on SSL, so to make life a little bit more convenient, I change it from SSL enabled to false. Obviously in production you'll never do that. One golden rule with apps, anything, everything has to be SSL in production. I'm going to go ahead and Run this and you'll see that it'll throw an error. Let's see that error.

Provider Hosted Apps Cannot Run as Pure HTML apps in IIS

So, I'm going to hit Play. It's going to deploy the app. See, it created a system called client ID. You'll find this useful in provider-hosted apps that use server side code. We're not there yet, so we won't worry about that. So, it's asking me to trust this app. I'm going to hit Yes. And it says Method Not Allowed. Now, this is an important consideration. What's happening over here is that the process of launching an app, basically issues a POST request to the Start page of the app. And IIS by default is configured to not allow POST request to be sent to HTML pages. Which is why we're getting this error. Now, we really don't care about that POST request, so I'm just going to come up here, this is just testing, so I'm going to hit Enter to issue a GET request.

SPAppWebUrl Requires Provisioning of an AppWeb

And you see that I'm getting an error over here. So, I'm just going to continue, but we'll debug this, and we'll see what the error is. I'll set a breakpoint over here. Now, remember Visual Studio is attached with a browser so I can debug this.So let's go ahead and Refresh this one more time. And let's see what it looks like. So I say hostweburl. It looks like that I can get the hostweburl. AppWeb, that is null. Why is that null? It is null because there is no AppWeb.

Creating an AppWeb in Provider Hosted Apps

You need the AppWeb to be able to use JavaScript. So, what I'm going to do is that I need to force the AppWeb to get created. So, I'm going to right click here, Add, New Item, and I'll just go ahead and add anything, so I'll just go ahead and add a Module, and this is something that it's there, just to force the creation of the AppWeb. I'll never use it, I'll never look at it again, but this just gives me an AppWeb so I can proxy my request through that. That's the only purpose of it. Now, let's Run it again. (Typing) It's installing. (Typing) Launches the browser. I'm going to Trust the app. Again, the same issue, hit Enter. Now hopefully I should get the appweburl, and I do, and let's go ahead and Run this. See, because I'm getting this dialog, it's because it's trying to make that cross domain call now. Actually, it's loading the app first, and now if I come here, it writes out the list of all the lists that are there in the HostWeb. And that's pretty cool.

Examining how Cross Domain REST API JS Calls Work

Now, before I stop this example, I'm going to do something else interesting. I'm going to hit F12 to bring up these developer tools, and let's see what's in the body. And you see what's going on here. The div is, you know the div, that's pretty obvious, but the IFrame over here is loading a page called as AppWebProxy.aspx. So, now you see what's going on. The requests are being funneled through AppWebProxy.aspx, and these requests are actually running on the server, as you can tell. So you just saw an example of using REST, JavaScript only, with no branding. Now, let's introduce the concept of branding. And, in parallel, I'll also explain how to use CSOM within apps, or JavaScript code.

Branding using the Chrome Control

So, the way you introduce branding in any application that is working as a SharePoint app, is by using something called as the chrome control. And the chrome control is basically that you would load SP.UI.Controls.js. And you provide the host URL as a query string in the Start page, because you got that already, like shown over here. So there's a special tilde called HostUrl, so you can either do HostUrl or StandardTokens. The way you would have to do HostUrl is where you don't have an AppWeb. So, if you don't have an AppWeb, but you need the HostUrl, then you can pass only theHostUrl using what you see here. And then there are a couple of ways to add the chrome control. What you can do is you clear the div with ID chrome control container, and the example that you're seeing over here is you add some attributes into that div, data-ms-control, and data-ms-options, and

IGATE Sensitive

Page 22: Sharepoint Apps Introduction_v1

that basically turns into a chrome control. So, you see here that there's a JSON object that I'm passing over here, and I have the ability to specify like a HelpPage, a little bit of Navigation, a Title, and an Icon. Now this JSON object it can specify that as data-ms-options property on this div, or you can also specify it in JavaScript. So the example that I'll be showing you actually uses JavaScript to do this. And when I say that this turns into a chrome control, by that what I mean is that it pulls in all the branding from the HostWeb, and it applies all the SharePoints, css' etc. onto our page.

Demo Branding and using Cross Domain Calls with CSOM

So I'm going to show you another example now where I'm going to show you cross domain requests using CSOM. But this time I will use branding, and therefore, I'll be able to show you how to do that with the chrome control. So, what I intend to do, in this example, is that I will create a simple CSOM based request, and it is going to pull out details from a particular list inside of the HostWeb. And that list is the Announcements list, so let me go ahead and set up the Announcements list first. So I'm going to go ahead and add an app. Create this. And I'm going to go ahead and add some data into it. Excellent. So now that we have some data inside of here, let's go ahead and write our simple app,which is going to pull data from this Announcements list, and it'll show that data inside of the app. And in order to be able to do that, I will also have to tweak the default permissions that the app comes with. So let's start Visual Studio. I'm going to Create a New Project, and I'll go with apps, App for SharePoint, and I'll call this ChromeControlCrossDomainCSOM. (Typing) And, again I'll go with a provider-hosted app just like before, just to prove that this is purely client side code. I will go ahead and Delete all server side code elements out of this once this gets created. So I'll scroll down here, and I will Delete the Default.aspx file. And I will Delete the SharePointContext, and TokenHelper.cs; we're not using them, so we'll Delete these. Just like before, I will need the appweburl, so let me go ahead and Add a dummy Module inside of my app. So, let's go ahead and do that. Now this will force the creation of the AppWeb, and therefore pass me the AppWeb URL. The next thing I will do is that I'll come here, and to the ChromeControl, to my web over here, and I'm going to go ahead and add an HTML file here. So, let's just add this at root. I'm going to say Add, HTML Page, and let's call it ChromeCrossDomain.html. And inside of the Scripts folder, I will go ahead and add a couple of scripts. So I will Add, let's separate according to two scripts. Let's all one as ChromeLoader, which takes the responsibility of loading the chrome control. And the second script let's go ahead and call it CrossDomainExec.js, which takes the responsibility of executing the cross domain request. And let's also come back to my AppManifest.xml, and change the Start page of my app to the cross domain HTML page that I just added. Okay, great. Now let's start adding our logic. So I'm going to start by going to the cross domain HTML file. Actually, there's a double "i" in here, let me quickly fix that. (Typing) And I'll just have to fix it up here. (Typing) Hmm, it fixed itself. That's good.

Demo of Chrome Control in Action

So let's start by adding some code inside of this HTML file. Basically, what I intend to do here is that I'm loading Microsoft.ajax because I'm using CSOM, so I need to do this. CSOM registers that SP namespace that I need to be able to access the CSOM object model, so I need to load the MicrosoftAjax namespace. I also need jQuery here, and I've loaded my custom two JavaScript files. Also, I have loaded something called as chrome control placeholder, this ID,so this is what will be responsible for turning into something that can pull all the SharePoint branding inside of it. And as you can see over here, that this h1 class, and finally this div inside of here, and the elements that I put inside of here, it's using a class called ms-accentText, and this is a SharePoint style. It's an out of box SharePoint style. So, the fact that I can use those styles means that I was able to pull in SharePoint branding inside of this particular page. So, let's start by looking at the ChromeControl.js file, where I'll be, or ChromeLoader.js file, where I'll be writing the logic for pulling in the branding of my SharePoint app. (Typing) So I'll start by creating a global variable, called hostweburl, which I'm going to use to save the URL for my HostWeb. And I've added a Helper function here, called getQueryStringParameter, which allows me to easily get a parameter from query string and put into a variable. The next thing I need is a function, which gets called as soon as the page gets loaded. So, let's go in and add that. And inside of here, I'm going to add a line of code, which gets me the hostweburl. Let's say decodeURIComponent, getQueryStringParameter, and I'm going to say SPHostUrl. (Typing) Excellent. Now, with the hostweburl loaded I can create a variable called scriptbase, just like before, and I can say hostweburl + layouts 15. And from here, I can go ahead and load the SP.UI.Controls.js file. So I can say scriptbase + SP.UI.Controls.js file, and when this file gets loaded, call a method called renderChrome, which I'm going to write next. (Typing) So the idea over here is that it's going to load this file, SP.UI.Controls.js, and once that file gets loaded, then renderChrome gets called, and inside of

IGATE Sensitive

Page 23: Sharepoint Apps Introduction_v1

renderChrome, I can write my logic that loads the chrome control. So, how do I do that? Step one is to give all the data necessary to the chrome control, like what is the app icon URL, what is the app title. So I create a JSON object, a standard JSON object that basically gives the chrome control enough information about what to show, and what are the links that it has to show, etc. And then I have to basically pass it the div using, the div that I had over here was chrome control placeholder. So, I have to basically pass in this line of code here, where I say var nav is equal to new SP.UI.Controls.Navigation, and this object is available to me because I've referenced this class, this JavaScript file here. So, I can say, SP.UI.Controls.Navigation, chrome control placeholder,and I pass in these options. And once that object is hydrated, then I can simply say nav.setVisible is equal to true. And by doing this much, my chrome control is going to work. Now, I'm not going to Run this just yet, because let's also so ahead and finish out the logic for the cross domain request that we have to execute next to be able to load the list of lists from the host web.

Demo of using CSOM to Execute a Cross Domain Call

And that code looks a little bit like this. So, again, I have these global variables up here, allAnnouncements, hostweburl, and appweburl. And first I get ahold of the hostweburl and appweburl, so now you see that I need the appweburl, which is why I had added that empty module. I created a scriptbase, and using scriptbase, I load a couple of files. I load SP.Runtime.js, and SP.js in sequence. Now the sequence is important, otherwise it'll bomb. And the reason I'm loading these files is because these are the files I need to be able to use CSOM. And then there's a third file that I load, which is SP.RequestExecutor.js, which is the same file you saw that I used to make REST API calls. And the REST API calls, and both of these basically go through that AppWebProxy, so I'm using this SP.RequestExecutor.js, and once all of these files are loaded, it's going to call execCrossDomainRequest. Now, this execCrossDomainRequest is basically if you start reading this code from bottom up, let's read this much first. So, it just looks like standard CSOM code. I get a context, context.load, context.executeQueryAsync. I'm specifying a CAML query, etc., etc. Where it gets interesting is how you create the context. And for that, let's start at the top. So, I say, where context is equal to SP.ClientContext appweburl. So basically the context that I'm using is for the AppWeb, not the HostWeb. But then, I create a factory SP.ProxyWebRequestExecutorFactory pointing to the AppWeb, because that's through where our AppWebProxy is going. And it's a context.set webRequestExecutorFactory, so basically pointed to the factory. And then I tell it what site are we targeting using AppContextSite. So, I say new SP.AppContextSite context hostweburl. So this is how I'm re-rooting the call from the AppWeb to the HostWeb. And as you can see over here, I say where web is equal to appContextSite.get web, and say a list, but then a standard CSOM code, and in the successHandler I'm able to write out all, the list of all that announcements that were found in that particular list. And in errorHandler, I'm simply writing out the error. Now, I have not tweaked any settings for my app right now. I'm just going to go ahead and Run this. And just for fun, I will set a breakpoint here. Let's first Run it without giving it any permissions, just under the default permissions of the app. (Typing)

Running App Under the Default Permissions

So provider-hosted apps will require you to do that trust thing through Visual Studio, so it can debug. Again, it's really necessary only for server side code. I'm going to go ahead and trust this app. You know why this is happening, because it's a POST request. I forgot to do the SSL thing, so it's saying show all content. And you see here, that, well, you saw the branding was there because, well, actually, let's finish this, and then we can see the branding. So you see that I get this enumerator, so apparently the Success method has gotten called, but you see here that there was nothing found in the enumerator. There are announcements in there, but I'm not able to read them. Notice that it is not throwing an error.So this is strange, that, generally speaking in server side object model, there're some places you would get an error if you try and access something that you don't have access to. But CSOM over here, instead of giving you an error, it's giving you a security trimmed UI sort of thing. So, it's not going to show me any announcements. But at least a good thing is that my SharePoint look and feel is coming through, so my chrome control is working. So the thing is,

Tweaking Permissions for Cross Domain CSOM Call

What do I need to do to be able to actually show the announcements? And the answer is, I have to tweak the permissions of the app so it can read the announcements. So, I'm going to open this

IGATE Sensitive

Page 24: Sharepoint Apps Introduction_v1

AppManifest.xml, and I'm going into Permissions. So first I'm going to show you adding the permissions from here, and then I'll open this file as XML,and we'll see what it did behind the scene. So, I will say the Permission is that to the Site Collection, we're asking for Read rights. Hit Save. And let's go ahead and Close this. And let's go ahead and Close this, and now I'm going to Open this as XML.

AppManifest.xml for a Provider Hosted App

And you see here that it added this thing called as AppPermissionRequest. Now, compare this entire file with what you saw in the SharePoint-hosted app. There are some key differences. Number one, instead of appweburl, you see remoteAppUrl. Number two, instead of AppPrincipal internal, you see RemoteWebApplication client ID is equal to *.You're not going to deploy with * in production, because that trusts everything. Generally speaking, you would give this a proper GUI, and that is what gets deployed. That is important when we do server side code. We're not doing that yet, so I'm ignoring that.

Structure of a SharePoint App Permission

And then you got something called as AppPermissionRequests, and it looks like an HTTP URL, but it's not a URL. It is basically something that makes your permission level unique. So basically what you're saying here is that what product am I asking for permission on, what part of the product I'm asking for permission on, and what kind of permission I'm asking for. So this is important because you cannot hard code any URLs inside of here, because that way your app isnot very portable. The whole concept, or theory, or philosophy over here, is that when you're writing the app you have very limited knowledge of where this app may get deployed. So you can't put knowledge about the HostWeb inside of the app. Now, the maximum resolution you can go to over here is that you can ask for permission on a list type. But then the thing is that in an app you can ask for permissions on only one kind of list type. You can't list three or four different list templates. If you list three or four list templates, it doesn't really give you an error, it just takes only the firstone of those. So that's something to keep in mind. Anyway, now on error on this, I should be able to see the list of lists.I'm also, to make things convenient, I'm going to change from SSL true to false. It doesn't make any change to the logic. You can try it with either way, but just so it doesn't prompt me for the show all content button and credentials twice, I change it from SSL true to false. Let's go ahead and Run this. Trust it. Again the get POST request issue. I'm going to go ahead and add my credentials here. (Typing) And now you'll see that the enumerator actually does find information.And now you see that I'm able to pull in Announcements from the SharePoint site. This is the same data that I had put in in here. If I was to open, say the First Announcement for instance, it says, This is the first announcement. I'm going to Edit this Item, add some more text, Save, come back here, Refresh, and you'll see here, that the same text appears here. So, this proves that through CSOM code we're able to read the HostWeb, and off the HostWeb we can get this information, and be able to show that inside of the AppWeb. It's quite amazing.

Summary

So what did we learn in this chapter? We learned some very high level basics of provider-hosted apps. But we only looked at client side code for now. In the next chapter, I will expand our knowledge further to also look at provider-hosted apps that use server side code, and in that context, I will also talk about apps that live in Office 365. In this chapter, I also demonstrated how you can use REST API with JavaScript, and how you use CSOM with JavaScript, and finally, I showed you how these external applications that work as apps inside of SharePoint can adapt SharePoint branding using the chrome control. I hope you found this chapter useful, and I'll catch you in the next chapter where I talk about provider-hosted apps, server side code. My name is Sahil Malik, and thank you very much for watching.

Provider Hosted Apps Server Side CodeIntroduction

in this chapter I'll be continuing the discussion forward on provider-hosted apps, specifically in the last chapter I talked about provider-hosted apps that use only JavaScript, only client side code, and in this chapter I'll be taking the discussion further and talking about provider-hosted apps that also use server side code. So, what have we talked about so far? So far, I've talked about SharePoint-hosted apps in

IGATE Sensitive

Page 25: Sharepoint Apps Introduction_v1

depth, and using the example of SharePoint-hosted apps, I also discussed in depth about a couple of important concepts that are things like Chrome Control. I talked about the branding, how it defers in SharePoint- hosted apps and provider-hosted apps, You know SharePoint-hosted app is just a SP Web, so you get the SharePoint master page, whereas in provider-hosted apps, you need to use the Chrome Control to download all the CSS, etc. And I talked about the UI aspects, like the full screen app, part app, that is some people call it a client web part, some people call it an app part, and I talked about custom actions. And then in the previous chapter I talked about provider-hosted apps that used only client side code.Now, in this chapter, we're going to go further, and we're going to talk about server-hosted apps, and we're going to talk about autohosted apps, and provider-hosted apps under server-hosted apps. So, what have we covered so far under provider-hosted apps? We've talked of only client side code, and in this chapter I'll be talking about server side code, and specifically this applies to where you setup the server, which is called as provider-hosted apps. I know the naming is a little confusing. There's no other like good name for provider-hosted apps, you know this red thing up at the top, let's call it as a server-hosted app, so like you have a server other than SharePoint involved, so the two cases you see down here are where you setup the server, which is provider-hosted app, and a server is setup for you, which is called as an autohosted apps. In both scenarios, you have server side code running on a server other than SharePoint, but interacting with SharePoint under well-defined permissions.

What are we going to Talk About

So, I'm going to be using Visual Studio to write these hosted apps, and I'll demonstrate provider-hosted apps, I'll demonstrate autohosted apps. What I'm not going to talk about in this chapter yet, is, number one, deployment details. Now, I'll talk about that in brief, because it is important for us to know what needs to be done next. But let's get the theory about how provider, or server-side hosted apps work properly in our minds first, and then we can dive into the deployment details. And I will also not be talking yet about advanced permissions and security scenarios. That's a topic for another day, we'll talk about that in another chapter. For now, you know, crawl-walk-run, let's understand how to write provider-hosted apps properly.

How does it Work - Server Side Code

So, how does it work? Server side code. You saw this slide in the previous chapter. The browser talks to some other server. This could be ASP.NET MVC, WebForms, PHP, or really anything else you want. And your requests are received from the browser by the server, and then this server talks to SharePoint. And for this to work, obviously, SharePoint has to trust this some other server.

Trusting the App Server

So, how does SharePoint trust this other server? There are two mechanisms. One is called as S2S, Server to Server trust, which is typically what you'll be using in on-premises, and it requires some amount of time setup that I'll go through. And the second choice is OAuth, which is something that you can use in Office 365, or you can even use it on-premises, but you need Office 365 currency anyway for OAuth-based trust to work. So, OAuth relies on Azure ACS behind the scenes, and as much as behind the scenes, it seems more complex, but in reality, developing for OAuth is both more flexible, and it is simpler for us as developers. So, we're going to start with an in-depth look into S2S, and we'll look at how you can do the same with OAuth as well. So, let's start with S2S.

The Concept of IssuerID and Client ID

When you're talking about S2S trust, there is a concept of an Issuer ID and a Client ID that we need to be very clear about. The idea here is that some other server is talking to SharePoint, and this some other server has been trusted by SharePoint. In other words, it's not just a server that has been trusted, it is certain apps running on the server that have been trusted. But remember the server, or potentially a department, like the finance department in your company, could have one or more servers, and they may many apps that they're writing, talking to the SharePoint environment. The idea here is that you can setup one Issuer ID to cover that one department, or that one team, or that one server, however you want to logically group this, and that one Issuer ID can be responsible for hosting many Client IDs.Sometimes we also call a Client ID as an App ID, so the idea here is that with one Issuer ID you can have many Client IDs. Now, the Issuer ID and the Client ID are both GUIDs. But, the

IGATE Sensitive

Page 26: Sharepoint Apps Introduction_v1

Issuer ID is backed by a certificate, so by allowing us the flexibility of having one Issuer ID supporting many Client IDs, we can work with a single certificate. So it makes the certificate management story for us a whole lot easier. That is why Microsoft designed it this way that they've created the separation between an Issuer ID and a Client ID. So for one Issuer ID, you can have many Client IDs.

The Process of Writing and Deploying a Prov. Hosted App

So the process of writing a server side code, provider-hosted app, is a little bit like this. Number one, you need to create a certificate, and you need this certificate because you need to associate that certificate with an Issuer ID. So, you need to first create the cert, and then with the help of the cert, you need to register an Issuer ID both inside a SharePoint, and you need to tell you server what you're Issuer ID is. Then you can use Visual Studio to write your app, and in Visual Studio it'll ask you to provide a certificate, and an Issuer ID. Now optionally, not necessarily, but optionally, you can alsogenerate a Client ID. But if you don't specify a Client ID, Visual Studio will generate it for you, and the advantage there is that every time you hit F5 to start debugging, the process of creating the Client ID and registering your app is transparent to the developer. Now what you'll also see is that once you get more familiar with writing apps, I think you'll probably want to generate a Client ID ahead of time anyway. This will become a little bit more clear when we actually see this running in example, but keep that in the back of your mind. So, everything to the left of this line is what we're going to cover in this chapter. To the right of this line, I will be covering in a subsequent chapter, in which I talk about packaging your app, how to deploy the server side code. So, you would package your app, basically generate the .app file, put that in your App Catalog, etc., and before users start to install your app, you need to deploy the server side portion of the app yourself. So, if this was an ASP.NET app, you'll need to set it up in IIS, or something like that. And over there, you're going to need a Client ID, and actually even when you package your app you're going to need the Client ID at that time also. So you need the Client ID at that time. Something that you generate, and you control. It can't be a Visual Studio auto-generated random Client ID at that point. And then finally, you deploy your app to the App Catalog, and then the users can start using it. So, when we put the left and the right side of this picture together, things will become very, very clear, but we need to understand the left side first, and once the left side is crystal clear to us,then we can move to the right side.

Generating IssuerID

The command, the PowerShell command that we're concerned with is New-SPTrustedSecurityTokenIssuer. And this accepts the following four inputs. The IsTrustBroker, starting from the bottom, is basically, is telling SharePoint that this one Issuer ID can issue multiple Client IDs. Certificate is what certificate is backed with, so the public key portion of the cert, the .cer portion of the certificate is required here. The RegisteredIssuerName is the name of the Issuer ID, and the Issuer ID the GUID, is specified up here. So, how do we get the rest of these parameters? For that, let's go back to PowerPoint. So I've increased the font size here a little bit, but it's the same command as before, and as you can seehere, that the certificate is something that I've generated, and exported on my C drive ahead of time. So, this is a .cer portion of the certificate, this is what SharePoint is going to need. Now, SharePoint is going to validate the request sent by the external server, so it needs the public portion of the certificate, which is what you see here. The other server is going to have to sign the request. So, it is going to need the private key, the pfx part of the cert, so we'll see the pfx part in play also very soon. Continuing further, the Issuer ID is just a GUID. And the RegisteredIssuerName is a concatenation of the Issuer ID, and the Run. So with these, I'm able to create a SPTrustedSecurityTokenIssuer, basically the Issuer ID. And another thing I need to do is that for development purposes, I need to AllowOAuthOverHttp.I would not do this in production, but for development purposes, it's great. So, I allow this, and I do a .Update, and for it to take effect, I have to do an iisreset. So this is how I would generate the Issuer ID and the idea is that then I would remember this GUID, this Issuer ID that we've created, and I would supply this to Visual Studio when I write my provider-hosted app.

Visual Studio and ClientIDs

And then Visual Studio will generate the Client IDs for me. And inside, if I was to look in my AppManifest.xml, or in the .config of my provider portion of my app, the Client ID, or the app ID will be returned as *. But what actually happens is that every time I hit F5, Visual Studio will create, and register a Client ID, and it will update those for me. So, the problem of this approach is that, let's say

IGATE Sensitive

Page 27: Sharepoint Apps Introduction_v1

we're working together as a team, and anytime I debug, I'm going to generate a Client ID, anytime you debug, you're going to generate a Client ID, and the AppManifest.xml, and the Web.config aregoing to keep changing. Source control becomes a real pain, because it keeps telling you that this .config file has changed, and you need to merge it, and the only thing that's changed is Client ID. So, I think in real dev environments you'll probably want to just go ahead and generate a Client ID yourself, but it's okay to get started with by having Visual Studio generate it for you.

Generating ClientIDs

Now, how about generating the Client ID. The Client ID goes in two places. It goes in the AppManifest.xml, and it goes in the Web.config of the provider-hosted app, and there is a file called TokenHelper.cs that looks for that file in that area.But, how do you generate a Client ID using a PowerShell command? Call Resgister-SPAppPrincipal, and it expects the following inputs. So the site where you're basically registering this Client ID is, this is how you get it, and the fullAppPrincipalIdentifier you would get it using the realm, and concatenating it with a GUID, and that GUID is your Client ID, and this is what you'll need.

Role of Certificates

So again, the role of the certificate over here is that you'll need a certificate because the app is going to sign its requests, and SharePoint can check those signatures. So, the SharePoint will need the .cer portion of the certificate, and the app is going to need the pfx portion of the certificate. Now, when we generate the certificate, you'll see that the app is going to, Visual Studio is going to put the pfx portion of the cert automatically in the .config of my app, and TokenHelper.cs is a helper class that Microsoft gives us that looks for the pfx cert over there. And the cer portion of the cert, if you remember, when I generated the Issuer ID, let's go back here. So when I generated the Issuer ID, --- the cer portion of the cert was being used over here. So this where that cer portion of the cert comes into play. So you see that this is built on certificates, so that's very, very important.

TokenHelper.cs

Now, TokenHelper.cs I've already mentioned this name a few times. Basically what TokenHelper.cs does is that it is a helper class Microsoft has given us that allows us, you know, makes our lives a little bit easier. So, how do you authenticate our app to SharePoint? The underlying mechanics of that are somewhat complicated, so they've made our lives easier by giving us this file. And this file is great for Windows authentication purposes. If you want to use FBA, or Claims, you're going to have to add more details into this file. This file does not work out of the box with FBA, or Claims, but it is possible to make provider-hosted apps work with FBA or Claims. Whereas, remember, in the other scenario, SharePoint-hosted apps, they can work with FBA, but they can't work with Claims, or ADFS, or Azure ACS. If that's your authentication provider, forget it. SharePoint-hosted apps are not going to work. Provider-hosted apps can work, but they don't work out of the box. And what helps us make those apps work with Windows Auth even is TokenHelper.cs.And if you want provider-hosted apps to work with FBA or Claims, then we have to extend this TokenHelper.cs. We'll leave that for another day. Now, I'm going to show you a couple of demos to get this provider-hosted app concept solidified in our heads. I'm going to show you the process of writing an ASP.NET WebForms app, and I'll demonstrate both CSOM, and REST API code. And then I'll also write another app, which is an ASP.NET MVC app, and I'll demonstrate this with just CSOM code, because REST API is exactly the same. In fact, I think what you'll see is that the only difference within WebForms and MVC app is that one is of WebForms and the other MVC, but as far as the SharePoint app story is concerned, both of them are absolutely identical. I'm using Visual Studio 2013. The steps with Visual Studio 2012 were a little different because the MVC app template was not baked into the project templates, so you had to do a couple of minor manual steps. I'll mention what the steps are, but I think you'll probably be using Visual Studio 2013, I hope, because the tools in that are better.

Demo of ASP.NET WebForms App with CSOM

So, let's go ahead and see how to write an ASP.NET WebForms app using server side code, and I'll demonstrate both CSOM and REST API. So, the first thing I'm going to need obviously is a certificate.

IGATE Sensitive

Page 28: Sharepoint Apps Introduction_v1

Generating and Exporting a Cert

So, first let's go ahead and generate a certificate. So let's go ahead and Open our Internet Manager, and here I'm going to go ahead and look for something called as Server Certificates, and I'm going to go ahead and Create a Self-Signed Certificate, and we'll call it OnPremApp. Now, can I use self-signed certs in production? Yes. Yes, you can, because this is not a certificate that needs to be trusted by a root authority, etc. This is a certificate that just needs to be trusted between SharePoint and the app server. So, using a self-signed certificate is absolutely no problem, just make sure that the certificate you specify is strong enough, like a 2048 key, or so on and so forth. Like this self-signed certificate that I just did over here, this is valid until like 2041, or some ridiculous year. So, you probably want to trim it down a little bit, but as long as, you could just make certs, etc., to generate these certificates. But, it's perfectly okay to use a self-signed cert. I'm going to go ahead, I'm going to Export this certificate. First I'll Export the entire certificate, both the public, and the private part as a pfx cert. I'll give it a Password. Let me make sure the Password is correct, and second, I'll also Export the certificate as a cer, without the private key. I'm going to hit Next, and I'm going to say c:\code\OnPremApp.cer. So this certificate now is exported in C Code, okay, C Code.

Demo Generating IssuerID

Now with this certificate exported, the next thing I need to do is that I need to run a PowerShell command, that will register this certificate for me, and it'll give me an Issuer ID, an associated Issuer ID with it. So, the PowerShell command that I'm about to run is actually mentioned here in the slides. So this is what I need. I'm going to go ahead and Copy/Paste this. Generating an Issuer ID, just make sure that the parts are correct, which in my case are, and I'm going to go ahead and Run this over here. And you see here that it went ahead and gave me this Issuer ID, so I need to Copy this Issuer ID, and I need to Save it at a safe place. I'll just go ahead and put this in Notepad.

Creating a Visual Studio Prov. Hosted App Project

Now, I'm going to start Visual Studio next. So let's go ahead and start Visual Studio, and I'm going to go ahead and click on New Project, and this time I'll choose App for SharePoint, and what should we call it? Let's call it WebFormsCSOM. So first we'll use CSOM. I'm going to hit OK. I'm going to choose to create a provider-hosted app this time, debugging locally. Hit Next. I'm going to choose to create a WebForms app. Now if you were using Visual Studio 2012, you will not get this choice. The only thing you could create there was a WebForms app. It wouldn't let you create an MVC app. But it was very easy to turn an existing MVC project into an app. All you had to do was extract things out of this WebForms app, you know the .config, and TokenHelper.cs, and viola, you had a SharePoint app ready. That was it. So the steps in that are very similar. They're described in my book, so I won't actually be demoing those here, I'll just show Visual Studio 2013. So, I'm going to hit Next here, and I'll basically say that I wish to be able to use a certificate, and the certificate I want to use, let's Browse to it, and it was in C, (Typing) Code, OnPremApp.pfx, and supply it the Password, and give it that Issuer ID that I just generated up here. Okay. And I'm going to hit Finish. And my project is created. Now, with my project created, the structure of the project is probably very familiar to you by now. There are two projects in here, one that holds all the details for the app, and the second that holds the details for my provider web. This is a WebForms app, and, as you can see, it's pretty intuitive. What's going on here is that there's a Default.aspx, which is the start page mentioned in AppManifest.xml, as you can see here. And you also see here that there's a code behind here, is referencing jQuery, etc., and there are at least two files, SharePointContext.cs, and TokenHelper.cs. So, this SharePointContext.cs, and TokenHelper.cs basically make my life a little bit easier when it comes to working with SharePoint apps infrastructure. Like, I want to know what the ASP Host URL is, so rather than remembering these keywords, I have a static method that gives me the Host URL. So there're some things here that help me out there, and in TokenHelper.cs, which is a little bit more complicated, in TokenHelper.cs, you have a whole bunch of methods that allow me to get like the access token, and the S2S secure token, and so on and so forth, and basically it simplifies my authentication routines when it comes to working with SharePoint. And what's even cooler is that they are actually giving us some starter code here, so I'm just going to go ahead and open this Default.cs, and what you see here in theDefault.cs, under Page Load, we're getting spContext, get the SharePoint Context, and then I say spContext.CreateUserClientContextForSPHost. So, what's happening over here is that there is something, you know, apps work under a security model, and when your server side code is talking to the server, SharePoint server, both the app, and the user need to have access to do an action for that action to succeed. That is the default behavior. Now, there's something called as

IGATE Sensitive

Page 29: Sharepoint Apps Introduction_v1

AppOnlyClientContext, and in which case the user may not have permissions, but the app has permissions, and the request can succeed. That's option two. Option one, which is default, in which the user, and the app must have rights to do something for that something to succeed. And what we need to do here is that we're creating a clientContext, just like the CSOM clientContext, and that CSOM clientContext, using this line of code, has been created under the first authentication model that I mentioned, which is AppPlusUser, so both the app, and the usermust have rights to do something for that something to succeed. Okay, and then what are we doing here, like once you get the clientContext, then it's just regular CSOM code. I'm doing clientContext.Load, clientContext.ExecuteQuery, response to a query, bam. It should write out the Title of my SP Web. Now again, I can go in and tweak permissions, etc., over here if I was doing something crazier, but just to write the Title, I don't need to tweak permissions a lot. So, a couple of other things I want to show you. Let's tap into the Web.config of my app here, and you'll see here that there are these things mentioned here. Okay. There is something called as ClientId with no value here, but you'll see that when I hit F5, Visual Studio will generate the ClientId for me, and it will put it in here for me. Now, let's scroll up here, and also open the AppManifest.xml as XML. And you see here that the ClientId is also mentioned over here. Again, when I generate my, when I hit F5, or when I generate the package, I'm going to have to require it to basically put in a real ClientId over here. So doing debugging, etc., its fine, but again in real projects, or when you are ready to deploy this, you're going to need a real ClientId. I'm going to actually leave this Web.config open because then we can see that it actually generated the ClientId, and it put it in there.

Running and Debugging your App

So, what I'm going to do next, is I'm going to hit this button here, and it'll deploy it, and package my app, and generate the ClientId, but when it does that, I'd like you to view this Output window very closely, and you'll see that the ClientId gets generated, and you'll see that Visual Studio is going to Update this file here, so I'm going to hit the Start button, and let's observe this Output window closely. So, you see it generated a ClientId, that's what I was talking about. It also created this trusted root authority line, because this is what helps Visual Studio debug things, so I'm going to hit Yes, this is what facility its debugging, so I'm going to hit Yes over here. And see it modified the Web.config. When I hit Yes, you'll see that a ClientId will appear here. You saw that? A ClientId appeared inside of my Web.config. Let's open the Web.config here. You see the ClientId appeared here. This is the same ClientId that Visual Studio generated. Now let's come over here. It's installing the app. And waiting for SP. It's saying, do you trust this app? So, a user that has rights to do what the app is asking to do can trust this app, so I'm going to hit this button. And this will go ahead and trust the app, and it writes out the Title of my site. I can show you this in Debug mode. Let's go ahead and setup a breakpoint here, like right over here, and I'm going to hit Refresh here, and you see here that the Title of the site is actually being refreshed using CSOM. See this? And this is how it works. Now, this doesn't look like a SharePoint page. What would you have to do to make this turn into a SharePoint page? The answer is Chrome Control. The Chrome Control that I demonstrated in the previous chapter, if you apply that over here, this will turn into a SharePointy-looking site. Even though this is really, this is really not a SharePoint site. It's an ASP.NET site. It's just interacting with SharePoint under a well-defined permissions model. So that's pretty cool.

Demo of ASP.NET WebForms App with REST API

Now, how do I turn this code into REST API? Now, I want to use REST API. So, this is CSOM. How do I turn this into REST API? I'm going to remove this code, and let's start writing some code, which turns this into a REST API benchmark. So in order to use REST API, I need something called as access token, and the access token, I can get that with something called as, so this is a string, accessToken is equal to, the TokenHelper.cs has got methods that help me get the accessToken, so I can say, GetS2S. You notice that there was a GetAccessToken, and then there is a GetS2SAccessToken. You would use GetAccessToken when you're targeting Office 365, and you would use GetS2SAccesToken when you're targeting on-prem apps. So, I'm going to say GetS2SAccessTokenWithWindowsIdentity, and here I need to pass in the HostWeb and I need to pass in the identity of the user that is logged in. Now, notice that the method says get access token with Windows identity. So, there is no method here that allows me to get an access token with an FBA identity, or a Claims identity. It is possible to do that, and I'll show that in a different chapter, but first let's just look at getting access token with Windows identity. So, this is how I can get the access token with Windows identity. Now, once I have the accessToken, I need to craft up an HTTP WebRequest that goes to the server. The request I'm going to do is really simple, it's basically going to target the hostWebUrl/_api/web. And, as you can probably

IGATE Sensitive

Page 30: Sharepoint Apps Introduction_v1

guess, this is loading the details of the web so I should be able to say,get the Title of the site out of this. And this request, the method on this will be GET. So let's specify that. Okay. And, another thing that I'll need to specify is that I need to specify that I want to work with JSON, and working with JSON I can say, endpointRequest.Accept = application/JSON;odata=verbose. So I'm going to accept, you know, I want to work in JSON, so the results will come back as JSON. Now, here's a question. How does SharePoint know that this is an authenticated request? The answer is this accessToken. But, how do I use this accessToken to tell SharePoint that this is an authenticated request that SharePoint can accept? And the answer to that is that I need to append a Header, or authorization, in which I need to say Bearer (space) accessToken, and this will allow SharePoint to basically again check with the certificate and see, is this somebody I trust, and say yeah, this server is somebody I trust. The Issuer ID for this guy is registered with a certificate, and that's what I need. And this will allow SharePoint to allow this request to go through. So, and that's basically it. The next thing we need to do is actually execute the request, and then I can get the results as a Stream. And once I get the results as a Stream, I just need to go through this Stream, and I need to write out the results of whatever was read from that Stream, and I can do that using this code over here. Okay, that's it. This is all I have to do to use REST API in start. Earlier I was using CSOM, now I'm using REST. Now, you'll see that, you'll see that the REST API code is a little bit more wordy. And you say, well, why shouldn't I just use CSOM always, and the answer is, mostly you'll use CSOM from server side, but there's some weird scenarios where you'll actually prefer to use REST, like if you're uploading a file, CSOM has a limit that it can only upload a 1.5MB file. I think that's silly. You know, why would you create an API that is so restrictive? But, anyway, if you really want to upload a file, I think you'll end up using REST. So I'm going to go ahead and Run this again just like before, no changes. So Visual Studio will completely change the logic here. Let's come back here, and so you see here that it writes out, the response stream is writing out the results as JSON. It's quite easy. Okay. So, this is how I can write REST API, and CSOM code in an ASP.NET WebForms based application.

Demo of ASP.NET MVC App with CSOM

Let's extend this a little bit further, and talk about how I can use MVC to use CSOM code, and I think once you see the CSOM code using MVC, you'll pretty much be able to write the REST API code yourself, it's exactly the same. You could literally Copy/Paste it out of the example that I showed earlier. So, again I need this Issuer ID, so I'll keep this safe. And I'm going to go ahead and again start Visual Studio, and I'll go ahead and create a New Project here. I'm going to call this new project, again App for SharePoint, I'm going to call this MVCCSOM, and hit Enter. Provider-hosted app, Next, MVC, Next, and we'll use a certificate. See, it's so nice, it filled all these details out for me. So let me make sure this is correct. And let's go ahead and create this. Now, for those of you that are familiar with MVC, this project will appear, it will feel right at home to home to you. It's got Views, it's got Controllers, it's got Models, just like any MVC project. So, there's a HomeController here, and there's a View out here, that is, oops, not this one here. There's a View out here that is basically writing our ViewBag.UserName. And if you see in here that this ViewBag.UserName is being populated by the HomeController here, and just glance through this code. This looks like exactly the same as what you saw in WebForms. We're using exactly the same logic, except instead of writing the title of the web, this time we're writing the name of the user. That's it. I mean, it's exactly the same code as WebForms. There's no difference here. Again, we're using the same TokenHelper.cs that we had earlier. Web.config has got the same elements over here that you saw earlier. These are the ones that we are concerned with. And I'm just going to go and hit Run this, and it'll generate the ClientId just like before, and let's wait for this to finish. It generated the ClientId, it'll update the .config here, bam, it puts the ClientId there. I'm going to go ahead and Trust this, and see, it writes out the name of the user. This is how you write MVC code. Now, I'm sure you can extend this very easily to work with --- REST API as well.

Autohosted App Targeting Office 365

But I'm going to switch gears, and I'm going to show you how to write a simple app targeting Office 365 next. So, let me go ahead and Close all these windows, I really don't need them, and the next thing I need is, you know, I'm going to write a simple app targeting Office 365. So the important keyword here that you need to remember is this word, autohosted. So far, anytime I needed to be able to create my app, I hosted the server myself. Yes, Visual Studio ran it in IIS Express, but if I wanted to deploy it, I would have to host that server myself. What an autohosted app does, in comparison, is that it hosts that server for me. It creates that server for me when the app gets installed, and it removes it when the app disappears. So, I'm going to next go ahead and write an app that's going to run in Office

IGATE Sensitive

Page 31: Sharepoint Apps Introduction_v1

365 with autohosted setup, and I'll show the parts of writing it, debugging it, and deploying it, and so on and so forth. So let's go ahead and start Visual Studio. I'm going to click on New Project, and I'm going to create a SharePoint App, and let's call it Office365App, and I'm going to hit OK. Now, I'm going to create an autohosted app, and I'm going to target Office 365, and for this I'll need my Office 365 URL. So, let me go ahead and log on to my Office 365 site, make sure that it actually works. Let's go to office365.com. I'm going to pick that app URL, and let's go ahead and Sign in, and provide my credentials. (Typing) And go ahead and Sign in. And let's find my, let's find my Office 365 site. Let's go to SharePoint. And it says winsmartsdev-admin, and the site I care about is this hhtps://winsmartsdev.sharepoint.com. Let's just make sure that site is there, and I'm going to clean this up, and how do I do that? Go to Site Actions, go to Site Contents, and we'll go ahead and remove all these apps I'm not using one by one. Okay, so what I have now is a pristine, clear Office 365 site, so I'm going to take this URL here, and I'm going to Paste this in Visual Studio. (Typing) And I'm going to choose autohosted app, hit Next. I'll choose, let's say WebForms. I'm going to hit the Finish button. Note, it didn't ask me for like a certificate and all that, because it's really not required in this case. What's required in this case is something called as a Secret, and that Secret, in conjunction with Office 365 and Azure ACS does an OAuth protocol dance. It gives you the access token. At the end of the day, you need the access token. So if you go into, the code is slightly different this time. So you go into the Web.config. It's got a ClientId, which will get generated when I run this, and it's got this random looking thing, which is a Client Secret. And this Client Secret is what I care about. This Client Secret is what helps me generate the access token, I don't need certificates, and that's pretty cool. And if you examine the code here, so let's go ahead and open Default.aspx.cs, and go down here. Hey, the code looks almost identical. Actually, it is, it is identical, right? So you see here the clientContext, spContext, CreateUserClientContextForSPHost, and the code is exactly the same, and again, the point here is that you get a clientContext. Once you get the clientContext, then you're just working with regular CSOM code. The only difference is this time it's going to run in Office 365, and you have an autohosted app. The code is exactly the same as before, so, let's just go ahead, and Run this.

Debugging an Autohosted App

I said autohosted app, and the autohosted app by definition means that it's going to provision an area in Azure. So, when I hit the Start button, is it going to provision an area in Azure? And if it does, how do I debug it? Let's find out. I'm going to hit this Play button. It'll ask me to Sign in to my Office 365 site, because it's deploying things over there. Let's go ahead and Sign in. (Typing) And it's asking to update this Web.config because it generated the ClientId. And again, I have to hit Office 365 again for debugging purposes. (Typing) And let's go ahead and Sign in, and I'm going to hit this Trust It button. (Typing) And you see here that it's able to write out the title of my site. Remember, the logic is exactly the same as before, but this time I'm running in Office 365 as an autohosted app. Not quite. Look at the URL. When I'm debugging, I'm still using IIS Express, but I can debug, it's as if it is autohosted app.

Packaging and Deploying an Autohosted App

Now, I'm going to go ahead and package this app, so I'm going to say right click. So, a couple interesting things I want to show you is that, you got these event receivers here, that's the same as a provider-hosted apps, but with autohosted apps, you also have these two things here. So if your app needs a database behind the scenes that's sitting in SQL Azure, you can also create a SQL Azure area behind the scenes for you. And if you want data sharing, you can share that SQL Azure database, or you can use Azure table storage, and so on and so forth, if you wanted to. I'm going to go ahead and hit right click, Publish, and it'll just go ahead and Package the app. (Typing) So, it has made my app available as a .app file, and I need to make this app available for use in my Office 365 site. So how do I do that? I'm going to click, I'm going to come back here. Let's Copy/Paste this URL to actually open it in another tab, and I'm going to go to this Admin area again, and go to SharePoint, and I'll go to this apps area. And I'll go to my App Catalog in my Office 365 area, and I'm going to go ahead and Create a new app catalog site. So, I'll hit OK. (Typing) And let's go ahead and Create, I'll just call it App Catalog/sites/appcat, and let's give it an Administrator name. (Typing) Let's wait for this App Catalog to get created. Okay. So, once this is created, let's go ahead and visit the site, the App Catalog. (Typing) And from here it's actually very, very similar to what you've already seen in on-premises. What you'll do is that you will take this app, and you could upload it here. Actually, upload it here under Apps for SharePoint, you can upload the app in here. And once you upload the app here, you can add it in any of your site collections. And since you've already seen that, the process of that is exactly the same as I showed you in the SharePoint-hosted app, so I won't actually walk through all those steps, and leave that as an exercise for you.

IGATE Sensitive

Page 32: Sharepoint Apps Introduction_v1

Using the Developer Site

I will use this opportunity to show you how you can use the dev site to be able to do the same thing. And the dev site is something that you'll never roll into production, but it's here, so let's use it. So, I'm going to say new app to deploy, and I can either pick an existing available app, or I can say upload the app to the developer site. And I can choose to find this app, this package that I just created, and let's go ahead and Upload it. It says Deploy this app here, I'm going to say Deploy. And it's asking me to trust this app, I'm going to hit Trust It, and watch what happens. And the app is installing. Let's give it a little time. (Typing) Now remember that this installing might take us a little time because it's also creating an area in Azure for you. Okay, so let's give it a couple of minutes, and pretty soon it'll change it to like this, and then you just go ahead, and click on this app. And it's redirecting me to the app. And you see here it's running just like before, as if I was running it on-prem. The difference this time is that, look at the URL, guid.o365apps.net. So this area was created for me on the fly. And when I go in and Uninstall this app, it'll remove that area for me. So let's go ahead and REMOVE it, and by doing so, that area is gone as if it was never there. That's pretty awesome. This is an autohosted app.

Summary

Fantastic! We've covered a lot of ground in this chapter. What exactly did we talk about? We talked about a deeper dive into provider-hosted apps, and then talked about using server side code with provider-hosted apps. I demonstrated that using ASP.NET MVC and ASP.NET WebForms. I showed you both CSOM and REST, and I actually also showed you this as an autohosted app, or as a provider-hosted app. And I also showed you a little bit of how things work behind the scenes. You know that Bearer authorization request, a clientContext, the accessToken, those are the things you'regoing to need, the Web.config entries, the TokenHelper.cs. So, we covered a lot of interesting things here. I'll tell you one thing, provider-hosted apps I think are probably going to comprise the majority of the kinds of apps you will write. So this is a concept that you must get very clear about, so provider-hosted apps are very important for us to learn. So, what's next?

What is Next?

There are further details in provider-hosted apps, specifically around apps security. There are different security pattern names, how security works behind the scenes, and I'll talk about those in depth when I talk SharePoint security in general. The SharePoint security now, you can think of it as it's got two halves. One is user security, and the second is apps security, so I'll talk about all of that when I take a deeper dive into security. And then one thing that I have not talked about yet, is, believe it or not, a small topic, which is deploying these apps. So, again when I talk more about security, I'll be able to talk more about deploying these apps also. 

IGATE Sensitive