THE MICROSOFT JOURNAL FOR DEVELOPERS JANUARY 2018 VOL 33 NO 1magazine Working with Span in C# 7.2.................................22 0118msdn_CoverTip_8x10.75.indd 1 12/12/17 12:43 PM 1317msdn_CoverTip_8x10.75.indd 2 11/28/17 2:59 PM THE MICROSOFT JOURNAL FOR DEVELOPERS JANUARY 2018 VOL 33 NO 1 magazine Working with Span in C# 7.2.................................22 All About Span: Exploring a COLUMNS New .NET Mainstay UPSTART Stephen Toub. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Crisis of Confidence Krishnan Rangachari, page 6 Extend Excel Formulas for Data Analysis DATA POINTS Michael Saunders.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Creating Azure Functions to Interact with Cosmos DB Build the API to Your Organization with Julie Lerman, page 8 Microsoft Graph and Azure Functions ARTIFICIALLY INTELLIGENT Mike Ammerlaan. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Creating Models in Azure ML Workbench What’s New for .NET UWP Development? Frank La Vigne, page 16 Daniel Jacobson and Stefan Wick.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 CUTTING EDGE 20 Years of Cutting Edge: Creating a Line-of-Business App A Conversation with the UWP Dino Esposito, page 64 Bruno Sonnino. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 DON’T GET ME STARTED WD-40 David Platt, page 72 0118msdn_C1_v1.indd 1 12/12/17 8:51 AM Infragistics Ultimate 17.2 Productivity Tools & Fast Performing UI Controls for Quickly Building Web, Desktop, & Mobile Apps Includes 100+ beautifully styled, high-performance grids, charts & other UI controls, plus visual configuration tooling, rapid prototyping, and usability testing. Angular | JavaScript / HTML5 | ASP.NET | Windows Forms | WPF | Xamarin Download a free trial at Infragistics.com/Ultimate Untitled-5 2 11/6/17 1:06 PM filtering.321. a tiny footprint. WYSIWYG page design. The Ignite UI Angular Data Grid enables you to quickly bind data with little coding - including features like sorting. and easy-to-use API. & built-in-themes. paging. MVC & Angular components. data rich web applications Create beautiful. Featuring Ignite UI A complete UI component library for building high-performance. powerful data binding. templates and more! Speed up development time with responsive layout. Our easy to use Angular components have no 3rd party dependencies.8588 Untitled-5 3 11/6/17 1:06 PM .com/Ignite-ui To speak with our sales team or request a product demo call: 1. responsive desktop & mobile wep apps with over 100 JavaScript / HTML5. Download a free trial of Ignite UI at: Infragistics.800. touch-first. movable columns. cross-browser compatibility. ” c/o MSDN Magazine. as well as Print Production Manager Peter B.O. Skokie. 101. Jane Long.m. Valenti Chairman of the Board Jeffrey S. please use the following form:
[email protected]. Events Sponsorship Sales Danna Vedder E-mail: jlong@meritdirect. there President Senior Director. CA 91311. magazine JANUARY 2018 VOLUME 33 NUMBER 1 ID STATEMENT MSDN Magazine (ISSN 1528-4859) is published 13 times a year.. Lindgren Executive Vice President Michael J. Editorial Director. LEGAL DISCLAIMER The information in this magazine has not undergone any formal testing by 1105 Media. Client Services & Webinar CORPORATE ADDRESS 1105 Media. or mail. Ste 101.A. fax. Chatsworth. Box 3167. Lead Generation Marketing Eric Yoshizuru MEDIA KITS Direct your Media Kit requests to Chief Director. Event Marketing Merikay Marzoni For more information. News David Ramel Henry Allain the publisher.S.00. Inc. Art Director Joshua Gould Suite 150. Director. Canada Group Managing Editor Wendy Hernandez Publications Mail Agreement No: 40612608. ADVERTISING AND SALES Senior Manager. Irvine. Weller Senior Director.com/1105 Chief Revenue Officer Dan LaBianca Coordinator. and at additional mailing Director Dan Fernandez offices.com are: U. International $60. and is distributed without any warranty expressed LEAD SERVICES or implied. $10. Event Marketing Chantelle Wallace Staff may be reached via e-mail. Operations Sara Ross other lists from 1105 Media. Periodicals postage paid at Chatsworth. Senior Contributing Editor Dr. Irvine. Reproductions in whole or part Vice President. David S. Julie Lerman. Custom Assets & Client Services Mallory Bastionell Revenue Officer Dan LaBianca. 9:00 a. Lead Generation Marketing Senior Graphic Designer Alan Tao Mahal Ramos contact: PARS International Phone: 212-221-9595 Senior Web Designer Martin Peace E-mail: 1105reprints@parsintl. Single copies/back issues: U. While Vice President. email Editor in Chief Michael Desmond MSDNmag@1105service. CA 91311 1105media.com ENTERPRISE COMPUTING GROUP EVENTS Web: 1105Reprints. Box 201. Fax 818-734-1522 Rajeev Kapur 9201 Oakdale Avenue. Chatsworth. Event Marketing Michelle Cheng Reaching the Staff Regional Sales Manager Christopher Kourtoglou Coordinator. Print Production Coordinator Lee Alexander Senior Director. P. CA 91311-9998. James McCaffrey or XPO Returns: P. Events Brent Sutton LIST RENTAL This publication’s subscriber list. Box 2166. Audience Development in the industry. monthly with a special issue in November by 1105 Media. please contact our list manager. Carol Stream. plaques and posters Project Manager.00. Canada. Associate Creative Director Scott Rovin 972-687-6799 (fax). Mail requests to “Permissions Editor. News Kurt Mackie Telephone 818-814-5200. ON L4B 4R5.m. 9201 Oakdale Avenue. Site Administration Shane Lee Chief Financial Officer Front-End Developer Anya Smolinski Craig Rucker Junior Front-End Developer Casey Rysavy Chief Technology Officer Office Manager & Site Assoc. CA 92618 Vice President. CA 91311 Senior Site Producer Gladys Rama The opinions expressed within the articles and other Chief Operating Officer contentsherein do not necessarily express those of Site Producer. Annual digital subscription rates payable in U. 972-687-6702 (phone). PT) Senior Site Producer. Klein 2 msdn magazine 0118msdn_Masthead_v3_2. $25. $35. Mark Michaelis. e-prints.O. POSTMASTER: Send address changes to MSDN Features Editor Sharon Terdeman Magazine.indd 2 12/12/17 8:56 AM . Audience Development is no guarantee that the same or similar results may be Henry Allain & Data Procurement Annette Levee achieved in all environments. Digital Strategy Becky Nagel Chief Executive Officer Corporate Office (weekdays. Suite 101.. Dan LaBianca & Lead Generation Marketing Irene Fincher Director. telephone. Return Undeliverable Canadian Addresses to Circulation Dept. Frank La Vigne. Platt Printed in the U. Enterprise Computing Group Scott Bekker all others $12. Merit Direct. Inc.S. Inc. is available for rental.com Irvine Office (weekdays.00.m. 9201 Oakdale Ave.com PRODUCTION STAFF Vice President. IL 60076.com Art Director Michele Singh Senior Program Manager. Client Services & Webinar Production Chris Flack REPRINTS For single article reprints (in minimum Art Director Chris Main quantities of 250-500). Phone: 913-685-1301.S. Annual subscription rates payable in US funds Editorial Director Jennifer Mashkowski mmeditor@microsoft. P. 8:30 a. Advertising Sales Associate Tanya Egenolf E-mail: To e-mail any member of the staff. James Bowling Erik A. Contributing Editors Dino Esposito.S. Lead Services Michele Imgrund the information has been reviewed for accuracy. dlabianca@1105media. Implementation or use of any information contained herein is the reader’s sole responsibility. Art and Brand Design Scott Shultz prohibited except by written permission.S. Technical inaccuracies may result from printing errors and/or new developments Chief Revenue Officer Director. CA 92618. Send orders with payment to: MSDN Magazine. Suite 150. funds are: U.com ART STAFF Production Tracy Cook Creative Director Jeffrey Langkau Director.m. Richmond Hill. Site Manager Kent Sharkey International $25. Events Danielle Potts Web: meritdirect. General Manager Jeff Sandquist Ste. – 5:00 p. Chatsworth.00. PT) ONLINE/DIGITAL MEDIA Telephone 949-265-1520.O. Ted Neward. 4 Venture. IL 60132. – 5:30 p. Fax 949-265-1528 4 Venture.com or call (847) 763-9560. Untitled-9 1 12/8/17 2:35 PM . As he writes in in Microsoft OneDrive. Microsoft Cognitive Services. Graph is a family of rich.” in the form of Microsoft Graph.” Visit us at msdn. consistent REST APIs that provides vital connective tissue between applications. In our Ammerlaan says the Graph APIs Connect(). as Arenas updated. Outlook. MSDN and Microsoft logos are used by 1105 Media. In the article. “Building Microsoft Graph required coordinating API designs how do you link up and imbue that data with context. the more useful by far the net set of products you build could As director of product marketing on the Microsoft Office be—greater than the sum of Ecosystem team.com/magazine. Questions. Azure Active Directory. and then perform voice recognition via the article: “The more APIs you can bring together and connect. you are not permitted to transmit copies of MSDN Magazine (or any part of MSDN Magazine) in any form or by any means without the express written permission of Microsoft Corporation. In this issue of MSDN Magazine. the benefits of adopting Microsoft how the extensions can be used to access and prepare files stored Graph compound with investments into the APIs. store. intelligently interpreted. So while Graph APIs are conceptually similar to exist- wrote. MSDN Magazine is published by 1105 Media. of a years-long effort that demanded a strategic rethink across ated in and captured by productivity applications such as Word.com/library/toolbar/3.mspx. “The breadth of tools. 1105 Media. © 2018 Microsoft Corporation. Ammerlaan says the Graph APIs are the result its parts.indd 4 12/12/17 8:52 AM . A listing of Microsoft Corporation trademarks can be found at microsoft. vastly simplifying developer interaction product-specific APIs like SharePoint REST continue to be actively across all of Microsoft’s APIs by bringing them together. Microsoft Corporation is solely responsible for the editorial contents of this magazine. Ammerlaan But the most important thing is that this capability is accessed via a suggests a measured approach. Excel. Microsoft continues to refine. with respect to any code or other information herein and disclaims any liability whatsoever for any use of such code or other information. leveraged and consumed? allowing for quick evolution while building a more universal and It’s a question that Microsoft has spent years working to answer. Ammerlaan says. is an independent company not affiliated with Microsoft Corporation. Functions Binding Extensions can be used to automate common and documentation make Microsoft Graph the best way to access tasks and processes. Inc. or introduce into a retrieval system MSDN Magazine or any part of MSDN Magazine. Other trademarks or trade names mentioned herein are the property of their respective owners. Editor’s Note MICHAEL DESMOND Going to Graph It’s been a challenge since forever: How do you unlock the data cre. its Graph APIs. If you have purchased or have otherwise properly acquired a copy of MSDN Magazine in paper format. He notes that many existing single REST API endpoint. and IT resources and data stores. OneDrive. SharePoint.” ing product APIs.0/trademarks/en-us. teams at Microsoft. Without limiting the rights under copyright. I’m convinced every enterprise applica- using Binding Extensions to pull together disparate sets of data in tion could benefit from Microsoft Graph to be at its most effective. intelligence and APIs housed in Microsoft’s intelli- gent cloud.” one piece of code using a single authentication token. Ammerlaan walks through Microsoft data and insights. “Microsoft are the result of a years-long Graph: Gateway to Data and Intelligence” (msdn.” She went on to describe how the intelligent Graph engine uses machine learning to provide calculated insights and rich relationships. Azure cloud infrastructure. “in a single URI namespace with a single authentication story. Microsoft Corporation does not make any representation or warranty. so it can be and consistency across a dozen teams (and growing) at Microsoft. Inc. SDKs. Mike Ammerlaan “For new projects.microsoft.com/magazine/mt790189). special issue last year. There. These recommendations or guidelines may not apply to dissimilar configurations. under license from owner. Planner.” says Ammerlaan. Outlook. The recommendations and technical guidelines in MSDN Magazine are based on specific environments and configurations. MSDN Magazine. express or implied. improve and extend lot of factors. 4 msdn magazine 0118msdn_DesmondEdNote_v3_4.” in which he describes how the new Azure to new projects. All rights reserved. you are not permitted to reproduce. For organizations looking to migrate to Graph.com. the decision to shift to Graph depends on a A year later. Microsoft Principal Program Man- ager Yina Arenas explored the Graph APIs in her article. rethink across teams at Microsoft. she described Graph as “the unified gateway for developers to effort that demanded a strategic access all the data. He shows Over time. Otherwise. Complying with all applicable copyright laws is the responsibility of the user. Inc. I think developers should strongly consider writes “Build the API to Your Organization with Microsoft Graph evaluating Microsoft Graph and seeing what facets of it may apply and Azure Functions. OneNote. SharePoint and OneNote? And just as important. consistent API. you are permitted to physically transfer this paper copy in unmodified form. Excel and more. including Exchange. comments or suggestions for MSDN Magazine? Send them to the editor: mmeditor@microsoft. Untitled-4 1 11/27/17 3:38 PM . different parts of you—shifts Part II. TV personalities. longer running away from V1. because those were hallmarks of V1. parts don’t yet understand what’s happening. I’ll answer this in two parts: First. when engineers say “lack of confidence. by examining confidence As an example. You’ve just uncovered a what they really mean is that they feel stuck. act in Behind the Scenes opposite ways and associate with people you wouldn’t normally This process is more common among those who are sensitive and associate with. friends. an engineer who’s wasting all his time at work on itself. you’re striding toward V2. The unfamiliarity can jolt the system so much that introverted. Carefully self-monitor your exposure to draining people. That’s excellent growth! Yet. haven’t gotten to know V2 yet. keep trying again. think opposite thoughts. read the books and watch the videos of those who do. Was that growth spurt RadicalShifts. people for so long that their identity has become the sum of their So. things start to fall apart. with greater urgency. he may notice that he now starts binging on the Internet like he’s never binged before. and associated with certain moment. it’s not They don’t yet know that V2 is just a healthier upgrade to V1. your desires. est binge to the act of him seeking help. getting your bearings? umn. “If I were supremely confident in this moment. He panics. You can ask yourself. anytime you take on a new identity or set of behaviors. So.indd 6 12/12/17 9:01 AM . you may reach a point where a little more your productivity and your outlook toward people. you may find yourself in a funk—it’s as if the growth you experienced never even happened. by discussing what to do if. help! He reasons that at least his old problem wasn’t this bad before. or older parts of yourself that are used to seeing only V1. No matter how many times you realize something: Confidence is the natural outcome of hundreds fall down in your quest to become V2. optimistic. actions. And when that happens. you begin to The solution is deceptively simple. after you take the the Internet may finally admit that he has a problem. from a friend. If you don’t They’ll bring back older desires and compulsions with greater know any. They your job to fix or teach them. but they lack perspective. They have believed big insight.” You may see this in your own careers. not long after. a new Basically. and of small acts of courage. These older parts have your best inter- Until you build up your own emotional reserves. you’re no success that had seemed a struggle. Fortunately. you may feel suddenly overwhelmed. Visit nal problems may suddenly get a lot worse. out the company of those with a higher self-image. positive. acted certain ways. you stop. In fact. and stops seeking fessional growth. Once you take the leap. The fastest way to grow confidence is to be around (V2)—and who you no longer want to be—Version 1 (V1). and friendships. that they’re being attacked. The Reframe problem is back. These older online acquaintances who are self-flagellating or unkind to them. opinions. ests at heart. The engineer then connects his lat- Feeling lack of confidence is very common. and second. just when you were finally confidence” in taking their next big professional leap. and in that space. His old Part I. To break out of the pattern. self-assured people. 6 msdn magazine 0118msdn_RangaUpstart_v3_6. but now seems easy. your personality. K rishnan R angachari helps engineering managers have more impact. so it’s something software engineers often encounter. Upstart KRISHNAN RANGACHARI Crisis of Confidence I’m often asked by engineers how they can overcome their “lack of a fluke? Why is it all falling apart now. In this col. a little more of you—your will. and go back to the old ways. They may even feel selves. Play it. set up an internal battle between who you’re trying to be—Version 2 Catch it. such inter. and taken a positive next step. they try to bring back actions can drain you. because that’s their conditioning. and seek help leap. your origi. bigger than ever. force. Every time you do this. what tiny step would I take right now?” Then. dramatic strides in Over a period of years. even out-of-control. Doubt it. But right at this crucial certain thoughts. go do An Answer it! When you do this in small ways here and there. Sometimes. You may be running low The process of unlearning your V1 habits creates a struggle with on confidence because of coworkers. You may taste of you lives in V2 than in V1. you may make sudden. and it can stunt pro. The Post-Confidence Funk loyalties from V1 to V2. the cure is simple: you seek the only friend they’ve ever known—V1—by any means necessary. Here’s how you can overcome it. you temporarily shed your conditioning. you self-identity can emerge.com for his newsletter and coaching. directly or indirectly. n Yet. you just get back up. docxconverter. a server product for automated processing or an SDK for integration into third party applications. All rights reserved. into DOCX format.indd 1 04/11/2017 15:22 Untitled-1 1 11/6/17 12:24 PM . © Amyuni Technologies Inc. Create Convert OCR Create naturally editable DOCX Convert images and graphics Use OCR technology to convert documents with paragraph of multiple formats into non-editable text into real text formatting and reflow of text DOCX shapes Extract Open Configure Extract headers and footers from Open PDF documents with the Configure the way the fonts are source document and save them integrated PDF viewer and quickly embedded into the DOCX file as DOCX headers and footers resave them to DOCX format for optimal formatting A virtual printer driver available for Windows 7 to Windows 10 and Windows Server 2008 to 2016 Powered by Amyuni Technologies: Developers of the Amyuni PDF Converter and Amyuni PDF Creator products integrated into hundreds of applications and installed on millions of desktops and servers worldwide.com Amyuni DOCX Converter for Windows Convert any document. Enable editing of documents using Microsoft Word or other Office products. Free Demo at DOCXConverter. A standalone desktop version. www.com All trademarks are property of their respective owners. including PDF documents. MSDN Ad DOCX Converter 02. You Azure Cosmos DB is the next generation of what began life as Azure can also use Visual Studio Code in combination with the Azure Document DB—a technology I’ve written about numerous times command-line interface (CLI). a cross-platform realigned so that there’s more to choose from than just strong and option. anything you build bounded-staleness. (a simple task) and from there. You can read much more about Cosmos DB by starting at cosmosdb. as well. One is with tooling A Bit About Azure Cosmos DB in Visual Studio 2017. in its current state. Custom Azure Functions 8 msdn magazine 0118msdn_LermanDPts_v5_8-14. of the moving parts. To achieve that goal. Between those two extremes. Preparation for Building the First Azure Function There are three ways to build Azure Functions. and the docu. there are lots of fabulous resources for doing this with some extraordinary features. And a Bit About Azure Functions I’m going to use Cosmos DB to store the CookieBinge scores. But was basically an excuse for me to explore using Entity Framework having finally had a chance to work with Azure Functions. you’ll also have your aha moment. its consistency models have been the portal is that it’s Web-based and. Data points JULIE LERMAN Creating Azure Functions to Interact with Cosmos DB In my last column. Besides the ease with which in Visual Studio 2017. All of these models are under the Cosmos DB umbrella. it was automatically switched to an Azure Cosmos DB. I’ll be using two cool features of Azure: Azure Cosmos DB and Azure Functions. The addi. allowing your existing document database to benefit from all of the new features Cosmos DB brings. users can now also choose and assets from source control into Azure. I was forced to think a little harder about all way of a Node. stores game scores locally on the APIs. I now Core 2. while it takes the picture to make this a possibility.com/magazine/0118magcode. just not my server. Another benefit is that without the help of the Visual articles where I used it as the back end of an Aurelia Web app by Studio 2017 tooling. I feel I got a much better understanding that DocumentDB evolved to become a globally distributed database way. care of the cross-cutting concerns such as deployment. graph databases. Keep in mind. Figure 1 A Bit of the Template List for Creating New.. I decided to start my learning by in this column. I walked you through building a simple Universal computing” offering. In fact.com. Of course. pushed to your repository. In that last article. table (key/value pair) and column data storage.0 to per. I promised the myself.. but the other thing I like about using it can be distributed globally. if you had an Azure DocumentDB. while you can deploy your function code eventual. other game players on the Internet. or sending e-mails. session or consistent prefix. I’ll take advantage of another relatively new feature of Azure: Azure Functions.com/magazine/mt147238) in June 2015 was followed by two more I needed. “An Overview of Microsoft Azure DocumentDB” way of the portal because it walked me through all of the steps (msdn.0 (EF Core) in a device-bound Windows 10 app.js server API. I didn’t totally understand this until I did it sist the data to a SQLite database. have a great respect for the concept. How- ever. Another is directly in the Azure portal. and connections to other functionality such as data storage device where the game is being played by using EF Core 2. Azure Functions lets you focus tion of providers for portable databases such as SQLite complete on the actual logic you want to perform in the app. supporting The app. ment database is now joined by a number of other data models— documents accessible via MongoDB APIs. rather than write all of the code myself using the Document DB APIs. Azure Functions is the Microsoft “serverless Code download available at msdn. There are many directly in the portal will have to be downloaded to your machine more important features to support the data store.indd 8 12/12/17 8:55 AM . I’ve always been a skeptic about that phrase Windows Platform (UWP) app—a game called CookieBinge—that because the computing is still on a server . so my hope is that by following my path as I prepare this next iteration of this game would allow users to share that data with feature for the CookieBinge app. therefore. and the function is flexible Azure Functions is a service that’s grouped in a function app that allows you to define and share settings across its set of functions. The function is built into a file called devices on which they’re playing. In the sample. For easy future access to your new func- tion app. but if you scroll down below those buttons. PowerShell. My functions will be built to support the list of goals men- tioned earlier. though of course you’d need that for Azure will call in response to an HTTP request to this func- the real world. persisting not only some user Name the function and then click the Create button. You can have additional logic in supporting •A llow a user to retrieve the highest scores across all users. part of my Visual Studio subscription. but that’s more advanced than needed for this first look. Go to azure.azurewebsites. click on the will be free for a year and there are a few dozen that will always be plus sign next to the Functions header. The portal provides a slew of templates in a vari- If you want to follow along and don’t already have an Azure ety of languages: Bash. but also the mine StoreScores. type of device the game was played on.net. In the Azure portal.com/free to get set up. or an event in a blob or a queue. I’m not going to bog this lesson down with matters like creating The only method in the example is called Run. Some Azure products To create the first function inside the function app. a change in a Cosmos DB database. you can see that the function is looking for Creating the Azure Function in the Azure Portal incoming data that represents a name. Now you can add some functions into the function app. such as a name for your app. I want functions that respond to Figure 2 Default Function Logic for a New HTTPTrigger requests coming over HTTP.com January 2018 9 0118msdn_LermanDPts_v5_8-14. • Store user scores on the Web. I’ll use C#. run. I’m using the account I get as pre-defined functions. I want in Figure 1. My aim is to show you Azure Functions and. even. files. you to fill out some metadata. As this is just a simple demo. including an HTTP request.indd 9 12/12/17 8:55 AM . which is what and authenticating accounts. Because I want to call into these functions from the UWP app. Python and TypeScript. HTTP Trigger – C# should be at the top of that list my app to be able to: and that’s what you should select. JavaScript. F#. I’m happy to inform you that you can get a free sub. The Azure Functions service has a pre-defined (and quite rich) set of events it can respond to. Batch. click New and filter on “function app” to easily find that option. subscription. C#. which prompts Figure 3 Defining the Functions Integration Points msdnmagazine. PHP. scription. It took only about 30 seconds for my new function app’s deployment to be completed. Click Function App in the results list and then Create. I named mine cookiebinge. and you’ll see a scrollable grid filled with template options. as well.csx (see Figure 2). I’ll start by creating a new func- tion app. I named information and the date along with the score. tion. You’ll see buttons to create free. as shown Before creating the functions. Choose that option allowance for experimenting with Azure. So. the interaction from the UWP app. relaying information to a log. I’ll accept the rest of the defaults on the Create page. The portal will create a function with some default code so you • Allow users to retrieve their highest scores across all of the can see how it’s structured. which has a monthly credit you’ll find a link to create a custom function. I need to define my goals. It has one parameter to capture the request and another for tually. and it’s not just for a short trial. check the Pin to Dashboard option and then the Create button. csx. The new version of the func- to Interact with Cosmos DB tion expects a JSON object passed in that aligns with this BingeReq- The goal of the function is to store the incoming data into a uest class.set. But I also want to log.indd 10 12/12/17 8:55 AM .userId). BingeDocument. add an output that has a Cosmos DB collection as its destination.CreateResponse(HttpStatusCode. so I’m going to use one of those. There’s no public string userId {get. The Document Parameter Name represents the } parameter you’ll use in run. public int score{get. .csx file below the Run method: public class BingeRequest{ Cosmos DB database. The constructor takes a populated BingeRequest and after setting the value of logged. } public class BingeDocument { .} number of other Azure products—and Cosmos DB is one of them. as well as adding one more property products—and Cosmos DB is named logged.Verbose("Outgoing userId:" + doc.OK. which inherits from BingeRequest.} public string deviceName {get. } with defaults.log). . as well as the connection to the Cosmos DB account where the database lives. the function will return an Http the database and sees that it doesn’t exist.set. but not when I enough to search for it in the query parameters and in the request save this output. To do this.} public bool worthit {get. You know } else { what to do.Content. if (doc. I’ll do that using a second integrate easily with other Azure class. thereby inheriting all of its properties. IAsyncCollector<object> outputDocument) { thing through HTTP. } outputDocument. If the name isn’t found. returns “Hello [name]” in the response. which will display a list of icons. I do want to keep that HTTP output.set.BadRequest. it transfers the BingeRequest one of them.} need to create connections and commands and other code to do public string userName {get. Notice that it says public static async Task<HttpResponseMessage> Run(HttpRequestMessage req. further down on the page you’ll see a SELECT button. and the collection within that database. message. I’ll leave that as the default name.userId). . the trigger is an HTTP request and that the output returns some.Verbose("Incoming userId:" + bingeData.csx Customizing the Function Now it’s time to redefine the function code. await outputDocument. (Click that button!) return req. Because I marked the checkbox to create the Figure 4 Defining a Cosmos DB as Output for the Function database and collection.} this task. you should see your new function and Storing It into the Output. Azure Functions has the ability to integrate easily with a public DateTime dateTime {get. Select that and using System.ReadAsAsync<BingeRequest>(). var doc=new BingeDocument(bingeData.csx File Capturing the Binge and In the Functions list. Next are the names of the Cosmos DB database 10 msdn magazine Data Points 0118msdn_LermanDPts_v5_8-14. When the function first attempts to store data into body.$"{doc.set.CreateResponse(HttpStatusCode.} } But this is not the same structure as the data I want to store Azure Functions has the ability to because I want to capture one more property—the date and time the data is logged into the database. Because I want to return a success or failure BingeRequest bingeData = await req. which I added into the run. Customizing Run. select it and then return req. values to its own properties: Figure 5 The New run. public class BingeRequest{ ." ). click on New Output.set. those will be created for me. log.AddAsync(doc). . The screen to set up this integration gets pre-populated $"The request was incorrectly formatted. Figure 4 shows how I’ve filled out this form before sav- ing the output definition. the function will create ResponseMessage with a friendly error message. Here’s where the magic begins. I already have a few Cosmos DB accounts created. You’ll also see a checkbox to automatically cre- ate the database for you.Net. but I let my function create a new database named CookieBinge with a collection called Binges in that account.userId} was created" ). Cosmos DB three items below it.set. One of those items is Integrate. TraceWriter log.userId !=" " ){ Scroll down to the one called Azure Cosmos DB. otherwise it the database on the fly. you’ll see the form partially shown in Figure 3. Untitled-6 1 3/6/17 2:32 PM . output parameter name in the output configuration in Figure 4. and when you save. public BingeDocument(BingeRequest binge){ Next. without the IDEs that let you debug. For example. It gets stored into the DocumentDB as JSON— the function converts it again in the background for you.set. also get output to the debug window. I asynchronously add the BingeDocument I just created guage you’re working in.userName. The code window is amazing score=binge. with results being dis- played in the log window below the code window. I return a message via HttpResponse.csx. Finally. I instantiate a new BingeDocument. Compiling and Testing the Function Functions get compiled when you save them. Because I wired everything up with the inte- gration settings. but it’s like in the logs so.deviceName. right- click on the editor window to see the long list of editor features of which you can take advantage. The TraceWriter lets me output messages to the log window that’s I then use the TraceWriter to show some data from the request below the code window. wrong.indd 12 12/12/17 8:55 AM . including placeholders for the BingeRequest and BingeDocument classes working in. very detailed. dateTime=binge.} at parsing the language you’re } With these types in place. into the asynchronous outputDocument. Notice that its name aligns with the the debug window. I’ll take these out eventually. any compiler errors. Its signature takes a request any compiler errors. in an opening brace. along with the logged property populated. } public DateTime logged{get. Don’t get me indeed get the data from the request object. The result of that outputDocument object is what gets sent to Cosmos It also does things like inserting a closing brace when you type DB by the function. Figure 6 The Log Window Displaying Compiler Information Including Errors The first line of code in Run asynchronously reads the request public class BingeDocument:BingeRequest { and converts its result into a BingeRequest object. the Run method can take advantage of them. which are very detailed. relay- ing the function’s success or failure. but now it also has an asynchronous output parameter named outputDocument. though. described earlier. in fact. The code window is amazing at parsing the lan. When all is said and done. Figure 6 shows the compiler output. Let’s parse the new Run method. I’m going to randomly delete something important in the code so you can see the compiler in action. BingeDocument object. passing in the object logged=System. also get output to The result of the output parameter is what will get pushed to the Cosmos DB output I defined. highlighting the chaos I created by deleting an open brace from line 13. and when you save. userId=binge. I just created from the request. I don’t have to write any code to make that happen. There are an impressive number of editor features.score.DateTime. Figure 5 shows the modified listing for run.Now. Even Figure 7 The Test Pane After Running a Test on the Function without a debugger. when debugging.dateTime. which are and a TraceWriter just as the original signature did. I can tell if BingeDocument did the old days.userId. which results in a fully populated userName=binge. deviceName=binge. I’ve found that 12 msdn magazine Data Points 0118msdn_LermanDPts_v5_8-14. com Untitled-1 1 11/6/17 12:31 PM . File Format APIs Americas: +1 903 306 1676 EMEA: +44 141 628 8900 Oceania: +61 2 8006 6987 sales@asposeptyltd. The Postman or Fiddler application. The other tab is for running tests. "score" : "5". The test will call the searching. Click on Binges to open up the Data Explorer for that collection. although the only one I have is settings defined in the UI. Thanks to the following Microsoft technical expert for reviewing this Figure 9 Looking at the Stored Documents in Cosmos DB in the Portal article: Jeff Hollan 14 msdn magazine Data Points 0118msdn_LermanDPts_v5_8-14. function. That URL is what I’ll use in the CookieBinge app to send data to the cloud. as shown in built-in test UI is like a mini-Postman or Fiddler application for cre. That’s what just got created by the function. the When the code is fixed up and the compiler is happy. In Figure 7. Let’s take a look at display the “Reloading” message followed by “Compilation succeeded. "deviceName" : "XBox". Now it’s time to test the function and you can do that right in the You can do this by first opening the Cosmos DB account in same window where you’re coding the function. there are only two. The test UI defaults to sending This built-in test UI is like a mini- an HTTP Post. ating HTTP requests with a lot less effort because it’s already aware of the function to be tested. my next column will show you how to build two more functions to retrieve different views of the data.csx file I’m in the filter to find it. passing in the request body. you can see the output Looking Ahead If you look back at Figure 7. Mine is called data- code editor are two tabbed panes. but you can use whatever values you want: { "userId": "54321".” that before wrapping up this installment of my multi-part column. Follow her on Twitter: @julielerman and see her Pluralsight courses at juliel.” as well as a Code First and a DbContext edition. I can see all of the currently looking at and a function. Now that you’ve seen how to cre- ate the function and hook it up with Cosmos DB. Microsoft MVP. the document are the properties I defined. ments were stored in the collection. Enter the following JSON into the Request Body textbox. partitioning and more. At the same time. Once I open the account.” as well as the log output from the function in the Logs window. click the Run button on the Test pane. schema is important. and then display any HTTP results in the Output window. You can find her presenting on data access and other topics at user groups and conferences around the world. "userName": "Julie". software team coach and consultant who lives in the hills of Vermont. The final installment will Figure 8 The Binges Collection Listed in the datapointscosmosdb Account show how to call the functions from the CookieBinge app and display their results. so I’ll go to All Resources and type datapoints to the function. the log will Binge collection where this document was stored. and in it. seeing these errors helps me work through code I’ve had to write Viewing the New Data in the Cosmos DB Database without the aid of IntelliSense or other coding tools in my IDEs. By default. so you don’t even need to change that for this test. One displays the list of files related pointscosmosdb. above the code window.indd 14 12/12/17 8:55 AM . so you can see in Figure 9 that two docu- "dateTime": "2017-10-25 15:26:00". The rest are metadata "logged": "" } that Cosmos DB and the relevant APIs use for tasks like indexing. I learned how much I depend on those tools! the CookieBinge Cosmos DB database was created.json file that contains all of the collections and databases there. the run. All you need to do is insert a JSON ob- ject to represent the incoming request. I’ve run the test twice. To the right of the the portal where you created this database.me/PS-Videos. n J ulie L erman is a Microsoft Regional Director.com/blog and is the author of “Programming Entity Framework. She blogs at the datafarm. you’ll see there’s a Get Function URL link “54321 was created. all from O’Reilly Media. Next. This my Binges collection in the CookieBinge database. The first seven properties in "worthit" : "true". What you can’t see here is that as a result of this first successful test. Figure 8. verify. on-premises and in the Cloud – fast. Your Way.com 1-800-MELISSA Untitled-9 1 12/8/17 2:37 PM . easy to use. email. address. Product Ecosystem. and powerful developer We profile. Your Data. standardize.melissa. Data Quality Made Easy. See What’s New at www. Start Your Free Trial www.Melissa. NAME @ Melissa provides the full spectrum of data Our data quality solutions are available quality to ensure you have data you can trust. match and tools and plugins for the Microsoft® enrich global People Data – name.com/msft-pd Melissa Data is now Melissa. phone. and more. a language popular with data in your data science projects. please refer to the 14. This stands in stark con. The steps click on the Create button (see Figure 1). Note that there are similar to Figure 2. Four features were measured from each Workflow of an Azure ML sample: the length and the width of the Workbench Project sepals and petals. Note context menu that appears. scope of this article. Viewing the Code Click on the down arrow to the right of Once the project loads into Azure ML the Filter Species step. level data scientists can also Loading the Iris Classifier Project Templates benefit from the tools provided As noted in my previous column. are imported into the project in lines seven through haven’t already installed Azure ML Workbench. Look for Classifying hand side of the screen. In the context menu Workbench. which is a tool primarily geared toward beginners. In case you were wondering. The focus here will be on building models with scikit-learn. the syntax should be familiar to any C# devel- The Iris data set is a multi-variate data set that consists of 50 oper. click on it and of steps taken to clean the data. It should look Species column is null. The second step is often the more Iris can be determined. I introduced Azure Machine Learning Workbench plotting libraries that provide the language with a rich ecosystem (Azure ML Workbench). While a full tutorial on the Python language falls outside the documentation at bit.ly/2j2NVdH. the data. However. scientific and Project Template by ML algorithms. In the to see what the raw data looks like. additional options to add extra conditions. add names to the columns and remove rows where the Species column is null.py file to view rule is set up to remove any rows where the its contents in the editor. Click on the iris. samples from each of three species of Iris. that doesn’t mean Azure ML Workbench is only for experienced data scientists. Various segments of the scikit-learn. Artificially Intelligent FRANK LA VIGNE Creating Models in Azure ML Workbench In my last column. The Click on the iris_sklearn. 16 msdn magazine 0118msdn_LaVigneAI_v3_16-20. as data rarely scientists and ML practitioners.indd 16 12/12/17 8:53 AM . Azure ML Workbench provides numerous project templates (I used the Linear Regression tem. in Azure Azure ML Workbench. It is an oft-used laborious and time-consuming: wrangling sample data set in data science and ML. Note the number Iris in the Project Templates. This time I’ll utilize the Classifying Iris project template to demonstrate even more features of Azure ML Workbench. the species of the data. plate). the code is This dialog box will be an invaluable tool in Python. Project to create a new project. choose New that this file lacks column names. click on the folder icon on that appears click Edit to display the Filter the left side to reveal all the files included. library. a popular ML and machine learning (ML) practitioners. referred to as sklearn trast to Azure Machine Learning Studio (Azure ML Studio). Now. One of these is scikit-learn. If you in the code. The first step in any ML project is loading tion of these four features. Name the click on the iris. select bench really shines. This is where Azure ML Work- Open Azure ML Workbench. Column dialog shown in Figure 3.dprep file list on the left- project IrisClassifier. a new tool for professional data scientists of tools and utilities. Intermediate and even entry- Intermediate and even entry-level data scientists can also benefit from the tools provided in Azure ML Workbench. Based on the combina.csv file Projects and click on the plus sign. Python Figure 1 Choosing the Classifying Iris comes in a clean format that’s consumable enjoys a diversity of ML. the algorithm will predict to which species of Iris the plant belongs. loading the data. the remaining 65 The first step in any ML project is percent go into X_train and X_test: X_train. Sepal Width.indd 17 12/12/17 8:53 AM . select Open Command Prompt from the File menu. a data Figure 2 The iris_sklearn.py File in the Azure ML Workbench Text Editor structure from the NumPy library): X. Y_train) Logistic regression is a statistical method analyzing data sets where there are one or more variables that determine an outcome (bit.score(X_test.py file separates the DataFrame into two arrays: X for the features and Y for the label. Features make up the various fields needed to make a prediction. is the Species.values. The following iris = run('iris. Y = iris[['Sepal Length'. However. X_test. Now that the data has been cleaned and loaded.format(accuracy)) The best way to understand this is to actually run the code. a popular plotting library for Python.py msdnmagazine. the correct values to the label are known. You can read more about DataFrames at bit. At the command line. A algorithm then discovers the relationships and patterns between pandas DataFrame is a two-dimensional data structure similar to the features and the correct label. The The output is a pandas DataFrame with the cleaned data. 'Petal Length'. as shown here (strictly speaking. test_size=0. To install it. spark=False) line of code randomly reserves 35 percent of the rows in the input data set and places it into Y_train and Y_test. Y_test = train_test_split(X. the features are: Sepal Length.dprep'.35. Once trained. type the following: pip install matplotlib Once installed. the dimensions of the sepals and petals determine the Iris species. the algorithm is tested for accu- racy by calling the score method on the model: accuracy = clf1. The algorithm is trained by passing the features and label to it. In this case.ly/2zQ1hVe). the code loads the data by executing the iris. there’s one more step. The following line creates an ML model with a logistic regression algorithm against the training data: clf1 = LogisticRegression(C=1/reg).dprep file on Once the data is separated into a label and features. random_state=0 In supervised learning. Y.fit(X_train. type the following to the command line: Figure 3 The Filter Column Dialog Window python iris_sklearn. it’s time to line 28. a table in a SQL database or in a spreadsheet. After referencing various libraries and initializing the local envi. before that can be done. 'Sepal Width'. given the widths and lengths for Sepals and Petals. dataflow_idx=0. or pre- dicted value.ly/2BlWl6K.values ronment.com January 2018 17 0118msdn_LaVigneAI_v3_16-20. The label. X and Y are NumPy arrays. Line 32 in the iris_sklearn. Y_train. it’s time to sepa- rate the data into features and labels. In this case. 'Petal Width']]. iris['Species']. which loads the data file and performs all the steps defined: separate the data into a training set and a test set. Petal Length and Petal Width. Y_test) print ("Accuracy is {}". This project uses matplotlib. In this case. I explained how to explore the results of pred = clf2.0.com/magazine/mt814414).25]] print ('New sample: {}'.6792452830188679. f) f.py script either through Azure ML Workbench or the command line. Executing the Code from Within Azure ML Workbench While running the code in the command line is useful. By default. Scroll down to see the Metrics and Visualization sections to see the output from the # Add random features to match the training data X_new_with_random_features = np. there’s little need to continually train a model.pkl'.3. the accuracy of the model is 0. Choose the first record # Predict on a new sample in the data grid under Runs.6.dump(clf1. meaning that it correctly guesses the species of Iris in the test data 67.c_[X_new./outputs/model.format(X_new)) to see basic performance statistics of the run. 1.pkl'.predict(X_new_with_random_features) a job and view the job history. which is done on lines 89 and 98: on the iris_sklearn.py Program tion about the jobs that have run. Please refer to that for more details print('Predicted class is {}'. Azure ML Workbench provides a way to make this simpler and capture informa. you’ll likely notice that the pro- cess takes several seconds. random_state. 'rb') clf2 = pickle.pkl") f = open('. n)] script as shown in Figure 6. Lines 79 through 82 take the trained model and persist it to disk using the Pickle library (bit. After the program The next step is to create some sample data and use the model runs. Review the Run Properties section X_new = [[3. the output should look like Figure 4. Fortunately. On my Surface Book.py entry in the run list. output and details about the run will appear.format(pred)) (msdn. This executes the script locally and tracks the execution of the f2 = open('. Click Run. the process is hardly instantaneous. # Score on the new sample In my previous article.indd 18 12/12/17 8:53 AM .ly/2im9w3O): print ("Export the model to model. 'wb') pickle. 3. click to predict the species. To the immediate left of it. Look for the Run button.randn(1./outputs/model. In a few moments. it takes about nine seconds.load(f2) script via the Jobs tab in Azure ML Workbench.92 percent of the time.close() Lines 86 and 87 demonstrate how to restore the trained model from disk: Figure 6 Metrics and Visualizations Shown in Azure ML Workbench 18 msdn magazine Artificially Intelligent 0118msdn_LaVigneAI_v3_16-20. While different hardware configurations will produce differ- ent results. Most of the pro- cessing time is devoted to training the model. To see that. there are two dropdowns and a textbox. Figure 5 Running Files in Azure ML Workbench it should look like Figure 5. 0. As displayed in the command window.Figure 4 Output of the iris_sklearn. Persisting a Trained Model While running the iris_sklearn. • Rapidly test and prepare apps for Windows 10 without the need for hardware or software • Capture a default install automatically and create customized discovery documentation • The service is configured on a tenant philosophy.New debug visualizer expression map and code analysis diagnostics We accept purchase orders. CHM.New Wizard control and Data Grid scrollbar annotations • ASP.00 Discover.04 Help and documentation for . Splash Screen and Context Toolbar controls • CodeRush .so you only need to load the JavaScript that contains the features you need • A Client-side component .com BEST SELLER Apptimized from $5.New Hamburger Sub Menus. Contact us to apply for a credit account. trellis. but with all the power of a true WYSIWYG XML editor • Single source.439. meaning that customer data is protected • The advanced MSI Editor provides full MSI and App-V editing capability • Supports bulk upload source media. multi-functional. interactive user experience across all browsers • Modularized . /update/2018/01 www.292. • Harness the power of a spreadsheet to display and manage data like Microsoft Excel • Go beyond the grid with cards.com Untitled-9 1 12/8/17 2:30 PM . Chart series types and Unbound Data Source • WPF . test and manage applications in the cloud.works with Windows. efficient. MS Word.1 from $1.New TreeMap control.476. additional Themes. Berkshire Chiyoda-ku GA 30188-5188 RG1 4ET Tokyo.New Vertical Grid control. • Powerful features in an easy.NET and mobile applications. Linux. news feed. Rich Editor Spell Checking and more • Windows 10 Apps . calendar.US & Canada: (888) 850-9911 650 Claremore Prof Way 2 New Century Place 7F Kojimachi Ichihara Bldg Suite 100 East Street 1-1-8 Hirakawa-cho Woodstock Reading. Kindle or print • Styles and Templates give you full design control BEST SELLER DevExpress DXperience 17. Android and iOS BEST SELLER Help & Manual Professional from $586. multi-channel publishing with conditional and customized output features • Output to responsive HTML. 102-0093 USA United Kingdom Japan www. All Rights Reserved. PDF. pure JavaScript spreadsheets for Enterprise apps.componentsource. All prices correct at the time of press. and zip file capability for requests that have multiple EXEs BEST SELLER SpreadJS from $1. ePUB.NET .51 Deliver intuitive.99 The complete range of DevExpress . Online prices may vary from those shown due to daily fluctuations & online discounts. MacOS.NET controls and libraries for all major Microsoft platforms. • WinForms .componentsource. package. © 1996-2018 ComponentSource. accessible and intuitive user interface • As easy to use as a word processor. Gantt. US Headquarters ComponentSource European Headquarters ComponentSource Asia / Pacific Headquarters ComponentSource Sales Hotline . timeline and more • Renders to the HTML canvas for a fast. Next. Sci-Kit Learn. The tool truly brings test data will likely be unusable when given data great capabilities to the data science field.argv) > 1: script a number of times with a different regularization rate each time. such as support for Jupyter notebooks. Because I already ran the script with a parameter of 10. Wintellect and co-hosts the DataDriven podcast. click on the save icon.system('az ml experiment submit -c local .py file with a new regularization parameter that’s half the value of the previous run until the value gets below 0.005. check for the presence of os. the variable and then click the entry for iris_sklearn. of course. click on the Jobs tab.01. matplotlib and. I would like to change line seven to five. To edit the text. choose iris_sklearn.py program executed the if len(sys.argv[1]) Wrapping Up In this article. well on test data. Azure ML Workbench includes several more features that I will fitting the model.ly/2iatJpC.py file. First and graphically to make data foremost is the ability to install and consume any Python library. This program will call the iris_sklearn. More infor- mation about regularization and overfitting is Frank La Vigne leads the Data & Analytics practice at available at bit.py {}'.indd 20 12/12/17 8:53 AM . There’s an option to edit in another program. When com.py. The run. respectively. such as Visual Studio Code. mand-line window and inside the Jobs pane within the Azure ton.py are both selected. click on the files icon and click on the run. like so: data points there are in the graphs. However. While not as straightforward or approachable benefit of exploring the results as Azure ML Studio. the text isn’t editable.py. choose Edit in Workbench Text Editor (see Figure 8). including Pickle. you can see toward the lower python run.ly/2kfLU1f and bit. I explored a common sample data set in data science Tracked jobs have the added with Azure ML Workbench. as shown in Figure 7. Tracked jobs have the added benefit of exploring method and sets the Regularization rate. and click Run once more./iris_sklearn.format(reg)) a parameter.TV). There’s experimentation faster. in this case. Now. The program will run and then pass a command to the under- lying OS to run the iris_sklearn. n outside of the test set in the future. lines 47 and 48. Overfitting occurs when the model performs too explore in future articles. demonstrating the power and flexibil- ity of the program. Note that the charts now have a second data point. browse through it and Figure 8 Switch to Edit Mode this article: Andy Leonard 20 msdn magazine Artificially Intelligent 0118msdn_LaVigneAI_v3_16-20. “Frank’s World TV” (FranksWorld. Azure ML Workbench program: In the iris_sklearn. click on Open Command Figure 7 A Second Data Point Added to the iris_sklearn. Notice the program output in the com- You may have noticed the Arguments textbox next to the Run but. click on the dropdown on the upper-left portion of the text area to switch to edit mode. convert the value to a float. the introduction of additional information in order to avoid over.com and you can watch him on his YouTube channel. A model that provides highly accurate results with source control integration and Docker images.py middle of the screenshot that the predicted class is [‘Iris-setosa’].py file through the Azure Azure Passing Parameters ML Workbench system. Earlier. Notice how many more retains the value it was initialized with on line 45: 0. If no parameters are sent to the program. and then set the reg variable Click on the Jobs icon in the toolbar on the left-hand side of the screen to its value. as you may have already noticed. He blogs Enter the number 10 into the Arguments textbox regularly at FranksWorld. Regularization rate controls the results graphically to make data experimentation faster.py Jobs Tab Charts Prompt from the File menu and type the fol- lowing command and hit enter: If you refer back to Figure 4. reg = float(sys. Thanks to the following technical expert for reviewing pleted. I left this field blank. However. After changing line 7 to reg = 5. making sure that Local and iris_sklearn. Azure ML Workbench opens up a lot more possibilities to the data scientist and ML practitioner.py file. also a command-line interface that can accept commands to install Python libraries and run Python code as tracked jobs inside Azure The reg value gets passed as a parameter to the LogisticRegression ML Workbench. RavenDB comes with a series of built-in fixes 500 Companies. Your community license includes 3 cores. and 6 GB of RAM. and secure RavenDB in a matter before they become an issue. giving you maximum and try it out. RavenDB lets you adapt quickly and seamlessly as you rise up the About Hibernating Rhinos learning curve. but we developed RavenDB creators of RavenDB. make big changes. Reduce latency and boost performance with additional capacity. Execute at millisecond performance right until you hit the limits of your hardware. RavenDB can reach over 100. You can install. Instant replication keeps several copies of your database with you. common problems you can expect to encounter. not to waste precious time and money on the phone with Europe.000 writes and half a million reads per second per node. speed-obsessed. is a leader in open source NoSQL database Keep Your Release Cycle Moving with Fewer Interruptions. adding nodes to your database cluster and replicating your database to them in a matter of hours. a data cluster flexibility. Latin America. one of them running over 1. It’s open source. Make your data integrity a constant with one of database running at once so your customers never have to wait in line. the only document databases that is fully transactional. We want you to use RavenDB to build an transactional (ACID). and resolving them Easy to Install. visit g https://ravendb. Our credo of it just works strives to save your DBA and development team time and resources by resolving the most common issues before they occur. set up. and Israel. a leading OLTP document database that is fully so you won’t need it. Choose your own hosting. Get Started at No Cost Download RavenDB at https://ravendb. Our distributed database lets you operate over a cluster of servers. giving you high-availability to ACID. or in Scale up Quickly. of minutes. On commodity servers. Be ready for high traffic days like Black Friday by the cloud through AWS or Azure. Our agile database is schemaless. Hibernating Rhinos LTD. It’s customer base includes Fortune our support engineers. There is no need for expensive migrations. and a pleasure to use. Enjoy the Best of All Worlds RavenDB employs the latest in database development to benefit your business in several ways: High Speed Performance. For more information. It’s founder Oren Eini and his team are the provide the best support in the industry.0 to tackle the most common challenges your database faces in handling the scale and scope of today’s data. The ramp up to learn is very quick and our SQL like query language makes RavenDB easy to use.5 million instances of that help you cut down on overhead by anticipating the most RavenDB. Hibernating Rhinos operates in the United States. Upgrade to NoSql and take the best part of a relational wherever your users are. You don’t have to fight your schema every time you want to with up to 3 nodes.net/ Untitled-9 1 12/8/17 2:33 PM . We architecture and design. MSDN MAGAZINE VENDOR PROFILE magazine RavenDB OLTP Made Simple RavenDB is one of the few fully transactional NoSQL databases. Always be there for your users. our state of the art GUI interface.net/get-ravendb-for-free Flexibility. You can run RavenDB on-premise. application. What Makes RavenDB Unique We developed RavenDB 4. so they can devote more energy towards useful work. indd 22 12/12/17 8:59 AM .NET Framework. and its name is Span<T>. You’re implementing an operation and a length.NET for safe and efficient And depending on the type of data involved. eliminates the safety guarantees over System. char[] and char*? well with full arrays or with subsets of arrays.NET. . such as a specialized parsing method. You’d that are core to .NET runtime optimizations when working with spans Technologies discussed: What Is Span<T>? Microsoft . an offset and a count. But what if you wanted to support data in like one they created with stackalloc to use some space on the memory that wasn’t in an array. however. as mentioned in the array example. That. stack. you might be able to use unsafe code and equally well with managed arrays and unmanaged pointers? pointers. and yet worked equally well with inputs of on such an arbitrary region of memory. . but instead came from native code. You’d likely expose a method be used to carve out just the piece that’s interesting to them. getting a pointer memory access at all may not be practical. but then what if the caller doesn’t have of it sorted? You’d probably then also expose an overload that took a string but instead has a char[]? Or what if the caller has a char*.Substring could operate in-place on data in memory.NET All About Span: Exploring a New . involving a string allocation over that T[]. and yet worked equally type string. or as the result of a call to native code? How could you write for example. 22 msdn magazine 0118msdn_ToubSharp_v6_22-27. overruns and access violations that for most . • New Span<T> and related types in . but that takes an array and provide an implementation that operates that’s a relatively expensive operation. a thing of the past.NET Mainstay Stephen Toub Imagine you’re exposing a specialized sort routine to port operating over a subset of that string? String.NET Core.NET developers are mentation that operates on strings. wants the whole array sorted.Span<T> is a new value type at the heart of . or lived on the stack and you only had a pointer and your parsing method in a way that didn’t force the caller to do any a length? How could you write your sort method that operated allocations or copies. You could. • New C# language features for working with spans There’s an answer to this conundrum. • . It enables the representation of contiguous regions of arbitrary memory. It also invites additional performance pen- alties. exposing an implementation that accepted a pointer Or take another example. but what if the caller only wants part take an offset and a count. But what if you wanted to sup. and that also worked In both situations. such as needing to pin managed objects for the duration This article discusses: of the operation so that the pointer you retrieve remains valid. That’s great if your method’s caller has an array and and memory copy.String.NET and opens you up to problems like buffer likely expose a method that takes a string and provide an imple. C# System. string worldString = str. utilizing an overload of the (where the 0th index into the Span<int> maps to the first four span’s Slice method. which provides semantics like that of that’s likely much more familiar: indexing into arrays.ReadOnlySpan<T>. Span<T> is a value type containing a ref and a length. // OK Assert.ReadByte(ptr). ReadOnlySpan<char> worldSpan = And it does so while still providing safe access with performance str. with the JIT introduced in C# 7.Equal(42.Equal(127. bytes[1] = 43. // Throws IndexOutOfRangeException while to have at least a basic understanding of the details behind bytes[2] = 45.Equal(43. Here’s an example: struct MutableStruct { public int Value.Equal(42.0 called ref returns. as shown here: and to pass around.” enabling it to work with immutable lates both. you can easily and efficiently create a span to repre. worldSpan[0] = 'a'. efficient as on arrays: indexing into a span doesn’t require enables read-only access. location rather than returning a copy of what lives at that location: var values = new int[] { 42. types. (By contrast. bytes[0]).Equal(42. } Assert. For example: Span<byte> bytes = stackalloc byte[2]. which (optimizations aside) you have a ref T on the stack. From this brief description. } } AddOne(ref values[2]). // Error CS0200: indexer cannot be assigned to For example. offset field.NET. How Is Span<T> Implemented? Assert.Equal(arr[2]. called System. and the C# 7.. Span<byte> bytes = arr. as the ref field itself already encapsu- readonly T” instead of a “ref T. Types that contain such refs directly or indirectly are called ref-like Span<MutableStruct> spanOfStructs = new MutableStruct[1]. length: 5). is provided by native code via interop. The concept of a ref T field may be strange at first—in fact. bytes[0] = 42.Equal(43. Consider a ref usage with a “ref T” return type. and its usage constraints. } . unsafe { bytes = new Span<byte>((byte*)ptr. bytes[0] = 42. as those details imply something about both its performance Assert. However. As mentioned.) msdnmagazine. spans support the notion of reinterpret From there. such as to memory allocated from a native heap. But } finally { Marshal.. For example. lengths.. using is implemented. private readonly int _length.Slice(start: 7. Span<T> is defined in such a way that operations can be as A second variant of Span<T>. like so: defined approximately as follows: IntPtr ptr = Marshal.. Developers generally don’t need to understand how a library they’re Assert.Value = 42. spans are more than just a way to access and subset arrays. spanOfStructs[0].. such that example. slicedBytes[1] = 43. it’s worth- slicedBytes[2] = 44.Substring(startIndex: 7.. or is on the stack. The ref T in is not ref returning. Span<byte> bytes. it.String.com January 2018 23 0118msdn_ToubSharp_v6_22-27.2 compiler allows declaration of such ref-like Assert. safely and efficiently. slicedBytes[1]). // Throws IndexOutOfRangeException one can’t actually declare a ref T field in C# or even in MSIL.FreeHGlobal(ptr). . spanOfStructs[0].2 feature to return a “ref and its starting offset. returning a reference to the actual storage public static void AddOne(ref int value) => value += 1. types by using ref struct in the signature. // throws IndexOutOfRangeException More generally. bytes[2] = 44. bytes[0]). The impact of this ref-returning indexer is most obvious via This code passes a slot in the array by reference. characteristics like that of arrays. // Allocates object. bytes[1] = 43. Assert. } the Span<T> is the same idea.Equal(arr[5]. Assert. // Implicit cast from T[] to Span<T> mentioned. 1).Equal(arr[6]. public ref T this[int index] { get { .AllocHGlobal(1). arr[2]). ReadOnlySpan<T> makes it very ef. // No allocation Assert. simply encapsulated inside a struct.indd 23 12/12/17 8:59 AM . ArraySegment<T> has a separate data types like System. 126 }. except its computation to determine the beginning from a pointer indexer takes advantage of a new C# 7. they can be used to refer to arbitrary pointers and First. bytes[1]).Equal(Marshal. Assert. The indexer is declared generating for it the equivalent of a ref T field. Assert.Equal(45. They can also be used to refer to data on the stack. 84. bytes[2]). making it more expensive both to index into ficient to slice strings without allocating or copying.. world". you can create a Span<T> from an array: Spans provide a multitude of benefits beyond those already var arr = new byte[10]. // Using C# 7.Value). . worldSpan[0]).AsReadOnlySpan(). } Span<T> is actually written to use a special internal type in the The Span<T> indexer takes advantage of a C# language feature runtime that’s treated as a just-in-time (JIT) intrinsic.2 stackalloc support for spans System. length: 2). slicedBytes[0]). regardless of whether that memory is associated with a managed string str = "hello. var listOfStructs = new List<MutableStruct> { new MutableStruct() }. That way if you read a buffer of bytes.Equal('w'.Slice(start: 5. bytes[0]). // Error CS1612: the return value is not a variable 1. two things should be clear: listOfStructs[0]. to write and read data in the relevant portion of the original array: you can pass it off to methods that operate on grouped bytes as ints Span<byte> slicedBytes = bytes. From there you can index into the resulting span bytes of the Span<byte>). length: 5). slicedBytes[1]). casts. slicedBytes[0]). public readonly ref struct Span<T> try { { private readonly ref T _pointer.. Assert. meaning you can cast a Span<byte> to be a Span<int> sent/point to just a subset of this array.Value = 42. values[2]).Span<T> is a new value type at the heart of . This type is just like Span<T>. slicedBytes[0] = 42. in the case of Span<T>. such as by comparing it with the List<T> indexer. Assert.Equal(42. for example: Span<byte> interiorRef1 = arr. you var arr = new byte[100]. This means you can’t box spans (and thus can’t use Span<T> with existing Figure 1 Non-Allocating/Non-Copying Conversions Between Span-Related Types reflection invoke APIs. It means you can’t ArraySegment<T> Memory<T> Implicit cast. a second thread reads the abstract class that can be used to wrap data that needs to have its span. what’s the answer? Memory<T>. and ref fields You can create a Memory<T> from an array and slice it just as can refer not only to the beginning of objects like arrays. and so on exist whether dealing with T[] ReadOnlySpan<T> Ctor. but also you would a span. See Figure 1 for machine’s word size.NET containing a second and related set of types. This highlights sponding _length of 50. OwnedMemory<T> is an can set the corresponding _length to 20. but the heap. AsReadOnlySpan method become fields on classes..Span } is a relatively expensive operation for the . marshaling methods stored to the heap (and there’s currently no Span<T> ReadOnlySpan<T> Implicit cast..DangerousCreate(arr. ReadOnlyMemory<T>. If multiple threads read and write a span’s fields these types. AsSpan method Yet. Stream stream) Span<byte> interiorRef2 = new Span<byte>(arr. and tracking them // Or buffer. What Is Memory<T> and Why Do You Need It? } Span<T> is a ref-like type as it contains a ref field. or even in ArraySegment<T> ReadOnlyMemory<T> Implicit cast. rather. Span<T> instances can only live on the stack. .NET 0118msdn_ToubSharp_v6_22-27. It means you can’t use spans in places where they might implicitly ArraySegment<T> ReadOnlySpan<T> Implicit cast. Implicit cast Most of the issues cited at the beginning of T[] Memory<T> Ctor.NET runtime’s garbage collector.indd 24 12/12/17 8:59 AM . return Checksum(buffer. { Span<byte> interiorRef3 = int bytesRead = await stream. Further. 24 msdn magazine . T[] Span<T> Ctor. Implicit cast. Then.typed as T[]. including the new _pointer but the old (and longer) _length. Implicit cast. Then.Length – 20). AsReadOnlyMemory method memory. if Span<T> can’t be stored to the heap and void* ReadOnlySpan<T> Ctor thus can’t be persisted across asynchronous void* Span<T> Ctor operations. AsMemory method have Span<T> fields in classes. the runtime constrains these refs to only live static int Checksum(Span<byte> buffer) { . T[] ArraySegment<T> Ctor. it’s stored as an object.Slice(0. private readonly int _index. as instances of that type argument ReadOnlyMemory<T> ReadOnlySpan<T> Span property could end up getting boxed or otherwise ReadOnlySpan<T> ref readonly T Indexer get accessor. private readonly int _length. Memory<T> has a interior pointers that might be in existence. These references are called interior pointers. 2. AsReadOnlySpan method synchronous or asynchronous operations.” Imagine an You’ll notice that Memory<T>’s _object field isn’t strongly already initialized span containing a valid reference and a corre. on the heap at the same time. read-only equivalent. can get a Span<T> from it.Slice(0. as it provides an implicit low limit on the number of As with Span<T> and ReadOnlySpan<T>. for instance by ArraySegment<T> Span<T> Implicit cast. These limitations are immaterial for many Span<T> ref T Indexer get accessor.Buffers.Length – 20). AsReadOnlySpan method asynchronous functionality is another story. 20. arr. when you want to do synchronous processing. One thread starts writing a new span over that Memory<T> can wrap things other than arrays. bytesRead)). but it’s a (non-ref-like) struct and can live on to the middle of them: the heap. before it System. AsReadOnlyMemory method compiler-generated state machines.Span. . Implicit cast.) It also Memory<T> Span<T> Span property means you can’t use Span<T> as a generic ReadOnlyMemory<T> ArraySegment<T> DangerousTryGetArray method argument. marshaling methods scenarios. And as you’d expect.. as From To Mechanism they require boxing). native T[] ReadOnlyMemory<T> Ctor. static async Task<int> ChecksumReadAsync(Memory<byte> buffer. } on the stack. But String ReadOnlySpan<char> Implicit cast. Span<byte>. AsSpan method capturing them into lambdas or as locals ArraySegment<T> T[] Array property in async methods or iterators (as those Memory<T> ArraySegment<T> TryGetArray method “locals” may end up being fields on the Memory<T> ReadOnlyMemory<T> Implicit cast. not on That’s a more advanced topic beyond the scope of this article. AsReadOnlySpan method “where T : ref struct” constraint available). which means reading and writing a span is not a quick summary of built-in mechanisms for converting between an atomic operation. AsMemory method this article around arrays. Implicit cast. bytesRead). led by Memory<T>. AsReadOnlyMemory method non-ref-like structs. Span<T> as previously shown is larger than the its Span property returns a ReadOnlySpan<T>. there’s a risk of “tearing. public readonly struct Memory<T> { This second item has some interesting ramifications that result in private readonly object _object. The nature of Span<T> as a ref-like type brings with it some Memory<T> looks very much like an ArraySegment<T>: constraints due to its ref T field. in particular for compute-bound String ReadOnlyMemory<char> AsReadOnlyMemory method and synchronous processing functions. such as memory retrieved from a pool.ReadAsync(buffer). arr. like it and gets as far as writing the new _pointer value.Slice(start: 20).OwnedMemory<T>. lifetime tightly managed.AsSpan(). array slices. ref arr[20]. As such. for example.. As a result. This means asynchronous Stream read operations that complete Hundreds of new members synchronously can be entirely allocation-free. such as for an ID of some and types are being added across . commaPos)). the runtime can cache a completed Integrate with . in that you’ve avoided the heap allocation. In addition to string’s new constructor. int length = . Today you might write code like this: of Span<char>. and where it’s unlikely we can cache a completed task for all common How Do Span<T> and Memory<T> return values.. string id = new string(chars). and you want to parse out those two You could instead use stack-allocation. across ..SendAsync. you’re still forced to copy into the string the data that was gener- By using the new Span-based Parse overloads. method is frequently expected to return synchronously. it’s how Memory<T> can be used to. Instead. This approach string input = .Parse(input.').Substring(0.NET. you’ve made this ated on the stack.Slice(0. many such methods have been added across the frame- to do that. and efficient. If you’re writing Random rand = . a comma (such as “123. for example. guaranteeing accepts a byte[] and returns a Task<int>. What if you could like BigInteger and IPAddress. also takes advantage of the new string constructor that accepts a int first = int.Parse(inputSpan. and even up to higher-level types it could easily lead to a stack overflow situation...NET Libraries? Task<bool> for a result of true and one for a result of false. i < chars. you can now write this: { string input = .Length. hand out a writable span you can write to in order to fill in the CancellationToken cancellationToken = default) { . commaPos)).. such as in overloads of and types are being added Socket.Substring(commaPos + 1)). public delegate void SpanAction<T..NET. This is better. Stream.NET today is defined to accept a byte[].AsReadOnlySpan(). From System. efits. This approach also only works when the amount whole operation allocation-free. For example.. ing.. but if it’s thousands of bytes. kind.IndexOf('... there are places where Span<T> allows the frame- work to include methods that in the past raised memory safety concerns.Length. incurs two string allocations. write to the string’s memory directly instead? Span<T> allows you In fact.Random to System. DateTime. ValueTask<T> is a struct into native memory. int commaPos = input.ReadAsync in . overloads that accept a ReadOnlySpan<char> in addition to the for (int i = 0. you’re expecting a string that contains two numbers separated by } string id = new string(chars). For instance.'). i < chars. making it msdnmagazine. ReadOnlyMemory<char> can also be used that helps avoid allocations in cases where an asynchronous with strings.StringBuilder to has a Create method: System. while array. In addition.Parse(inputSpan. Some of these even carry with them additional ben.. in TArg>(Span<T> span. Random rand = . Socket. int first = int.ReadAsync that’s passing in a Memory<byte>.IndexOf('.456”). hundreds of new members containing a randomly generated value.ReceiveAsync.Net.. string now also work. Imagine a situation where chars[i] = (char)(rand.Next(0. to avoid needing to use unsafe code. performance-sensitive code. like so: int second = int.com January 2018 25 0118msdn_ToubSharp_v6_22-27. like 32 bytes. TArg arg).Parse(input. int length = . Today you might write code that requires allocating a char loads of existing array-based and string-based methods. and even take advantage numbers. Stream now has this method: This method is implemented to allocate the string and then public virtual ValueTask<int> ReadAsync( Memory<byte> destination.Next(0.. i++) too many. but it In the previous Memory<T> code snippet. but int second = int. this new ReadAsync overload returns a ValueTask<int>. that may be two string allocations for (int i = 0. WebSocket. For example..ReceiveAsync and TextReader. chars[i] = (char)(rand. however. ... SpanAction<char. TState> action). 10) + '0')...Text. TState state. 10) + '0').. Span<char> chars = stackalloc char[length]. ReadOnlySpan<char> inputSpan = input. TimeSpan and Guid. you’ll notice a call can’t cache four billion task objects for all possible result values to Stream.. That. But of a Task<int>. Similar parsing and formatting of space required is something small enough for the stack.ReadAsync. this overload not only that the span (which refers to the string’s internal storage) will accepts a Memory<byte> instead of a byte[]. ReadOnlySpan<char>. Because it’s quite common for Stream implementations to How does that work? buffer in a way that makes ReadAsync calls complete synchro- nously.Slice(commaPos + 1)).. i++) { existing overloads that take strings. just as can ReadOnlySpan<char>.indd 25 12/12/17 8:59 AM . like this: others are entirely new types focused on specific areas of process. but also returns a cease to exist before the string’s constructor completes. wrap pointers ValueTask<int> instead of a Task<int>. ValueTask<T> is also used in other new overloads. overloads have been added to make working public static string Create<TState>( with {ReadOnly}Span<T> and {ReadOnly}Memory<T> simple int length. Note that the You’ll notice that unlike the existing ReadAsync method that stack-only nature of Span<T> is beneficial in this case. Consider a situation where you want to create a string In support of Span<T> and friends.Sockets. If the methods exist for primitives like Int32 up through core types like length is short.. } int commaPos = input. all the primitive types like Int32 now have Parse var chars = new char[length]. that’s fine. Many of these are over. } contents of the string while it’s being constructed. return sum. but efficient for accessing data. but simply to compare the All this functionality isn’t just for public consumption. impossible to use the span to mutate the string after the construc. it’s likely that spans The assembly code is so similar in part because of the elimina- will be exposed out of public APIs in the lower levels of ASP. ASP. devel.NET Core have switched to using the new ReadAsync and ReadOnlySpan<T>). dword ptr [rcx+4*r9+16] ReadOnlySpan<byte> utf8Text = . dword ptr [rcx+28] tions of the stack. string id = string. These oper. Thus.Hash return sum. The JIT needs to generate code here that ensures the accesses to formance win if they don’t have to encode to and decode from data[i] don’t go outside the bounds of the array.NoInlining)] { static int Return4th(int[] data) => data[3]. which not only avoids the Unicode encoding the assembly code generated for the loop looks like the following: and decoding....Buffers. For example. new types like can tell from the structure of the loop that i will always be in range System. mov eax.Buffers.Text. To enable this. A cmp instruction is still in the loop. many { new . The JIT needs to generate code that ensures such accesses don’t go outside the bounds of the array. not only have you avoided the allocation. the span indexer as an intrinsic. as well as a throughput improvement.Utf8Formatter are being added..Text.NET Core now has a heavy cmp r8d. (Span<char> chars. TryComputeHash method on System. making spans an exception to be thrown). standardFormat = 'P')) jg SHORT G_M33811_IG03 throw new InvalidDataException().Security.NET Runtime? tion is complete: One of the ways the .Next(0. Parsing that had been following code. System.Text. such as in its middleware pipeline. Random r) => of the array. i < data. } Algorithm to achieve a monstrous savings on allocation (a byte array per iteration of the algorithm.. the JIT can optimize away the bounds checks on the array.Create(length. Call The runtime applies similar optimizations to span (both Span<T> sites across . it con. { consider this method: for (int i = 0. add rsp.Buffers.. rand.Base64.NET tion of bounds checks. and the subsequent jbe instruction is then jumping to the range check failure routine if 3 is out of range (for it does for arrays.Utf8Parser and (the loop iterates through each element from beginning to end). For example. in on the action. you’re writing sub rsp. for (int i = 0. What About the .TryParse(utf8Text. 40 ret G_M22714_IG04: The runtime can apply for spans call CORINFO_HELP_RNGCHKFAIL int3 That cmp instruction is comparing the length of the data array the same kinds of optimizations against the index 3. i++) sum += data[i].Length.. chars. chars[i] = (char)(r. But also relevant is the JIT’s recognition of Core.Length. r8d This doesn’t stop at the level of the core .Cryptography.NET libraries. 3 jbe SHORT G_M22714_IG04 also avoiding the copy and you’re not constrained by size limita. movsxd r9. Compare the previous example to the overloads to avoid unnecessary allocations. that indexing into an array doesn’t allow going beyond the length Random rand = . Consider this Sum method: static int Sum(int[] data) Beyond core framework types gaining new members.NET runtime provides safety is by ensuring int length = . inc edx if (!Utf8Parser. but because the JIT strings when working in UTF-8. where the only change is on the parameter type: done by allocating substrings now takes advantage of allocation-free static int Sum(Span<int> data) parsing. for example. cmp r8d. meaning that the JIT generates 26 msdn magazine . the gener- }). dword ptr [rax+4*r9] inc r8d tinues all the way up the stack.. Even niche types like Rfc2898DeriveBytes have gotten { int sum = 0. which might iterate thousands The generated assembly for this code is almost identical: G_M33812_IG03: of times). no additional bounds checking. 10) + '0'). and Memory<T>-based methods for better performance. rather value of i (as stored in the edx register) against the length of the array the framework itself is able to utilize these new Span<T>-based (as stored in the r8d register). that doesn’t mean that every individual array access needs a bound check. 40 directly into the string’s memory on the heap. which means you’re cmp dword ptr [rcx+8]. but enables them to work with native buffers that G_M33811_IG03: movsxd r9.Length. i < data. ated assembly for this method looks like the following: Now.NET types are being developed to work with spans for int sum = 0. edx are common in the very lowest levels of various networking stacks: add eax. opers looking to write high-performance microservices and } Web sites heavy in text processing can earn a significant per.indd 26 12/12/17 8:59 AM . System. edx dependency on spans. edx out int bytesConsumed. taking advantage of the new Span<byte>-based for (int i = 0. } On the x64 machine on which I’m typing this article. a practice known as bounds checking. with the Kestrel server’s HTTP jl SHORT G_M33812_IG03 parser written on top of them.. In the future.NET 0118msdn_ToubSharp_v6_22-27. out Guid value. efficient processing in specific scenarios. i++) [MethodImpl(MethodImplOptions. ate on spans of bytes. i++) sum += data[i]. add ecx. . Let’s look at { three such features. albeit without some of the optimizations imple- public ref struct Enumerator mented when built into to the platform. As noted earlier. Karel Zikmund msdnmagazine. instead of writing: github.ly/2zywvyI. to This is also extremely useful in situations where you need some working with you on GitHub to improve .. but want to avoid allo cating heap memory for relatively small sizes. Debug. • Write two completely different code paths. which The types. bool formatted = guid. Ahson Khan. // Code that operates on the Span<byte> able in the blog post at bit. // Uh oh Several features have been } Here space is being allocated from the stack and then trying to return a reference to that space.. Bill Wagner. Vladimir Sadov. Jan Vorlicek. with safe code and with minimal ceremony: an efficient mechanism for accessing data.NET Core 2. In previous versions of changes between the current preview version and what’s actually C#. That will make Span<T>. you tell the C# compiler to allow you to that. } Of course. . n scratch space to perform an operation. the same thing can be accomplished without code dupli- the same kinds of optimizations it does for arrays.NET. Span<char> chars = stackalloc char[100]. For example. allocating and oper- ating over stack-based memory and over heap-based memory. Jan Kotas. and other elements dis- is exposed in C# as of version 7.indd 27 12/12/17 8:59 AM .com/stephentoub. Thus.com January 2018 27 0118msdn_ToubSharp_v6_22-27. is available for you to try out today—simply add a reference to the private int _index.com/dotnet/corefx repositories for Span<byte> bytes. After keyword before struct.. tion in unsafe code. the functionality available for existing releases of . to do the following: Several features of C# 7. but the moment you return. Jared Parsons. providing feedback. the success of this feature set relies on developers { byte* tmp = stackalloc byte[length]. that Enumerator would need to store the Span<T> and. length). keep in mind that there can and will be breaking Stackalloc initialization of spans.NET Framework. and that can be done without the feature set. By putting the ref cussed here are on track to being included in .NET Standard 1. Thankfully the C# compiler detects such invalid usage with ref structs and fails the compila- compiler to help make Span<T> tion with an error: a first-class citizen in . Such changes will in large part be local variable. out int charsWritten.Memory.2 compiler will be required to use Span<T>). All of this is to illustrate that the runtime can apply for spans Now. System. would itself need to be a ref struct.Slice(0. also sign up for the associated constraints to be assigned to your are also on track to being made available in a System. it can be dangerous What About the C# Language and Compiler? to pass spans around in a way that might enable referring to mem- I’ve already alluded to features added to the C# language and ory that’s no longer valid.com/dotnet/coreclr and github.NET further. and keep an eye on the using the unsafe keyword.Memory. More details are avail. and building their own libraries bytes = new Span<byte>(tmp. rather than translating its actual IL stack-based memory and written with pointer manipula- code into assembly. making spans cation. Marek and then delegate to an implementation also used for the Safar. to hearing from you about your experiences. and in doing so core types like Span<T>. utilizing these types. As of C# 7. Because spans can refer to data that might be associated with a given stack frame.2. like this: and . . We look forward You can write simply: Span<byte> bytes = stackalloc byte[length].2 as ref struct. Previously you had S tephen T oub works on . Span<byte> bytes = length <= 128 ? stackalloc byte[length] : new byte[length].dll type.1. runtime optimizations.NET. Thanks to the following technical experts for reviewing this article: • Pin the memory associated with the managed allocation Krzysztof Cwalina. and even better.1. Span<T> is a ref-like type. charsWritten). You can find him on GitHub at two choices: github. if you wanted to write a struct Enumerator for a package that’s compatible with . So please do give it a try. Joseph Tremoulet. unsafe Ultimately. as well as the new types like Utf8Parser. Span usage validation.2 are related to spans (and in fact the static Span<char> FormatGuid(Guid guid) C# 7. special code for the indexer. "d"). the result of stackalloc could only be stored into a pointer delivered in a stable release.NET Core.NET Framework thus.NET programs. methods. return chars. ongoing work.TryFormat(chars.Assert(formatted). that added to the C# language and space will no longer be valid for use. imagine a method that tried compiler to help make Span<T> a first-class citizen in . The use other ref struct types like Span<T> as fields.NET at Microsoft. For example. error CS8352: Cannot use local 'chars' in this context because it may expose referenced variables outside of their declaration scope What’s Next? Ref structs. all with the goal of providing efficient and safe } access to memory in modern . Eric Erhardt. You can also find documentation at aka.ms/ref72. stackalloc can now be used as part of due to feedback from developers like you as you experiment with an expression and can target a span. trying it out.dll package from NuGet. A preview of this package { private readonly Span<char> _span. I expect them to make their way into the . 2018 Hyatt Regency Austin Austin Code Like It’s 2018! June 10 – 14. SUPPORTED BY PRODUCED BY magazine Untitled-7 2 10/11/17 1:47 PM . the Microsoft Platform and open source technologies in seven great cities across the US. independent developer conferences. and we want you to be a part of it.NET. as we highlight how far technology has come in 25 years. Las Vegas Code the Future. March 12 – 16. 2018 Hyatt Regency Cambridge Boston Developing Perspective. 2018 Bally’s Hotel & Casino Respect the Past. Join us in 2018 for #VSLive25. April 30 – May 4. VISUAL STUDIO LIVE! (VSLive!™ ) is celebrating 25 years as one of the most respected. while looking toward the future with our unique brand of training on . longest-standing. CONNECT WITH US vslive. 2018 DATES ANNOUNCED August 13 – 17. 2018 Loews Royal Pacific Resort Orlando Code Odyssey. NEW LOCATION! October 8 – 11.com twitter.com – linkedin.com/vslive – facebook. 2018 Hilton San Diego Resort Code Again for San Diego the First Time! December 2 – 7. 2018 Microsoft Headquarters Yesterday’s Knowledge. Redmond Tomorrow’s Code! September 17 – 20. 2018 Renaissance Chicago Look Back to Chicago Code Forward.com – Join the @VSLive Search “VSLive” “Visual Studio Live” group! #VSLIVE25 Untitled-7 3 10/11/17 1:48 PM . And one of the handy tools you’re an AI developer or data scientist looking to build intelligent for code breaking is to recognize primes quickly. from my handy little Before you start building. check out the love to have an ISPRIME function for the millions of detectives who “Azure Machine Learning Functions” section later in this article. the add-ins don’t need any code changes to run on all the different platforms. and they interact with them naturally for their function depends on your skills and goals. And underneath all the fancy ask yourself this: “Does my function need to change anything aside features. does calculation. the real value is from the Excel value that’s being returned?” In other words. consider building an Excel or building for people in your own organization. though you can control all those behaviors as part of a solution to more complex calculations like the T. tions for you in the future! Some of the technologies discussed in this article are in preview. already use Excel. This article discusses: Thousands of add-ins are already available and they all run across • Excel add-ins Excel platforms. so Contoso would models for data analysts to use at your company. as soon as you make a change. To decide if yours should. What Can I Build? powerful. a number to be changed in a financial database on the Internet. which might contain functions and other capabilities.ly/2AUOsZk). Azure Machine Learning Web servers.ly/1Tjynwl). And then. Microsoft will have solu- this function and the other capabilities it needs for its add-in. JavaScript Custom Functions in Excel Add-Ins all information is subject to change. somewhere on the sheet or a new row to be added underneath or from the essential AVERAGE function (bit. called “Calc” internally. either selling externally like Contoso Cryptographers capability that Excel doesn’t already have. So if you want to provide a powerful developer. people don’t expect for- relationships between cells: You express complex models by writ. Excel add-ins are tools that professional developers can build to extend Excel and interact with the data in workbooks (bit. Calc the result of self-contained formulas without side effects. Later in this article you’ll see how Contoso builds And if you don’t have any of those skills. behind the slick charts and formatting. (bit.indd 30 12/12/17 9:01 AM . you type “=SUM()” in cell A1.” If analyze data in Excel to decode messages. JavaScript.ly/2jhcEuV). an add-in is the function for that purpose. Excel Online and even • JavaScript custom functions in Excel iOS. When updates the dependent values based on those formulas.TEST statistical function you build. and have the ability to call external Excel. Best of all. Anyone familiar with Web technologies will find add-ins easy • Azure Machine Learning functions in Excel to build. OFFICE Extend Excel Formulas for Data Analysis Michael Saunders Take a second to think about Excel as a whole—it’s a flexible. If you’re a professional day-to-day calculation needs. People at work and in school learn Excel functions The type of solution you should build to create your Excel to use in formulas. ing simple formulas to describe the dependency trees between That change might trigger other changes. all the way to massive 100MB financial-model functionality should use Excel formulas. ubiquitous tool for analyzing data. as is explained in Cryptographers Corp. because they’re written just like Web pages: Add-ins run Technologies discussed: HTML. Mac. workbooks at the world’s top banks. to string-anal. wants to release a solution that helps sleuths the “JavaScript Custom Functions in Excel Add-Ins section. including Windows. (Excel also supports other types 30 msdn magazine 0118msdn_SaundersExcel_v3_30-33.ly/2ipowKE). ysis functions like SEARCH for finding substrings (bit. you don’t expect a chart to appear Excel provides tons of helpful functions to use in your formulas. and CSS. Calc is what lets you create the function have side effects? In Excel. consider that not all extensions to Excel to-do list spreadsheet. mulas to change anything except the cell in which they’re entered. JavaScript. See Figure 2 for an example: The Contoso right tool for data analytics solutions in Excel. but those would also be values (see Figure 1). which specifies different situations. and HTML task values are pseudorandom. In this case. Contoso of JavaScript custom functions. Then. To be an effective extension point. But if necessary. divisor++){ The key difference between this function and ISPRIME is that if(n % divisor == 0) return false. but deployed by the developer. } if (n < 2) return false. like ribbon buttons. Look at Figure One common aspect of all asynchronous functions is that they 4 for an example with the Contoso Crypographers ISPRIME func. in around PRIME is selected. Bringing Web data into Excel write than just the function itself. but you can see the documentation for more info. the function can make many case. For JavaScript custom Both of these pieces of information and much more are provided functions. as described at bit. calls and take longer than that to evaluate. for (var divisor = 2. max.sqrt(n). } return true.xml file. then makes an XML } HttpRequest (not visible in the function—it’s in the sendRandom The function simply checks all possible divisors up to the square OrgHTTP method) to the random.org are safe such as the abilities to add and remove to use for this purpose—they’re rows. is one of the key reasons companies want to extend Excel func- custom functions must look and feel just like native ones. divisor <= root.org number to write it to the cell. But sometimes you might want key pieces of an add-in. In Contoso’s case. In contrast. random. generated by random. else setError(result. setError){ ISPRIME function to see how it’s written (It’s also possible to check sendRandomOrgHTTP(min.ly/2qsPfLe. but that’s much more if(result. Thankfully. instead. Excel has an excellent RAND func- tion at bit.error). so Excel shows a tion: In addition to the name of the function itself. tion to be resolved (see Figure 6). Let’s take a closer look at the Contoso Cryptographers function getRandom(min. isn’t ideal for encryption because its tual menu options. Excel shows the name of the parameter (in this a tenth of a second.xml file. All the actual logic is done already. The rest of the code is plicity of their ISPRIME function. even apply formatting to cells. but the problem is that RAND elements.xml Your Own Web App Office Add-In (with Office. max) { return new OfficeExtension. it immediately returns a JavaScript promise. Contoso resolves the promise with the ran- JavaScript. They can add UI tion.number) setResult(number). the cryptogra- but they can’t run across platforms or be phy functions are defined and well-known deployed to the Store. And Of course. function(result){ primality using only built-in Excel functions. and generated from atmospheric noise. flexibility. If you’re familiar with the add-in model.) Figure 3 shows the beforehand. They can interact procedurally. the HTTP request can complete quickly.com January 2018 31 0118msdn_SaundersExcel_v3_30-33. take some amount of time to return their result.js) this information is provided in JavaScript rather than hardcoded statically somewhere. custom functions make it tion to Excel using an add-in (bit. it’s Prime Numbers must design a function that can call possible to extend Excel formulas.org to fetch random num- Custom functions allow developers to add any JavaScript func. The main piece the ability to enable different functions in is the manifest. it’s no good to hardcode now. once the Web root to determine whether the input is prime—a few lines of service has responded. I won’t discuss all the metadata HTML here.org service.indd 31 12/12/17 9:01 AM . of add-ins.Promise(function(setResult. you might be wondering why manifest. Excel displays a #GETTING_DATA message in the cell while it waits for the func- helpful description to clarify the purpose of the function. just as with any their next goal is a little more difficult: other Web application. generated panes and dialogs. so Microsoft expects asynchronous functions to be popular. numbers with workbooks via thousands of APIs. var root = Math. difficult for the person requesting the calculation. functions have a bunch of customized information. insert and edit charts. resolving the value in JavaScript causes it to be displayed by the developer in the JavaScript definition of the function’s meta- data. After CONTOSO. You can see another example in Figure 5. function isPrime(n) { }). the Web location of the rest of the add-in Contoso Cryptographers love the sim- and other metadata. with the new preview release Figure 2 The Contoso Function to Identify random numbers. to extend Excel (see the documenta. But there’s more to dom.bers via HTTP request. Users can then access easy to include Web requests. RANDOM is asynchronous: instead of returning a value to Excel. n) to make it easier to pick the right inputs.): }). like in the manifest.ly/2AYtNUW).IS.ly/2AV47rw). And native tions. Figure 1 Calc Lets You Create Relationships They want to build a function to generate Add-ins provide lots of useful ways Between Cells random numbers for encrypting text. The reason is Figure 3 The Key Pieces of an Add-In msdnmagazine. contex. as you can see in Figure 5. Here’s what Contoso’s asynchronous custom functions like any other native function in Excel (such as RANDOM function looks like: AVERAGE). You can see that the description is specified as a string and so is the name of each parameter. Whatever they decide. The in Figure 8). just like for any other Excel function.number. options: { batched: false. the creators can enable it for anyone they choose. I’ll explore the other new way to extend Excel formulas. The analyst which users get access via the O365 admin center (see the interface has some data on that product and the target markets in Excel. depending on the audience. Perhaps the JavaScript API could even be used to let customers encrypt an entire worksheet of data with a click of a button. settings for how they behave.scalar. The public or predicts values based on a machine learning (ML) model. deploys directly to its small business customers returns the result asynchronously. so they don’t have to click anything to install it.CustomFunctionValueType. Azure ML functions are created by AI developers (often data scientists and other experts) for analysts in their organization to use. type in a cell. }]. description: "Determines whether the input is prime". Figure 9 shows a sam- Cryptographers to try writing your own custom functions (use ple spreadsheet with this type of data. Figure 4 Custom Functions and Native Functions Automatically Complete While You Type Figure 6 Waiting for an Asynchronous Function to Return immediately in the cell. an add-in using custom functions could have many other features.ly/2A70L5o) is available to anyone who has Excel— the model is built. Contoso Cryp. There are two main ways to deploy an add-in containing these The Azure ML function itself is based on a service that calculates JavaScript custom functions. as well: Contoso Cryptographers might want to create a task pane and a ribbon tab to give their customers easy access to their custom functions. and requires submis. there’s even a button to browse the Store on the Excel ribbon.indd 32 12/12/17 9:01 AM . streaming: false } }. Then an IT admin can choose dict demand for new products in various geographies. In contrast to JavaScript custom functions. As a result.ms/customfunctions). the guide and samples at aka. parameters: [{ name: "n". a marketing analyst at a retailer might want to pre- each customer with the manifest file. Figure 8 Deploying a Custom Function to an Organization 32 msdn magazine Office 0118msdn_SaundersExcel_v3_30-33. description: "the number to be evaluated". they can be Figure 7 An Excel View of the RANDOM Function After confident that the entire add-in will run across Excel platforms the Value Is Returned without code changes. valueType: Excel. Next. goal is to get a simple function that lets the analyst forecast demand Hopefully you’ve been inspired by the resourceful Contoso in each market without ever leaving Excel. result: { resultType: Excel. Instead. resultDimensionality: Excel.com/help.CustomFunctionValueType. The Then. valueDimensionality: Excel. Azure Machine Learning Functions The second type of extensible function Microsoft has announced is Azure Machine Learning functions (abbreviated Azure ML). Those users get the add-in installed automatically. calls a live Web service on the company’s Azure subscription and tographers Corp.scalar. they simply Store supports both free and paid add-ins. helpUrl: "https://example. every time someone wants to run the function.boolean.CustomFunctionDimensionality. it provides For example.CustomFunctions["CONTOSO"]["ISPRIME"] = { call: isPrime.CustomFunctionDimensionality. The function sion and validation through Microsoft. Figure 5 The Contoso ISPRIME Function Excel. }.Script.html". there’s no need to create an add-in package to deploy an Azure ML function. Once Office Store (bit. However. Figure 7 shows an Excel view of the same RANDOM function after the value is returned. and guidance on how to use them. Of course. com/vegas 0118msdn_VSLive_Insert. Register by January 19 and Save $400!* Use promo code VSLTIPIN *Available on 3. PROGRAMMERS AND ARCHITECTS: ➤ Visual Studio ➤ ASP. VSLive! 1998 VSLive! 2017 vslive. NV INTENSE TRAINING FOR DEVELOPERS. March 11. and 6 day packages only. LAS VEGAS.indd 1 12/6/17 10:56 AM .NET / Web Server ➤ . 5.NET Core ➤ Database and Analytics ➤ Xamarin ➤ ALM / DevOps ➤ Software Practices ➤ Cloud Computing ➤ Angular JS ➤ UWP/Windows RESPECT THE PAST. ENGINEERS. LAS VEGAS MAR 11-16 2018 BALLY’S. CODE THE FUTURE! ➤ BACK BY POPULAR DEMAND: Hands-On Labs! Sunday. Starting at $645 thru January 19. 2018 September 17 – 20. 2018 April 30 – May 4. Code Odyssey. Tomorrow’s Code! CONNECT WITH US twitter. Look Back to Code Like It’s 2018! Code the Future.com/vegas magazine 0118msdn_VSLive_Insert. June 10 – 14.indd 2 12/6/17 10:56 AM . the First Time! August 13 – 17.com – linkedin.com/vslive – facebook.com – Join the @VSLive Search “VSLive” “Visual Studio Live” group! EVENT PARTNER SUPPORTED BY PRODUCED BY vslive. Code Forward. 2018 Help Us Celebrate #VSLive25! Which Location Will You Attend? March 11 – 16. 2018 Bally’s Hotel & Casino Hyatt Regency Austin Renaissance Chicago Las Vegas Austin Chicago Respect the Past. 2018 October 7 – 11. 2018 Microsoft Headquarters Loews Royal Pacific Resort Redmond Orlando Yesterday’s Knowledge. 2018 Hyatt Regency Cambridge Boston Hilton San Diego Resort San Diego Developing Code Again for Perspective. 2018 December 2 – 7. typically from an external database. There are many more improvements coming to both of these function types. All that’s required for the service to appear as a function in Excel is that the analyst in Excel has permission to access it. Figure 10 is the Run Dashboard view in Azure ML (bit. it can be deployed as a Web service in the Learning Workbench is a tool that simplifies the data preparation organization’s Azure subscription. so stay posted Figure 10 Azure Machine Learning Workbench for future announcements! n Michael Saunders is a program manager on the Office team.ly/2jRJQsu).com January 2018 33 0118msdn_SaundersExcel_v3_30-33. Thanks to the following Microsoft technical experts for reviewing this article: Yina Arenas. In his spare time. the cell shows a #GETTING_DATA message while the service computes the result. with permissions for the right set of users to access it. and he studied Manage- ment and Materials Science Engineering at the University of Pennsylvania and Whar- ton. The Future of Extensible Functions in Excel I hope you’ll try the technology previews for extensible functions in Excel—JavaScript custom func- tions and add-ins if you’re a software or services vendor.ly/2nwa0WP) to create the model: She starts by preparing training data. An AI developer at that organization uses Azure ML servicesand lets the data scientist write Python code to train and evalu- ate models. Ashvini Sharma. Just as with the asynchronous JavaScript custom functions. Instead of defin- ing the metadata in JavaScript that runs locally. and some entirely new ones. you’ll also have the oppor- tunity to shape the final released product. so in addition to getting a head start. He’s originally from Toronto. and Azure ML functions if you’re an AI developer or data scientist. the metadata is defined in a Swagger (RESTful API) format that’s created automatically along with the deployed service.indd 33 12/12/17 9:01 AM . Canada. The analysts can then run the function normally. Saunders sings with the Seattle Esoterics and develops add-ins. to build an ML experi- Workbench. Microsoft is lis- tening carefully to all the feedback during the preview (post ideas to the UserVoice page at bit. Azure Machine Once the model is ready. ment based on historical sales for new products. Figure 11 shows the deployed Figure 9 Sample Product and Market Data That Will Be Analyzed with an Azure ML Function functions appearing for the data analysts in Excel. where he builds Excel features for developers. showing statistics on an experiment. Figure 11 The Deployed Functions Showing in Excel Sandhya Vankamamidi msdnmagazine. Cognitive Services Speech API cross-product integration. More organization. authentication requirements and style • Building processes and integrations in Microsoft Graph using of interaction. such as OneDrive and Mail (Outlook. Even five years ago.runCampaign()” is sets within your organization and allows you to pull together perhaps wildly overly simplistic. Microsoft Graph works with consumer services. including where can bring together and connect.com). Azure Functions. the process of getting a user’s complete profile and photo would require callouts 34 msdn magazine 0118msdn_AmmerlaanGraph_v3_34-41.indd 34 12/12/17 8:50 AM . as well. the more useful by far the net set people work and the tools they use to get work done. what would it is functioning and could transform productivity by building more look like? efficient processes and tools. Frequently. All information is subject to change. individual APIs from different product teams— at Microsoft. You’d layer on resources. Solving the Problem of API Sprawl This article discusses: Across an organization. and inter tion—and the kinds of roles and functions they fulfill. we offer Microsoft Graph—an API that spans key data in the API? Though “widgetMarketingTeam. which is personal productivity. Technologies discussed: Historically. You’d then of products you build could be—greater than the sum of its parts. Such people connected logically. You’d probably start with the people—the heart of an organiza The key is making every resource available consistently. typically organizational systems with a distinct set of APIs. in my case—would work differently and require Microsoft Graph. the set of software systems in use can vary • Using Microsoft Graph to unify data and authentication across wildly. empowering you to transform This article discusses Azure Functions Binding Extensions. add processes and work activities—perhaps these are methods For this. OFFICE Build the API to Your Organization with Microsoft Graph and Azure Functions Mike Ammerlaan If you think of your organization as an API. in public preview. you’d get great insights into how your organization over. nevertheless. each presents a unique structure. with an API to your everything you need to transform how work is performed. Azure Functions Bindings Extensions for Microsoft Graph. For developers. The more APIs you plish tasks and projects. a major challenge of software projects Azure Functions is simply bridging these different systems to provide a higher level • Creating a task using Azure Functions of insight and can include abstracting out different APIs and mas • Processing files in OneDrive tering individual authentication schemes. so you can craft comprehensive processes to are frequently grouped into defined and virtual teams that accom fit the way individuals and teams want to work. you can enter two simple URLs to see the kind of with items in Microsoft Graph gives you the ability to deeply cus calls you’ll be making in this sample. In this case. and more. A natural choice for building processes and integrations in Microsoft Graph is Azure Functions (functions. Alternatively. representing key facets and functions in a com undertaken by a member of their team. various tools of work are sign in with your organization account and directly access your represented for users and groups.com). calendar. as shown in Figure 1. possible to pull together. and fully conceive of all you might do. new capabilities have been added across the APIs in iment with your development. shown in Figure 2 . operation for creating a Planner Task (a POST to https://graph. a the “GET my manager” sample. Graph Explorer is an application Web site that ized groups are an emerging concept in Microsoft Graph.0/planner/tasks). Microsoft Graph is designed to be straightforward to work with. A new ability to persist custom metadata along In this case. These operations were all mechanics of webhooks. to where action. Let’s take a look at an example to get started in working with Microsoft Graph was born out of a desire to solve this problem. you can expand the set of samples to add connect your systems into Microsoft Graph by adding identifiers samples of Planner tasks. explore their starting with a list of users and other security groups. are made available as methods.js. From there. and making systems consis tent. including files via the Drive API. you could Within Graph Explorer. find The second part of the operation is to create a Planner Task. Outlook & Groups work. crosoft.microsoft. Microsoft Graph. Content and Notes Excel Models Sites and Lists array of SDKs. We recommend using a developer tenancy. User tasks are one way pany.azure. now available in preview with the Azure Functions 2.com/devprogram. own data. a Planner task board. to both Exchange APIs (to get information about a person) and Recently. What if you then wanted to get the information runtime. Since its launch two years ago. the net set of APIs becomes much easier and more practical Creating Tasks via Azure Functions to use. the Graph Explorer lets you either use a based workspace. You behind this is shown in the Run Query field. Microsoft Graph has continued to ask users to perform an action—to convert and track human to grow in breadth of both functionality and capability. update and delete (CRUD) APIs for core objects. automates some of the common tasks of working with about a person’s manager? That would involve querying a third Microsoft Graph. Simplified. central Graph Explorer.mi Microsoft Graph also goes beyond providing create. including authentication and working with the system to get organizational hierarchy. Through an analysis of Azure AD Azure AD Teams. As a simple REST API and coupled with a wide Files. like a Microsoft Teams chat.com January 2018 35 0118msdn_AmmerlaanGraph_v3_34-41. you want to check “get a tomize these items. Microsoft Graph pulls together diverse systems from across Imagine you’d like to have managers review and approve an action your organization. I want to implement a simple Web service that it really can serve as a foundational API for your organization. instructor and timing. Figure 1 Productivity APIs of Microsoft Graph msdnmagazine. which lets you add pinpointed blocks of code where you need it while Office Apps & OneDrive Excel SharePoint only paying incrementally for code as it’s used. though Graph contains a full organizational hierarchy and collection of groups. Within this sample set. these may not always form the best representation of how teams work. or sign into your own tenancy. API scheme. could use this metadata to then perform queries—for example. will give you a separate tenancy where you can feel free to exper Over time. incoming mail for both users and groups. available tasks via the Planner API.0 requirements. Microsoft Graph. The URL group could represent a class in an educational institution. generally lets you quickly model Microsoft Graph calls. read. For example.office. Groups can results. First. and differing Extensions.com/v1. a new set of integrations with Azure Functions makes SharePoint APIs (to get a photo from a user’s managed profile). it easier to connect to Microsoft Graph. In addition. Now a group is no longer just a group—with user’s manager.indd 35 12/12/17 8:50 AM . A major feature is a layer of insights that are generated behind the scenes as users People and Groups Organization Conversations work. but more complex than they needed to be. and a SharePoint site with read-only demo tenancy. you can get a list of the most closely related people (virtual teams) and files with which a user might be connected. Azure Functions supports development across languages.” which you can see in Graph Explorer by selecting additional metadata describing topic. Tasks Calendars Contacts Insights common utilities. Azure Functions Planner & To-Dos Outlook Outlook Microsoft Graph exists to be used and customized in broader sys tems and processes. At the core of Microsoft Graph is the set of users—typically all The first stop in any Microsoft Graph project is usually the employees with an account in an organization. Azure Functions Binding Each had their own authentication. such as those for finding an available meeting time among a set of users. all groups that represent science classes. you can see the from your system to the related entities within Microsoft Graph. Available from have an associated set of resources. You can document libraries and files.com/graph. will create a task assigned to a user’s manager. including C# and Node. developer. By unifying data and authentication. This contacts. from the Office Developer Program at dev. Untitled-4 2 9/7/17 1:32 PM . Untitled-4 3 9/7/17 1:32 PM . }.microsoft. because the new Azure Functions but at least you can see how you’d create the starter set of tasks that Binding Extensions capability is in Preview. function. { Functions.com". your function will typically incur cost only as it’s called.WAV "name": "accessToken". Under the Integrate tab of your { function. This sample shows how you can pull together disparate sets of data Figure 2 Results of Selecting GET my manager (a user’s manager and Planner tasks in this case) in one piece of code Now that you understand the Web service requests involved. Now. As before. In gen tasks on the fly and leverage existing Planner experiences is quite eral.ReadWrite) voice recognition. Note that you’ll need to configure an environment variable for the function applica tion called PlanId. With this function in place. Under mission.ReadBasic. This is an example of data processing that can be a •V iew users’ basic profile (profile) useful way to get more value out of files across OneDrive and SharePoint. This can be done via Application Settings for the function application.All) To get started.ReadWrite.All) per APIs. You’ll also need to have a Cognitive Services Speech API Integrate. Because this is implemented with Azure }. they can specify a filename parameter. You’ll also need to install the Microsoft Graph Extension. it’s time for the code. extension ties the myOneDriveFile parameter in your Azure func "type": "httpTrigger". This will require that the user sign in. you’ll create a standard HTTP C# trigger. including: a file for use. you follow some of the same steps as in the pre •R ead all users’ basic profile (User.indd 38 12/12/17 8:50 AM . the binding "name": "req". viding a flexible way to extend the data you have in Microsoft Graph. pro "name": "$return". start with Azure Functions Binding Extensions and Figure 3 Creating an HTTP Trigger to Handle Authentication set up a new HTTP C# trigger. after a user has signed into their Azure "direction": "in". It’s not quite “widgetMarketingTeam. use the binding markup shown in Figure 5 to connect "bindings": [ { your function to a binding extension. filename and contains English content within it. this will get tran "identity": "userFromRequest" scribed into English text. In this case.0 preview (“beta”) runtime. Note that the Azure Active Directory Microsoft Graph to handle the authentication and ensure you have an application registration that you use for this sample will need to authenticated access token by which you can access Microsoft Graph have the “Read all files that user can access” (Files. If a file has a . You then pass it into Cognitive Services APIs for doing •C RUD user tasks and projects (Tasks. "resource": "https://graph. which is shown in Figure 6.All) vious example.ms/azfnmsgraph to useful. common way to drive activities across teams. so the ability to create To get started. including setting up a Function App and an Azure You’ll want to leverage Azure Functions Binding Extensions for Active Directory registration. "direction": "in" tion to the onedrive binding extension. "direction": "out" } ].Read. you’ll want to follow the instructions at aka. create a new Azure Functions application. In this instance. which you can obtain from aka. authenticate and approve your application before it can be used. in Figure 3. select the Advanced Editor and use the bindings shown key. Creating and assigning tasks is a you can build a function using Azure Functions. you take advantage of Azure Functions for this sample you’ll need to add some further permissions to sup Binding Extensions for Microsoft Graph to do the work of preparing port reading manager information and tasks. { "type": "token".ms/tryspeechapi. "type": "http". your Azure Functions application over to the 2. Processing Files in OneDrive as well as configure App Service Authentication. The code for the function is shown in Figure 4.launchCampaign()”— get this accomplished. Another task you can perform is to process files that exist on a user’s As you configure the Microsoft Graph Application Registration. OneDrive. which has the identifier of the Planner Plan you wish to use for your tasks. you’ll need to switch would get the team off to a focused. with one authentication token. •R ead and Write All Groups (Group. In brief. To do this. Azure Functions + Microsoft Graph "disabled": false The two samples I presented here show how you can build both } human and technical processes on top of data within Microsoft 38 msdn magazine Office 0118msdn_AmmerlaanGraph_v3_34-41. structured start. Untitled-9 1 12/8/17 2:43 PM . ReadToEnd().0/planner/plans/" + planId + WebResponse response = null.Info("Error: " + e.graph.CreateHttp(url). log. accessToken. due). "Bearer " + token). using System.UtcNow.ToLower(). string taskBucket = values["taskBucket"].AddDays(5).ToString( hwr. { } var existingBucketTitle = bucket.Mail.GetResponse().ParseQueryString(req.com/v1. string bucketId = "".type\": \"#microsoft.ToString(). log). // the task to a bucket.RequestUri. public static HttpResponseMessage Run(HttpRequestMessage req. \"title\": \"{1}\".microsoft. log).Linq.Text. // find the bucket ID to add it to if (!String. TraceWriter log) appliedCategories = "{ \"category2\": true }". } string managerId = manager.Add("Authorization".ContentType = "application/json".IO. string token. using (StreamReader sr = new StreamReader(stream)) { foreach (var bucket in existingBuckets.UTF8."). bucketId.GetEnvironmentVariable("PlanId"). \"startDateTime\": \"{2}\".Info("Creating new task: " + jsonOutput).GetResponseStream()) string planId = System. string jsonOutput. using (Stream stream = response. \"assignments\": using System. accessToken.ToString("yyyy-MM-ddTHH\\:mm\\:ss. } catch (Exception e) string appliedCategories = "{}". log.Write(postData.Tasks.Length)."). hwr.0/planner/tasks".ToString()).IsNullOrEmpty(taskTitle)) WebResponse response = null. { } response = hwr. \"appliedCategories\": {3}. dynamic existingBuckets = JObject.com/v1.com/v1. var values = HttpUtility. { log. managerId.no title.indd 40 12/12/17 8:50 AM .ContentType = "application/json". \"dueDateTime\": \"{6}\". if (taskPriority == "alert" || taskPriority == "1") } { appliedCategories = "{ \"category1\": true }".Headers. "/buckets".ToString() + "\"".Format(" {{ \"planId\": \"{0}\".Configuration. string due = DateTime. using System.OK).IsNullOrEmpty(taskBucket)) using (var stream = hwr. "Bearer " + token).microsoft.BadRequest).Web. PostJson("https://graph. {{ \"{4}\": {{ \"@odata. accessToken.Info("Incomplete request received . // If the incoming request wants to place a task in a bucket. try return new HttpResponseMessage(HttpStatusCode.id. try if (!String. string token. hwr. { log. 0.Message). log.Info("Error: " + e.UtcNow.Json" } using System. \"orderHint\": \" !\". } // Retrieve data from query string private static string GetJson(string url.IndexOf(existingBucketTitle) >= 0) catch (Exception e) { { bucketId = ". string taskTitle = values["taskTitle"].ReadToEnd().Info("Getting Json from endpoint '" + url + "'").Message). using System.Net. } dynamic manager = JObject. \"bucketId\": \"" + bucket. postData. using System. planId.Add("Authorization".microsoft.Method = "POST". { } HttpWebRequest hwr = (HttpWebRequest)WebRequest.id. appliedCategories.fffffffzzz").GetBytes(body.plannerAssignment\".Threading.GetRequestStream()) { { // Retrieve a list of planner buckets so that you can match stream. using Newtonsoft. var postData = Encoding. { using (StreamReader sr = new StreamReader(stream)) // Retrieve the incoming users' managers ID { string managerJson = GetJson( return sr. string taskPriority = values["taskPriority"]. log. } } else { private static string PostJson(string url. } } if (taskBucket.GetResponseStream()) { taskBucket = taskBucket.Json. using (Stream stream = response.Query). now. accessToken. Figure 4 Posting a Task Assigned to a User’s Manager Azure Functions Source #r "Newtonsoft. "https://graph. if (String. hwr. log).Net. string jsonOutput = String. taskTitle.Info("Posting to endpoint " + url).name. log.Headers. hwr.Parse(bucketsJson). \"orderHint\": \" !\" }} }}{5} }}". TraceWriter log) // Expected format is taskTitle=task text&taskBucket=bucket { // title&taskPriority=alert HttpWebRequest hwr = (HttpWebRequest)WebRequest. return null.ToLower(). "yyyy-MM-ddTHH\\:mm\\:ss.GetResponse(). using System.0/me/manager/". TraceWriter log) { return new HttpResponseMessage(HttpStatusCode.IsNullOrEmpty(bucketsJson)) { { response = hwr.Environment. where possible } string bucketsJson = GetJson( "https://graph.fffffffzzz"). } 40 msdn magazine Office 0118msdn_AmmerlaanGraph_v3_34-41.CreateHttp(url).Info("Processing incoming task creation requests.value) return sr. string body. } } } } return null.Parse(managerJson). string now = DateTime. as was the case with the task sample in this { "name": "req". "en-us". Get started in building solutions for your "name": "myOneDriveFile". var payload = new ByteArrayContent(bodyContents).com/speech/ client.OK). "Bearer " + authToken). { string conversation_url = $"https://speech.cognitive. var transcriptionValue = await RequestTranscriptionAsync( response = await client. subscriptionKey)..PostAsync(uriBuilder. string responseJson = "default". } using Newtonsoft. "audio/wav"). byte[] bodyContents.Json.com/sts/v1.Text.Path += "/issueToken".TryAddWithoutValidation("content-type". // Download the contents of the audio file return null. n "path": "{query. { client. string authToken) // Transcribe the file using cognitive services APIs { log. with Azure Functions at functions. Matthew Henderson and Dan Silver Figure 6 Transcribing an Audio File from One Drive #r "Newtonsoft..ToArray().azure. var response = await client. System. Combining Microsoft Graph and Azure Functions allows "direction": "in" }. "type": "onedrive".Error($"Unexpected response from transcription service A: {ex. TraceWriter log) responseJson + "|" + response. } HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode. return data["DisplayText"].Uri.Net. hrm. }. "type": "http".Content.Json" response = await PostAudioRequestAsync(conversation_url. } audioBytes = StreamToBytes(myOneDriveFile).Configuration. developing products "direction": "out" such as SharePoint.0". uriBuilder. return ms. } ]. TraceWriter log) string fetchUri = "https://api."). using (var client = new HttpClient()) var bingAuthToken = await FetchCognitiveAccessTokenAsync(accessToken). Combined with the breadth of coverage of Microsoft Graph { and the ability to cross workloads (for example. tion.StatusCode + "|" + { response.DefaultRequestHeaders.platform.AbsoluteUri. return await response. organizational "bindings": [ hierarchy and tasks. you can build and add value across your entire organiza "type": "httpTrigger".. Yammer.").com.ReadAsStringAsync().ToString().Content = new StringContent("Content could not be transcribed..Content.CopyTo(ms).GetEnvironmentVariable("SpeechApiKey"). } if (null != transcriptionValue) { private static byte[] StreamToBytes(Stream stream) hrm. article). { } using (MemoryStream ms = new MemoryStream()) else { { stream. log.Environment. { string languageCode. return response.PostAsync(url. Excel.com/speech/ using (var client = new HttpClient()) recognition/conversation/cognitiveservices/v1?language={languageCode}".platform.indd 41 12/12/17 8:50 AM . Prior to this. Encoding. "text/html"). { string dictation_url = $"https://speech. private static async Task<HttpResponseMessage> PostAudioRequestAsync( string url. payload). { Mike Ammerlaan is a director of product marketing on the Microsoft Office Eco- "name": "$return".ToString() +"|"). var accessToken = HttpResponseMessage response.").Info("Downloading audio file contents. "identity": "userFromRequest". authToken).Message} |" + Stream myOneDriveFile. catch (Exception ex) { public static async Task<HttpResponseMessage> Run(HttpRequestMessage req. you to build out the full API to your organization. audioBytes.microsoft. JObject data = JObject. log).Linq.Add("Ocp-Apim-Subscription-Key". } byte[] audioBytes.Add("Authorization". bingAuthToken. using System.microsoft.").. "disabled": false } Thanks to the following Microsoft technical experts for reviewing this article: Ryan Gregg. helping people build engaging solutions with Office 365.ReadAsStringAsync(). using System. responseJson = await response. Bing Maps and Combat Flight Simulator.Headers.UTF8. and transform { productivity for all. } } } return hrm.com/graph.bing. string authToken.bing.Headers.Info($"Retrieving the cognitive services access token. log.. Figure 5 Setting Up a New Trigger for Getting a File on OneDrive Graph.com January 2018 41 0118msdn_AmmerlaanGraph_v3_34-41.DefaultRequestHeaders. log. HttpResponseMessage response = null. null). try } { } msdnmagazine. payload.filename}". organization by visiting developer.Parse(responseJson). } private static async Task<string> FetchCognitiveAccessTokenAsync( string subscriptionKey) private static async Task<string> RequestTranscriptionAsync(byte[] audioBytes.Info($"Transcribing the file. UriBuilder uriBuilder = new UriBuilder(fetchUri). system team. recognition/dictation/cognitiveservices/v1?language={languageCode}". and working "direction": "in". using System. he worked at Microsoft as a program manager for 18 years.Content = new StringContent(transcriptionValue. audioBytes. NET to Xamarin. returns to the strip. 2018 Bally’s Hotel & Casino Respect the Past. March 11 – 16. During this intense week of developer training. knowledge-share and networking at #VSLive25. Code the Future. VSLive! 1998 VSLive! 2017 SUPPORTED BY PRODUCED BY magazine Untitled-3 2 12/4/17 1:07 PM . Experience the education. Visual Studio Live! (VSLive!™) Las Vegas. celebrate 25 years of coding innovation as we take a fun look back at technology and training since 1993. 2018. March 11 – 16. Plus. you can sharpen your skills in everything from ASP. What’s our secret? YOU! Since our first conference (VBITS/ VSLive!/Visual Studio Live!). tens of thousands of developers.com/lasvegasmsdn twitter.NET Core Xamarin Azure / Cloud Hands-On Labs Software Practices ALM / DevOps SQL Server 2017 UWP (Windows) Who Should Attend and Why We’ve been around since 1993. programmers. DEVELOPMENT TOPICS INCLUDE: VS2017/.com – linkedin. software architects.com/vslive – facebook.NET Angular/JavaScript ASP. Register to code with us today! Register by January 19 and Save $400! Use Promo Code VSLJAN4 CONNECT WITH US vslive. engineers.com – Join the @VSLive Search “VSLive” “Visual Studio Live” group! Untitled-3 3 12/4/17 1:07 PM . designers and more have trusted us year-in-and-year-out for unbiased and cutting- edge education on the Microsoft Platform. NET Core for HoloLens & Immersive Headsets in Unity .Billy Hollis Roy Cornelissen & Marcel de Vries You will learn: 11:00 AM 12:00 PM General Session: To Be Announced .NET & Visual 12:00 PM 1:00 PM Birds-of-a-Feather Lunch > How to build your first mobile 1:00 PM 1:30 PM Dessert Break . March 13. with IdentityServer . we’ll start 12:00 PM 1:00 PM Lunch Speakers and sessions subject to change from zero. March 15. . and More .Coffee and Morning Pastries Sunday.Visit Exhibitors .Rockford Lhotka > How to think “mobile first” in 4:00 PM 5:15 PM W19 Assembling the Web .NET Core 2 For Mere Mortals TH02 Performance in 60 Seconds – SQL 8:00 AM 9:15 AM Sunday. March 12. Animation.NET Everywhere and for Everyone .Kevin Ford > The security architecture of 9:30 AM 10:45 AM T05 Angular 101 .Chris Klug .Coffee and Morning Pastries HOL on Angular TH01 ASP. . modules. with a little TypeScript.NET Core (Part 2) M 9:00am – 6:00pm (Part 1)* 9:00 AM 6:00 PM .com/lasvegasmsdn.Adam Tuliper Worst Practices . March 12.Brock Allen HOL01 Special 2-Day Hands- 4:00 PM 6:00 PM Conference Registration Open On Lab: Modern Security START TIME END TIME Pre-Conference Workshops: Monday. March 11. 2018 (Separate entry fee required) ONLY $645 through January 19 7:30 AM 8:00 AM Post-Conference Workshop Registration .Forms Projects . 9:00am – 6:00pm (Part 2)* START TIME END TIME Day 1: Tuesday. 2018 7:00 AM 8:00 AM Registration .Robert Boedigheimer with C# and CSLA .Deborah Kurata .Pinal Dave 9:00am – 6:00pm 9:30 AM 10:45 AM TH05 Getting to the Core of ASP.James McCaffrey Use promo code VSLDEC4 START TIME END TIME Post-Conference Workshops: Friday.Ben Hoelting . 4:15 PM 5:30 PM Welcome Reception START TIME END TIME Day 2: Wednesday.NET Core Razor Pages TH14 Introduction to Azure Machine works with components. March 11. March 11. HOL01 Full Day Hands-On Lab: Modern Security Architecture for ASP.Philip Japikse .Chris Klug * This 2-day Hands-On Lab is available with T14 Customizing Your UI for Mobile Devices: T13 Angular Component Communication 3:00 PM 4:15 PM Techniques to Create a Great User Experience the six-day conference package or on its . 2018 (Separate entry fee required) Architecture for ASP.Pinal Dave B Ted Neward 11:00 AM 12:00 PM Panel Discussion: To Be Announced In this Hands-On Lab.NET Core 7:30 AM 9:00 AM Pre-Conference Workshop Registration .NET Core 11:00 AM 12:00 PM KEYNOTE: .James McCaffrey and of course the ubiquitous TH17 Securing Web Apps and APIs TH18 Introduction to the CNTK v2 Machine 4:00 PM 5:15 PM model/view/controller approach. Principal Progr > About authenticating users 12:00 PM 1:00 PM Lunch with OpenID Connect 1:00 PM 1:30 PM Dessert Break . WebAssembly . Details at vslive. F01 Workshop: Creating Mixed Reality Experiences for HoloLens & Immersive Headsets F0 8:00 AM 5:00 PM with Unity .Brock Allen 7:00 PM 9:00 PM Dine-A-Round Monday.Coffee and Morning Pastries Xamarin and Xamarin.Coffee and Morning Pastries Choose From: HOL01 Full Day Hands-On Lab: Modern Security Architecture for ASP.Laurent Bugnion own.Billy Hollis your application architecture 7:00 PM 8:30 PM VSLive! High Roller Evening Out START TIME END TIME Day 3: Thursday.Robert Boedigheimer uniqueness while sharing a W15 Advanced Fiddler Techniques W16 Building Cross-Platforms Business Apps large chunk of your codebase 2:30 PM 3:45 PM .Scott Klein its core constructs and how it TH13 MVVM and ASP.Coffee and Morning Pastries Brock Allen T01 Go Serverless with Azure Functions T02 Getting Ready to Write Mobile T0 You will learn: 8:00 AM 9:15 AM .Alex Mullans > How to maintain platform 2:00 PM 2:20 PM W12 Fast Focus: HTTP/2: What You Need to Know W1 . 2:30 PM 3:45 PM .Ben Hoelting Learning . TH09 Entity Framework Core 2 TH10 SQL Server 2017 . Program Manager. 2018 HOL03 Busy Developer’s 7:30 AM 8:00 AM Registration .Kasey Uhlenhuth.Coffee and Morning Pastries Applies to HOL02 and HOL03 only.Visit Exhibitors > How to protect Web APIs T09 Busy Developer’s Guide to Chrome T10 Works On My Machine… Docker for with OAuth2 1:30 PM 2:45 PM Development .A Tour of W20 Radically Advanced XAML: Dashboards.Exhibitor Raffle @ 1:15pm (Must be present to win) apps on three platforms with the W09 Fast Focus: 0-60 for Small Projects in Visual Studio Team Services Xamarin framework 1:30 PM 1:50 PM .Intelligence Built-in then start working with Angular 2: 1:00 PM 2:15 PM For Mere Mortals . March 16. AGENDA AT-A-GLANCE So BACK BY POPULAR DEMAND ALM / DevOps Cloud Computing Database and Analytics Native Client Pr Sunday Pre-Con START TIME END TIME Full Day Hands-On Labs: Sunday. March 11.NET Core TH06 Secrets of SQL Server .James Montemagno.Forms W01 The Whirlwind Tour of Authentication W02 Building Mixed Reality Experiences Introductory / Intermediate 8:00 AM 9:15 AM and Authorization with ASP.Deborah Kurata T06 Lessons Learned from Real World Xamarin.Brian Noyes Learning Library .Database TH Security .Ted Neward Developers . Boyd Applications with Xamarin .Nick Landry ASP. 2018 (Separate entry fee required) Hands-On Labs 8:00 AM 9:00 AM Pre-Conference Hands-On Lab Registration .NET Core (Part 1) 9:00 AM 6:00 PM .Nick Landry & Adam Tuliper Untitled-3 4 12/4/17 1:08 PM . March 14.NET .Jason Bock Timelines.Philip Japikse Tricks Everybody MUST Know . W06 A Dozen Ways to Mess Up Your 9:00am – 6:00pm W05 TypeScript: The Future of Front End 9:30 AM 10:45 AM Transition From Windows Forms to XAML Web Development .Eric D. 2018 HOL02 From 0-60 in a Day with 7:30 AM 8:00 AM Registration .Nick Landry Sunday. Oren Novotny . 2018 Registration . and Yourself .Coffee and Morning Pastries T03 Database Development with SQL Server Data Tools T04 What’s New in Visual Studio 2017 for C# Developers . Microsoft Lunch Dessert Break .Roy Cornelissen & Marcel de Vries HOL on Angular .Alex Mullans W18 Getting to the Core of . W21 Encrypting the Web W22 Porting MVVM Light to .Leonard Lobel .Brian Randell Welcome Reception Day 2: Wednesday. 2018 Registration . 2018 Bally’s Hotel & Casino Software Visual Studio / ent Web Client Web Server Practices . March 14.Billy Hollis vslive.com/lasvegasmsdn Untitled-3 5 12/4/17 1:08 PM .Miguel Castro .Brian Randell ces: T15 PowerShell for Developers nce T16 To Be Announced .com – Join the Boss.Coffee and Morning Pastries es W03 Using Feature Toggles to Separate Releases W04 Lock the Doors.Brian Noyes “Visual Studio Live” group! Panel Discussion: To Be Announced Lunch TH11 Writing Testable Code and Resolving t-in TH12 Signing Your Code the Easy Way Dependencies . March 15.Miguel Castro TH15 “Doing DevOps” as a Politically TH16 Analyzing Code in .Coffee and Morning Pastries facebook. Bots.Oren Novotny ) Post-Conference Workshops: Friday.Robert Boedigheimer Lessons Learned . March 11.Scott Klein and Xamarin in 20 minutes .NET Standard with xUnit . Registration . March 12. March 11 – 16. ity from Deployments .Ted Neward will play host to Conference Registration Open Visual Studio Live!.Exhibitor Raffle @ 1:15pm (Must be present to win) W10 Fast Focus: Cross Platform Device Testing W11 Fast Focus: Understanding . 2018 (Separate entry fee required) Pre-Conference Hands-On Lab Registration . Await.NET Standard: VISUAL STUDIO LIVE! llis .Jeremy Clark .Roy Cornelissen .Coffee and Morning Pastries is offering a special ) M02 Workshop: Developer Dive into SQL Server 2016 M03 Workshop: Add Intelligence to Your Solutions with .Kasey Uhlenhuth T07 Introduction to Azure Cosmos DB T08 Using Visual Studio Mobile Center to Accelerate . and d) Pre-Conference Workshops: Monday.Jason Bock & Rockford Lhotka Basics of Principles and Process .Jeremy Clark to Rule Them All .Eric D.com – L TH03 Demystifying Microservice Architecture TH04 Cognitive Services in Xamarin Applications Search “VSLive” ve .Adam Tuliper CONNECT WITH rds.Veronika Kolesnikova & Willy Ci NET & Visual Studio.Laurent Bugnion pps a W17 Versioning NuGet and npm Packages .Leonard Lobel Mobile Development .NET .Coffee and Morning Pastries s F02 Workshop: Distributed Cross-Platform Application F03 Workshop: UX Design for Developers: Architecture .Laurent Bugnion VSLive! High Roller Evening Out twitter.Jason Bock W13 Fast Focus: Serverless Computing: Azure Functions W14 Fast Focus: TBD .Kevin Ford incipal Program Manager – Xamarin.Damian Brady ine TH19 I’ll Get Back to You: Task.NET Framework Full Day Hands-On Labs: Sunday.com/vslive – @VSLive Day 3: Thursday.NET Core .Oren Novotny .Jason Bock Powerless Developer .Veronika Kolesnikova e TH07 Unit Testing Makes Me Faster: Convincing Your TH08 Publish Your Angular App to Azure App Services linkedin. Make It So! ML Development in the Enterprise . Your Co-Workers. and TH20 Multi-targeting the World: A Single Project Asynchronous Methods . Boyd W07 Overcoming the Challenges of Mobile W08 Computer.Leonard Lobel AI. March 16.Marcel de Vries and Set the Alarm . and More . Microsoft Birds-of-a-Feather Lunch Dessert Break . 2018 (Separate entry fee required) Post-Conference Workshop Registration . March 13. Secure the Valuables.Visit Exhibitors or T11 DevOps for the SQL Server Database T12 To Be Announced . 2018 conference attendees.Brian Randell reduced room rate to Dine-A-Round Day 1: Tuesday.Forms .Visit Exhibitors . 2018 (Separate entry fee required) Pre-Conference Workshop Registration .Coffee and Morning Pastries HOL02 Full Day Hands-On Lab: From 0-60 in a Bally’s Hotel & Casino ) HOL03 Full Day Hands-On Lab: Busy Developer’s Day with Xamarin and Xamarin.DI Kills Two Birds with One Stone . U N I V E R S A L W I N D O W S P L AT F O R M What’s New for .NET UWP Development? Daniel Jacobson and Stefan Wick Back in October 2015, one of us had the pleasure to author Windows 10, and accelerate your UWP development to build great an article about .NET Universal Windows Platform (UWP) devel applications as quickly as possible. opment (msdn.com/magazine/mt590967). A lot has changed with .NET The Windows 10 Fall Creators Update brings a host of improve UWP development since then, and we wanted to address those ments for UWP developers, with Visual Studio 2017 version 15.5 and changes with a new article that helps get developers up to speed. later providing the best support for the Windows 10 Fall Creators Since October 2015, Microsoft has published a new release of Update SDK (10.0.16299.0). Some of the most important changes Visual Studio 2017, several new SDKs (including the most recent include new capabilities for enterprise applications, streamlined Windows 10 Fall Creators Update SDK), the Windows Applica application deployment, and support for both .NET Standard 2.0 tion Packaging Project, .NET Standard 2.0 support, improvements and the new Fluent Design System. Let’s explore these advancements. to NuGet, the new Fluent design system, new community driven tools including Windows Template Studio, and more. Many of New Capabilities in Windows these changes and improvements to the UWP developer ecosys for Enterprise Applications tem are designed to make it easier to bring your existing .NET Microsoft recognized the need to improve the Windows 10 Platform assets forward, optimize your application deployment strategy on for enterprise developers building applications for Windows on desktop PCs and has made important strides in this area with the This article discusses: Windows 10 Fall Creators Update. • Improvements for UWP developers in the Windows 10 Fall Best of Both UWP and Win32 Microsoft has improved the Creators Update Windows 10 Platform with the Desktop Bridge (aka.ms/desktopbridge) • How developers can modernize WPF and Windows Forms to enhance its appeal to all .NET developers, whether their current applications with Windows 10 and the UWP focus is on the UWP, Windows Presentation Foundation (WPF), • What’s new in Visual Studio 2017 for Windows client Windows Forms or Xamarin. With the new App Packaging project application developers type in Visual Studio 2017 version 15.5, you can create Windows • Support for .NET Standard 2.0 in UWP development projects App Packages for your WPF or Windows Forms projects, just like Technologies discussed: you can for UWP projects. Once your application is packaged, you get all the Windows 10 Visual Studio 2017, NuGet, .NET, Universal Windows Platform, Windows Presentation Foundation, Windows Forms application deployment benefits, including the option to distrib ute via the Microsoft Store (for consumer apps), the Microsoft 46 msdn magazine 0118msdn_JacobsonUWP_v3_46-53.indd 46 12/12/17 11:27 AM Store for Business and Education, or via any of your favorite app are many other ways to distribute applications packaged as an deployment options such as Intune. Packaged apps have access to .appx. These options support the deployment flexibility that many both the full UWP API surface and the Win32 APIs on desktop, so organizations require. you can modernize your WPF and Windows Forms applications Beginning with the Windows 10 Fall Creators Update, you gradually with UWP APIs and Windows 10 features. You can also can host your own .appx installer on the Web to invoke the app include your Win32 components in your UWP apps so that they installer automatically. It’s as simple as adding an activation scheme light up on the desktop with all Win32 capabilities. (ms-appinstaller:?source=) to the link to the .appx on the Web. For more information, check out the blog post on direct Web installs here: bit.ly/2mJfIUI. This approach makes it really easy to share The recent Fall Creators Update applications within your organization, simply by posting a link to the .appx on a Web site, for example. release has helped close the API You can also create app installer manifests to support automatic package updates. One advantage that this app installer technology and feature gaps between UWP provides over a scheme like ClickOnce is that automatic updates happen behind the scenes--the application can update before the and Win32 desktop applications. user of the application even launches it. To learn how to create your own custom .appinstaller files for automatic application Peace of Mind Users can install apps without regret and with updates in privately hosted deployment channels, check out the out concern that they contain malware. Installations don’t require blog here: bit.ly/2z4Fx3A. admin privileges, and each application install is isolated from If you need more capable device management tools in your others, easing management. Uninstalls are guaranteed to be clean, organization, you can leverage and distribute your applications with no rot in the Registry or file system or other unexpected side with Microsoft Intune (bit.ly/2B7OnyR). The Windows Application effects from installing software. This method of distribution is now Packaging Project is the fastest route to make your apps easily also available for your WPF and Windows Forms applications managed via Microsoft Intune. using the Windows Application Packaging Project. Last but not least, you can distribute your applications via the Visual Enterprise-Ready Security Windows Hello enables biometric Studio App Center (bit.ly/2AKpsjJ). Visual Studio App Center allows for authentication for devices and compatible apps. The Windows 10 rapid deployment to your development teams or beta testers of your App Model protects your data and system health through UWP application. You can also easily enable analytics to determine who’s app containers, which put the user in control over what apps can using your applications, and how they’re using them. and cannot do. In addition, apps must disclose their usage of resources, such as location or microphone, which the user or IT administrator controls via privacy settings. With Visual Studio 2017, it’s Closing Gaps for Desktop Applications The recent Fall Creators Update release has helped close the API and feature gaps between easier than ever to leverage UWP and Win32 desktop applications. Support for .NET Standard 2.0 has significantly increased the available API surface, while pro the Desktop Bridge to package viding access to many important NuGet packages that previously could not be used in UWP projects. For example, enterprise devel existing Win32 .NET applications. opers finally get access to SqlClient APIs to talk directly to SQL Server databases from their UWP projects. Microsoft also continues With the Windows Application Packaging Project and so many to improve the UWP App Model for desktop and enterprise channels of distribution for .appx packages, it’s easy to package and scenarios. Recent updates have enabled command-line activation, distribute your application for any scenario in your organization. auto-startup and capabilities for running with full-trust or with unrestricted execution lifetime (extendedBackgroundTaskTime Support for .NET Standard 2.0 and extendedExecutionUnconstrained). The Windows 10 Fall Creators Update is the first release of Windows 10 to provide support for .NET Standard 2.0. If you’re unfamiliar Streamlined Application Deployment with .NET Standard, you can get a lot of detail at aka.ms/dotnetstandard. Microsoft recognizes that many .NET developers are still building Effectively, .NET Standard is a reference implementation of the Windows Forms and WPF applications. In addition to making it as base class library that any .NET platform can implement, be it .NET easy as possible to bring existing assets forward, the company aims to Framework, .NET Core or Xamarin. The goal of .NET Standard solve a problem that many developers face today: deployment. With is to make it as easy as possible for .NET developers to share code Visual Studio 2017, it’s easier than ever to leverage the Desktop Bridge across any .NET platform on which they choose to work. (aka.ms/desktopbridge) to package existing Win32 .NET applications. While there are some similarities with the Portable Class Library You can certainly submit Win32 applications to the Microsoft (PCL) model, the biggest difference with .NET Standard is that Store with the Windows Application Packaging Project, but there you don’t have to choose which platforms you’re targeting. If the msdnmagazine.com January 2018 47 0118msdn_JacobsonUWP_v3_46-53.indd 47 12/12/17 11:27 AM One other huge benefit of .NET Standard 2.0 is that it provides a path forward for many existing .NET applications (whether they’re WPF or Windows Forms). If your .NET apps target .NET Framework 4.6.1 or later, you can start porting your codebehind into .NET Standard 2.0 libraries. That same code can then be shared across any .NET Platform that implements .NET Standard 2.0. The .NET Standard Compatibility Matrix in Figure 1 shows how sup port plays out across versions. This means you can start to port your code into reusable libraries, Figure 1 .NET Standard Compatibility Matrix and when you’re ready, you can share platform you target implements the base class library as defined the same code in UWP apps, Xamarin apps, .NET Core apps and more. by the standard, the shared code will work. A huge advantage of .NET Standard compared to PCLs is that when a new .NET Platform is introduced with .NET Standard support, you don’t need One other huge benefit of .NET to modify your shared code libraries, because you won’t have to add any new platform target. Standard 2.0 is that it provides a Early iterations of .NET Standard (versions 1.x) were a great start, but with the Windows 10 Fall Creators Update and .NET path forward for many existing Standard 2.0, Microsoft has made it drastically easier to share code across .NET platforms. .NET Standard 2.0 has about 20,000 more .NET applications. APIs compared to any 1.x version. In addition, .NET Standard 2.0 is supported with the .NET Framework version 4.6.1, as well as To assist you in determining if your code is API-compatible with UWP development for developers targeting the Windows 10 Fall .NET Standard 2.0, Microsoft created a portability analyzer that Creators Update. We’ll explore the nitty gritty details regarding will produce a report showing which APIs are compatible with each how all this works in the “.NET and UWP Development” section. .NET implementation (bit.ly/2zlgrBz). You can also check out a useful Channel9 video from .NET Conf 2017 that steps through the entire porting process, from a Windows Forms .NET application to a UWP application at bit.ly/2j9TB52. Fluent Design System With the evolution of computing devices and the emergence of mixed reality, it was essential that the Windows design system evolve, as well. To address this shift, Microsoft released the Fluent design system (fluent.microsoft.com). Built on top of five building block concepts—light, depth, motion, material and scale—this system is designed to support the next gen eration of UX across device types. With the Windows 10 Fall Cre ators Update, you can already see Fluent artifacts making their way Figure 2 Fluent Design in Action into Windows 10 and application 48 msdn magazine Universal Windows Platform 0118msdn_JacobsonUWP_v3_46-53.indd 48 12/12/17 11:27 AM Document Manipulation APIs Manipulating Documents? Americas: +1 903 306 1676 EMEA: +44 141 628 8900 Oceania: +61 2 8006 6987
[email protected] Untitled-1 1 11/6/17 12:31 PM you’ll immediately recognize improve Windows Application ments over Visual Studio 2015.ms/eshopuwp/src. which allows you to manage all create a new project type called the installations of Visual Studio 2017. These updates are centered on several design considerations. It supports scenario-driven acqui sition with the introduction of Workloads designed around what developers need to get their job done. A great way to see Fluent design in action is to take Windows 10 Creators Update (10. Workloads make it so that you only install what you need. Figure 4 WapProj Demo Windows Application Packaging 50 msdn magazine Universal Windows Platform 0118msdn_JacobsonUWP_v3_46-53. instances of Visual Studio 2017 can be installed side-by-side.0. In addition. again without breaking your production environment.windows. so you can install preview versions ( visualstudio. you can now 3). as well. including: make setup as fast and as • S ignificantly improved designer performance •H igh-fidelity designer surface. As soon as you begin to detail at aka. focused especially on easy as possible. The impact on Windows developers in the There are many improvements in Visual Studio 2017 compared to short term is that Microsoft must rebuild much of the tooling with Visual Studio 2015.0) or later. rendering artifacts introduced by the new Windows Fluent Design System Another sample (shown in Figure 2) that demonstrates Fluent • Fewer designer exceptions to minimize distractions and design principles in a more enterprise-focused scenario can be maximize developer productivity in the design surface found at aka.com) and try out preview SDKs. we’ll highlight some of the most import which developers have grown familiar. In this example.4 introduced some drastic updates Visual Studio 2017 was to to the XAML Designer. These updates to the designer required a rethink of the designer’s Improvements to Visual Studio 2017 underlying architecture. install Visual Studio 2017.com/vs/preview ) and retail versions (visualstudio.15063. This lets you try out the latest and greatest features without impacting your produc Figure 3 Visual Studio Installer tion environment.ly/2mK4pvH).16299. you can see the acrylic • Improved designer UX without breaking or changing exist material that provides a composited layer in the navigation pane. ant and impactful new capabilities of the IDE. One of the core priorities for Improvements to the XAML Designer Visual Studio 2017 version 15.ms/uwpsiblog.0. and not all the extra stuff that often made Visual Studio 2015 take so long to install. developers building Windows experiences.com) on the same machine. the SDK install can a look at the XAMLUIBasics sample in the UWP samples on be set up side-by-side.indd 50 12/12/17 11:27 AM . In addition. Here. Now you can enroll in the Windows GitHub (bit. beginning with the development. Packaging Project Things get started with the To streamline application deploy Visual Studio Installer (see Figure ment with Windows 10. Microsoft has only released the updates to the XAML Designer Let’s start with the latest tooling— to UWP developers targeting the Visual Studio 2017. To manage this challenge. You can read to make setup as fast and as easy as about the updates in much greater possible. ing XAML development in Visual Studio and Blend You can also see light effects that serve to highlight the “Add new •U pdated tools that help maximize the productivity of item” navigation button.0). Insiders Program (insider. One of the core Windows 10 Fall Creators Update priorities for Visual Studio 2017 was (10. downloads. security news. partner offers. SDKs.microsoft. which delivers the latest resources. magazine msdn.com/flashnewsletter Untitled-2 1 12/11/15 11:06 AM . and updates on national and local developer events. Get news from MSDN in your inbox! Sign up to receive MSDN FLASH. all . when an update to that library was made. One great use case of as shown in Figure 4.appx package format. library with no need to update every single project. and Figure 5 . you can update the Project. experience.0-Compatible UWP App when an update to your core librar ies are made. for NuGet package authors. With PackageRefer ence. which enables new scenarios such as package management across multiple proj ects. platform multi-targeting is publishing a single NuGet package to To create packages. The out put will be an . In addition. Let’s consider an example. Improvements to NuGet With Visual Studio 2017.NET UWP apps take advantage of the NuGet package reference model for adding NuGet packages to proj ects (bit. Every project that imports tions (for example. Let’s consider the same example.ly/2AXDDlz).indd 52 12/12/17 11:27 AM . Windows Application Packaging Project to your solution and add Finally. MSBuild integration enables conditional package references. every project that consumes that package would need to update the reference to take advantage of the latest version. The shared conditional package references. MSBuild target could specify conditional package dependencies to consume the Debug version of the library in Debug builds which provides finer control over of the projects that consume the library. This way. but now producing both a Debug and Release version of the core library. you have the unoptimized version of the library to provide the best debugging your project dependencies. Figure 6 Windows Template Studio Project Generation 52 msdn magazine Universal Windows Platform 0118msdn_JacobsonUWP_v3_46-53. This project allows you to add references to Win32 applica version in the custom MSBuild target.NET Standard 2. which provides finer control over your project depen MSBuild integration enables dencies. Traditionally. Just add a new Release versions of the project.appx that you can deploy using any of the methods mentioned in the “Streamlined Application Deployment” section of this article. NuGet package references provide several benefits for both NuGet package authors and NuGet package consumers. you can leverage platform a reference to your Win32 application using the Applications node. your enterprise can create a shared MSBuild target that gets imported into every project. right-click on the Windows Application Packaging Project and select Store | Create App Packages. multi-targeting in a single NuGet package. Say you work in an enterprise that has a core library shared across all (or many) projects that your enterprise produces. PackageReference has direct MS Build integration. You can configure the conditional dependency to then switch to the Release version of the core library when building Taking advantage of this project is simple. Windows Forms and WPF) and package them that MSBuild target will now reference the updated version of the using the . 5 architectures. and more in a simple wizard update to support . support all .NET and UWP developers.NET application that’s targeting . The Microsoft.com or on Useful Open Source Projects Twitter: @pmatmic. You can tions.NET Framework library on NuGet that you want to build many views.0. With . the specified platform is correlated to the TargetPlatformMinVersion of your project. Windows Template Studio is a great . The license provides free use for anyone flexibility to move at your pace—by specifying the version of . or implements . performant.NET Core for Windows 10. Telerik announced that it was open sourcing the Telerik UI UWP NuGet package.NET Native. For UWP development. This gives you the for UWP controls library. ready applications with the UWP. D aniel Jacobson is a program manager for Visual Studio.NET Standard 2. If you set For . don’t hesitate to reach out by e-mail or Twitter. the UWP Community Toolkit Universal Windows Platform. n always reference the latest and it should always work. You must services and more. background tasks. we wanted to leave you with some helpful open source projects that you can use to accelerate UWP development.0 and all the If your TargetPlatformMinVersion is greater than or equal to the platform specified in the NuGet package. Even though the .ms/wts). that you need and that you know works for your application.0 is UWP Community Toolkit The UWP Community Toolkit available in the Windows 10 Fall Creators update. including .NET platforms. working on tools for Windows platform developers.0 implementation.NET implementation for the 2017. These S tefan W ick is a program manager lead in Windows.NET Framework 4.NET Standard 2.NETCore.UniversalWindowsPlatform NuGet Closing Thoughts package takes advantage of platform multi-targeting support for It’s clear that a lot has changed for .0 imple that take advantage of the best of UWP and Win32. that was a lot of and Windows Forms.NET developers. It leverages best practices for development.com January 2018 53 0118msdn_JacobsonUWP_v3_46-53. Previously mentioned in this article is that . all of . Built. Matthijs Hoekstra. helper classes.5 or later way to get started building fully-fledged UWP apps (aka. the NuGet restore process will bring in the .ly/2AZA0iI.NET Standard 2. Reach him at
[email protected] TargetPlatformMinVersion less than the Windows 10 Fall Creators and all the free resources available.com or on and the Telerik Controls for UWP Development.0 and UWP Development announcement on the company’s blog: bit.NET building UWP apps. the . enterprise-ready controls—and with UWP develop ment they’re now free! Read more about the Telerik open source .com/Microsoft/UWPCommunityToolkit) is another community-driven tage of the . as shown in Figure 5. so as you build your Windows applica about which version of the NuGet package to reference.NET Core implementation for UWP development was shipped as a set of NuGet packages. controls. it’s never be referenced in the project. Now.NET Framework 4. The TargetPlatformMinVersion of your UWP project to the Windows toolkit includes templated animations.0 will be able to consume the NuGet package.0 or later. NuGet package version 6.NET Standard 2.NET Standard 2.0 implementation.NET for UWP Telerik Controls for UWP Development Back in February development ships as part of the . working on the include Windows Template Studio. Windows Template Studio Windows Template Studio (shown in Figure 6) is a dynamic template generator for UWP develop Thanks to the following Microsoft technical experts for reviewing this article: ment.NET Stan enterprise-ready applications with the Universal Windows Platform. With . In Visual Studio 2015. Microsoft is constantly improving its tools text—what it means for you is that you shouldn’t have to worry based on your feedback.NET Standard 2. NuGet will bring in the . the Desktop Bridge platform and updated the TargetPlatformMinVersion to the Windows 10 Fall Creators tooling combine to let you build powerful desktop applications Update or later. The latest version of your experience. regardless of the con and feel across apps and encourage best practices for application suming project. 10 Fall Creators Update or later. Use the UWP Community Toolkit to acceler also reference the Microsoft. if you have a .NET Standard 2. If you are building an application that has a applications as fast and easy as possible. the NuGet package can free resources available. regardless of your Windows 10 target. Using Windows Template Studio for all new application NuGet package can maintain both implementations so the latest development in an organization can help ensure consistent look version of the package is always applicable.UniversalWindowsPlatform ate your development.NETCore.indd 53 12/12/17 11:27 AM .NET Native. it’s never been easier to build Update. Telerik has a history of building powerful. developers faced a slightly fragmented experience when it came to . including WPF mentation of . any munity of Windows developers. Reach him at dajaco@microsoft. To take advan (github.NET Native compiler was shipped as been easier to build enterprise- part of Visual Studio. you must set your project that provides helpful tools for UWP development. Let’s say you’ve previously built and UWP app.4 implementation of . For example. Finally.NET Core for Windows 10.NET Standard 2.NET Standard 2. Unni Ravindranathan and Ricardo (Rido) Minguez msdnmagazine. With Visual Studio 2017. and lets you managed a . UWP development so you can always update to the latest ver with so many new tools and updates to make building Windows sion of the package. dard 1. maintained and updated by a passionate com implementation and a . It’s the fastest way to get started building a production-ready Mike Harsh. Twitter: @StefanWickDev. 2018. stay ahead and avoid Winter. AUGUST 6 – 10. Microsoft HQ. WA. visit the company store. 2018 • Microsoft Headquarters. Change. where you can have lunch with Blue Badges. ahem. As we celebrate the 20th year of TechMentor. Windows PowerShell Join us for TechMentor. and experience life on campus for a week! Hyper-V Are You Ready? IT Security EVENT PARTNER SUPPORTED BY PRODUCED BY Untitled-2 2 12/12/17 12:27 PM . Azure Plus you’ll be at the source. WA Hot Topics Covered: Change is Coming. with the tools you DevOps need today. while preparing you for tomorrow – keep up. In today’s IT world. we are more committed than ever to providing immediately usable IT education. August 6 – 8. Windows Server more things change than stay the same. as we return to Microsoft Headquarters in Redmond. Redmond. com/redmond Untitled-2 3 12/12/17 12:11 PM . In-Depth Training for IT Pros @ Microsoft Headquarters You owe it to yourself. your company and your career to be at TechMentor Redmond 2018! SAVE $400! REGISTER NOW Use Promo Code TMJAN2 CONNECT WITH TECHMENTOR Twitter @TechMentorEvent Facebook Search “TechMentor” LinkedIn Search “TechMentor” techmentorevents. have a lot of knowledge and experience working with them. But everybody says that the UWP is for developing small apps This article discusses: for Windows tablets and phones. And. though it’s still being updated. neither can be deployed to the Windows Store and or Windows Presentation Foundation (WPF). WPF. from the tiny Raspberry Pi to the huge Surface Hub. SQL Server use . and could be difficult to learn and use. Moreover. and so on. nents or do some magic tricks. hasn’t caught up with the latest improvements to the OS and its That seems to be a difficult choice: You can select Windows Forms SDK. You can use Centennial oper.com/bsonnino/lobuwp best experience to develop a new app.0 develop: all those new patterns. besides that. unless you use extra compo- Web isn’t an option and you must choose the best platform for it. you discover the Universal Windows Microsoft will discontinue any of them in the near future. but that’s not like getting “the real thing.NET devel.NET Standard 2.NET Standard 2. there’s no such thing as an LOB • Universal Windows Platform development app using the UWP. world- technologies with a lot of components. U N I V E R S A L W I N D O W S P L AT F O R M Creating a Line-of-Business App with the UWP Bruno Sonnino One day. this is no Technologies discussed: longer true. . to package the apps. It’s was created in 2006). There’s been aggressive development of new features— Universal Windows Platform. the XAML language. and you. new tools and components can give you the github. • Telerik controls for the UWP All that is far from the reality. as a . Windows Template Studio (WTS) is an extension to Visual Studio that provides a fast start to 56 msdn magazine 0118msdn_SonninoUWP_v3_56-63. as well as access SQL Server directly. wide discovery and distribution.” Will they be there in 10 years? My guess is yes. it’s very difficult to learn and • .0. your boss comes to you with a new assignment: Windows Forms doesn’t use the latest graphics cards and you’re You must create a new line-of-business (LOB) app for Windows. these technologies have some other problems: being actively improved and can be used with no change in a wide range of devices.indd 56 12/12/17 9:01 AM . the sandbox • Windows Template Studio that limits what can be done. Code download available at: At the same time. Windows with the new Fall Creators Update (FCU) and its SDK you can even Template Studio. Though in the past the UWP had some limitations. stuck with the same old boring style. to ensure it will be available for at least 10 more years. But in Platform (UWP) for developing for Windows 10 and see that addition to being a bit old (Windows Forms is from 2001 and WPF it doesn’t have the downsides of Windows Forms and WPF.0 APIs.NET Standard 2. there’s no sign that Digging a little more. which are mature benefit from it: There’s no easy deploy and install/uninstall. and on and on. You can also install it by going to aka. open source extension (you can get the source code from aka. Your version should be 1709 or newer). Visual Studio 2017 update 4 or newer. msdnmagazine. for the best UX.0 in the UWP is available only in in Figure 2. include. choose the pages in the app. Blank. as shown The support for . After you download it. In the next window you can select some features for the app. A new window will open to to use . and a Master-Detail page and name it Sales. Once you have FCU installed on your choose the project (see Figure 1). Not bad. You can run the app—it’s a complete app with a hamburger menu. you need the FCU and its corresponding SDK select the Windows Template Studio. there’s already a blank page selected. two pages (blank and master-detail) and a settings page (accessed by clicking the cog icon at the bottom) that allows you Figure 2 Page Selection to change themes for the app. then select Next. you can install WTS. you As you can see in the right Summary column. the pages new platform for developing your UWP LOB apps! you want in your project and the Windows 10 features you want to In this article. you can go to Visual Studio and create a Introduction to the Windows Template Studio new project using File | New Project | Windows Universal and As I said before. named Main. Now.NET 4. work. press Win+R and type Winver to show Select the Navigation Pane project and the MVVM Light frame- your Windows version.0.indd 57 12/12/17 9:01 AM .NET Standard 2.0. click on the Create button to create the new app with the selected features. then click on the Next button. I won’t choose any features now. or a First Use dialog that will be presented the first time the app is run. With the infrastructure in place. and the Telerik components and direct access to SQL Server using PRISM. In Visual Studio. Now. There’s a lot of development going on in this project. Visual Basic templates and Xamarin support are already .NET Standard 2. such as Live Tile or Toast.ms/wtsinstall. the Model-View-View- for UWP for free. You also need the . go to Tools | Extensions and Updates and search for Windows Template Studio. Windows Template Studio is a new. restart Visual Studio to finish the installation. Select a Settings page and name it Settings. except the Settings storage that’s selected when you choose the Settings page. available in the nightly builds (coming soon to the stable version).7 runtime installed to use it. I’m going to develop a UWP LOB app using WTS.ms/wts) that will give you a great quick start to UWP development: Figure 1 Windows Template Studio Main Screen You can choose the type of proj- ect (a Navigation Pane with the a full-featured UWP app and you can use the Telerik components hamburger menu.NET Standard 2. so if you haven’t updated. so you can see how everything works firsthand. or Pivot and Tabs). no? Now you have a Model (MVVM) framework for your MVVM pattern. machine (if you aren’t sure. With WTS installed.com January 2018 57 0118msdn_SonninoUWP_v3_56-63. must do it now. downloading the installer and then installing WTS. o. If you go to Solution Explorer. conn). public async Task LoadDataAsync(MasterDetailsViewState viewState) Quantity = reader.User ID=sa.GetString(1). PropertyChanged?.FirstOrDefault().CustomerID " + "inner join Sales. } Description = reader.Add(orderItem). " + public IEnumerable<OrderItem> OrderItems "sum(l. set.Add(order).GetDecimal(2). var orders = await DataService. return results. you (DateTime?)null }.OrderLines where OrderID = {orderId}". set.GetOrdersAsync(). new PropertyChangedEventArgs("OrderItems")).OrderId. } } } if (viewState == MasterDetailsViewState. conn).OrderId. no? But I’m pretty sure that’s not } catch what your boss had in mind when he gave you the assignment. var results = new List<Order>().resw file } return results.OpenAsync(). } using (SqlConnection conn = new SqlConnection( public DateTime OrderDate { get.User ID=sa. { UnitPrice = reader. int orderId) This is a great improvement.PickingCompletedWhen.Quantity. return null. " + public event PropertyChangedEventHandler PropertyChanged. } try public DateTime? DatePicked { get. DatePicked = !reader.0 in the UWP.OrderID = l. { get => _selected.OrderID " + set "group by o.OrderDate.PickingCompletedWhen " + _orderItems = value. RaisePropertyChanged("Orders"). Impressive what you’ve been } able to do with just a few clicks.. while (reader.UnitPrice) as OrderTotal " + { "from Sales. { o. value). There’s even a Strings folder with an en-US subfolder for the local.ExecuteReaderAsync()) } { public override string ToString() => $"{Company} {OrderDate:g} {OrderTotal}". set using (SqlDataReader reader = await cmd. SqlCommand cmd = new SqlCommand( "select Description. while(reader. you’ll see that many folders were OrderId = reader. { } Orders = new ObservableCollection<Order>(orders).Password=pass")) public string Company { get. } "Database=WideWorldImporters.. created for the app. Figure 3 The Order Class Figure 5 Code to Retrieve the Orders from the Database public class Order : INotifyPropertyChanged public static async Task<IEnumerable<Order>> GetOrdersAsync() { { public long OrderId { get.Quantity * l.OpenAsync().Server=.OrderDate. so { let’s go customize that app! return null. because it allows UWP apps to use a { using (SqlConnection conn = new SqlConnection( "Database=WideWorldImporters.NET Standard 2. copy the Resources. } using (SqlDataReader reader = await cmd.CustomerID = o.Customers c on c.Invoke( this. and translate it to the new language. if (orders != null) results.CustomerName. SqlCommand cmd = new SqlCommand("select o.GetDecimal(4). private set. set.UnitPrice " + public Order Selected $"from Sales. OrderTotal = reader.Read()) } { var order = new Order { Company = reader.IsDBNull(3) ? reader. name it with results.Server=. set.Password=pass")) Figure 4 SalesViewModel { try public class SalesViewModel : ViewModelBase { { await conn. ViewModels and Services.GetInt32(0).Read()) } { } var orderItem = new OrderItem { public ObservableCollection<Order> Orders { get. If you want to add more languages to the app.indd 58 12/12/17 9:01 AM . }. o.OrderLines l on o.OrderDate desc". "order by o. c. await conn. } } } } } } 58 msdn magazine Universal Windows Platform 0118msdn_SonninoUWP_v3_56-63. set. } } Accessing SQL Server from the App } One nice feature that was introduced in the FCU and in Visual public static async Task<IEnumerable<OrderItem>> GetOrderItemsAsync( Studio update 4 is the support for . var results = new List<OrderItem>().CustomerName. such as Models. } { public decimal OrderTotal { get. just need to add a new subfolder to the Strings folder.GetString(0).Orders o " + get => _orderItems. OrderDate = reader.Both) catch { { Selected = Orders. private Order _selected.GetDateTime(2). the locale of the language (like fr-FR).ExecuteReaderAsync()) { { Set(ref _selected. } { public bool Delivered => DatePicked != null.GetDateTime(3) : ization of strings. o.GetInt32(1). private IEnumerable<OrderItem> _orderItems. "c. "inner join Sales. Untitled-5 1 7/6/17 3:22 PM . to Margin="0. </StackPanel> // This is used by the SampleDataService. <ColumnDefinition Width="*"/> </Grid. if not. I must also <grid:RadDataGrid.15. Now I need to modify the list items data template in Sales Mode=OneWay}" Grid. </Grid> // It is the model class we use to display data on pages like Grid. set.Resources> because I want to notify the UI when the order items are changed <Style x:Key="RightAlignField" TargetType="TextBlock"> so I can load them on demand when displaying the order.12"> When the Selected property is changed. } <RowDefinition Height="Auto" /> public decimal TotalPrice => UnitPrice * Quantity. If you’re add- <Grid Height="64" Padding="0. while you still have Figure 6 The List Items Data Template the NuGet package manager window open.OrderItems = await </grid:RadDataGrid> DataService.OrderItems == null) </grid:RadDataGrid.12. including SQL With that. Chart. go to access method—but by using TCP/IP.0" UserFilterMode="Disabled" BorderBrush="Transparent" I need to change the DataType so it refers to the new Order AutoGenerateColumns="False"> class and change the fields presented in the TextBlocks. <DataTemplate x:Key="DetailsTemplate"> <views:SalesDetailControl MasterMenuItem="{Binding}"/> There are a lot of comments throughout the project that give </DataTemplate> guidance on what you need to do. So. to store the order items: <Setter Property="Margin" Value="0.0.0. This is done in the PropertyName="UnitPrice" Header="Unit Price" CellContentStyle="{StaticResource RightAlignField}"/> OnMasterMenuItemChanged method.ToShortDateString()}" Models folder. I’ll also use the Telerik UI for UWP grid.UniversalWindowsPlatform package.0. Rename the class to Order and Figure 7 Changes in SalesDetailControl change it to something similar to the one in Figure 3.ToShortDateString().Resources> public string Description { get. which is transformed to <grid:DataGridNumericalColumn an async method: PropertyName="Quantity" Header="Quantity" private static async void OnMasterMenuItemChangedAsync(DependencyObject d. with this comment Margin="0.0.0" /> <TextBlock Text="{x:Bind OrderTotal}" Margin="0. In this case. note: the access isn’t made by using named pipes—the default To make SQL Server client access available in your app.for.ly/2AFWktT. One Server client access and Entity Framework Core.OrderId). shown in Figure 4. CellContentStyle="{StaticResource RightAlignField}"/> if (newOrder != null && newOrder.0.ColumnDefinitions> ing a grid page in WTS.OrderItems. <Grid Name="block" Padding="0.SqlClient. Mode=OneWay}" The last change in the code to make is in the SampleDataService Style="{StaticResource BodyTextBlockStyle}" Margin="0.12.NewValue as Order. <TextBlock Text="Order total:" Style="{StaticResource BodyTextBlockStyle}" as shown in Figure 5.xaml. set.12. <ColumnDefinition Width="Auto"/> For this app. select “Manage NuGet packages” and install System. you need an Order class that’s very similar to this one.0. Mode=OneWay}" reflect that it’s not a sample anymore. So. Then right-click the References node and your server instance. } <Grid.xaml to reflect the changes. at all. Mode=OneWay}" to reflect these changes.ly/2fLYuBk and restore it to your <StackPanel Grid. I’ve <Setter Property="HorizontalAlignment" Value="Right" /> <Setter Property="VerticalAlignment" Value="Center" /> defined another class. huge number of APIs that were unavailable before. ItemsAsync method in the data service to load them. now a free open source product that you’ll find at bit.0. it calls the GetOrder Style="{StaticResource BodyTextBlockStyle}" Margin="0.Column="1" Margin="12.Columns> <grid:DataGridTextColumn PropertyName="Description" /> change the codebehind in SalesDetailControl.0.0" The SalesViewModel. must also be modified Text="{x:Bind MasterMenuItem. set.12. </DataTemplate> and Master Detail.GetOrderItemsAsync((int)newOrder. This class implements the INotifyPropertyChanged interface. </Grid> } 60 msdn magazine Universal Windows Platform 0118msdn_SonninoUWP_v3_56-63.indd 60 12/12/17 9:01 AM .0"> <Grid.cs to load the <grid:DataGridNumericalColumn Items for the selected order when it’s changed. you must run the SQL the app properties and select Build 16299 as the Minimum Version Server Configuration app and enable TCP/IP connections for in the application tab. UserGroupMode="Disabled" Margin="12.0.0" /> at the beginning: </StackPanel> // TODO WTS: Remove this class once your pages/features are using your data.Row="1" Margin="12. <TextBlock Text="{x:Bind Company}" Style="{ThemeResource ListTitleStyle}"/> <StackPanel Orientation="Horizontal"> Now.Company. as shown in Figure 6.NET app. Style="{StaticResource BodyTextBlockStyle}" /> The code is the same you’d use in any .Data. this package is installed automatically.RowDefinitions> public decimal UnitPrice { get.RowDefinitions> <TextBlock Margin="12. CellContentStyle="{StaticResource RightAlignField}"/> DependencyPropertyChangedEventArgs e) <grid:DataGridNumericalColumn { PropertyName="TotalPrice" Header="Total Price" var newOrder = e.UI. <RowDefinition Height="*" /> } </Grid.Row="2" Page.0"/> <TextBlock Text="{x:Bind MasterMenuItem. to remove the sample data and create the SQL Server access.0.0. Style="{StaticResource SubheaderTextBlockStyle}" /> <StackPanel Orientation="Horizontal" Grid. } <RowDefinition Height="Auto" /> public int Quantity { get.0"/> class.0"/> <TextBlock Text="{x:Bind MasterMenuItem.OrderTotal. OrderItem.12. there’s no change </StackPanel> <grid:RadDataGrid ItemsSource="{x:Bind MasterMenuItem.8"> <Grid. If you go to the <TextBlock Text="{x:Bind OrderDate. I’ll use the WorldWideImporters sample database.0. you’re ready to access a local SQL Server database.Columns> newOrder.0" /> public class OrderItem </Style> { </Grid. you must change the default data access. it will check whether the <TextBlock Text="Order date:" order items are already loaded and.0" VerticalAlignment="Center"> SQL Server instance. I’ve renamed the class to DataService. you’ll see the SampleOrder class.12.12.ColumnDefinitions> which you can download from bit. select and install the <DataTemplate x:Key="ItemTemplate" x:DataType="model:Order"> Telerik.OrderDate. If you go there.Add(new ShellNavigationItem("Shell_Main". private set. which Figure 8 Application Showing Database Orders point to where to go to change the icons and the text for the items: Next. so I use the hex value and cast it to the Symbol enumeration. I cursor over RadDataGrid.resw: Add a menu item title for each page I still have the empty main page. but for the second there’s no such enumeration. type Ctrl+. but you don’t need at bit. Symbol. and a box will open. The icons in the lateral bar for both pages are the same and they can be customized. then choosing { Customers = new ObservableCollection<Customer>(customers). As you can see from the added _primaryItems. One tion.Add(new ShellNavigationItem("Shell_Sales".com January 2018 61 0118msdn_SonninoUWP_v3_56-63. People and ShoppingCart. // Edit String/en-US/Resources. Just put the mouse from Segoe UI Symbol. I’m binding the ItemsSource property to Customers. _primaryItems. you can run the app and see the customers on the main page. typeof(MainViewModel). Everything to add a Live Tile will be there. like what’s shown in Figure 8. it will show the RaisePropertyChanged("Customers"). To do that.resw and change Shell_Main and Main_Title.xaml. } } so you can see if you really like what you did. thing to notice here is that I don’t wait for the loading to complete. as shown in Figure 7. you just need to cre- } ate the tile content.com/Microsoft/WindowsTemplateStudio/blob/master/docs/ RadDataGrid to show the order items.png <grid:RadDataGrid ItemsSource="{Binding Customers}"/> files.GetCustomersAsync(). Live Tile. { LoadCustomersAsync().GetLocalized(). as shown in Figure 11. projectTypes/navigationpane. } Adding a Live Tile to the App public async Task LoadCustomersAsync() I can also enhance the application by adding a live tile.md tion.People.Sam- } ples. take a look You must add the namespace to the Page tag. indi.microsoft. must change the NavigationItems in the code: cating the right namespace to add.ly/2zICuB2 for more information. line. When you click on the Next button. with a customers grid and a mas- ter-detail view showing the orders.Text The GetCustomersAsync method in DataService is very similar to Customers.cs. by going to Solution Explorer. sort- ing and filtering are built into the grid and there’s no extra work to do. This is already done in LiveTileService. changing some properties: <grid:RadDataGrid ItemsSource="{Binding Customers}" Figure 9 MainViewModel Class UserColumnReorderMode="Interactive" ColumnResizeHandleDisplayMode="Always" public class MainViewModel : ViewModelBase AlternationStep="2" AlternateRowBackground="LightBlue"/> { public ObservableCollection<Customer> Customers { get.GetLocalized(). the ViewModel indicates that the change the title of the page and the caption of the menu item. To When the data is fully loaded.People. as you can see in Figure 10. Now.indd 61 12/12/17 9:01 AM . For the first item. so I must (Symbol)0xE7BF. edit Resources. there’s already a symbol in the Symbol enumera- I’m loading the customers when the ViewModel is created. Clicking on the public MainViewModel() Finish button will add the changes to the app.com/windows/uwp/style/segoe-ui-symbol-font I display the sales data in the top of the control and use a Telerik // Or to use an IconElement instead of a Symbol see // https://github.) I’m going to use two symbols to remember the syntax and correct namespace. Symbol. create this property in MainViewModel. affected tiles (both new ones and those that have been changed). but it can use some finishing touches. I get the orders on the second page.FullName)). right-clicking the project node and if (customers != null) selecting Windows Template Studio | New feature. With that. I Customers property has changed and that loads the data in the view. In MainPage. The Data. I’ll do so { var customers = await DataService. you’ll see these comments. you get a lot of goodies for free: grouping. I’ll use it to show a grid of all You can use font symbol icons (as in the actual code) or images customers. when I run the applica. or characters from any other fonts. I must change SalesDetailControl to point to the new fields // TODO WTS: Change the symbols for each item as appropriate for your app // More on Segoe UI Symbol icons: and show them. (You can use .FullName)). These icons are set in the ShellViewModel. as shown in Figure 9. I can also add some customization to the grid by to GetOrdersAsync. Context for the page is an instance of MainViewModel. Using the Telerik grid. XAML paths. Finishing Touches I have now a basic LOB application. add the DataGrid to the content grid: from other sources if you use IconElements. It’s a partial class that adds the method SampleUpdate to msdnmagazine. // https://docs. typeof(SalesViewModel). Server=.CityName. you have access to a lot of APIs that are already avail- able in the . public async Task LoadDataAsync(MasterDetailsViewState viewState) Phone = reader. Not bad! Wrapping Up As you can see. Figure 10 GetCustomersAsync Method LiveTileService.Customers c " + } "inner join Sales.User ID=sa.CustomerCategoryName.GetString(1). public async Task LoadCustomersAsync() var results = new List<Customer>().CustomerCategoryID = cat.Count).GetString(2). { if (customers != null) while (reader. var customer = new Customer RaisePropertyChanged("Customers"). WTS gives you a quick start. sort or fil- ter the customers listed and show the orders using a master-detail view. } Name = reader. catch } { if (viewState == MasterDetailsViewState.FirstOrDefault().NET Framework. You can group. private async Task StartupAsync() c. getting the data from many sources. with no change.GetInt32(0).DeliveryCityID = That will happen when I get the customers in MainViewModel: city.UpdateCustomerCount(0).Instance. " + { "cat.DeliveryAddressLine2.DeliveryPostalCode.Read()) { { Customers = new ObservableCollection<Customer>(customers).ExecuteReaderAsync()) var customers = await DataService. I still don’t have the customer count to update. { Singleton<LiveTileService>. c. The orders count will be updated when I get the orders in Sales- Address = reader.CityID". helping you to quickly and Figure 11 Customers Grid with Grouping and Filtering easily create an application using 62 msdn magazine Universal Windows Platform 0118msdn_SonninoUWP_v3_56-63. { using (SqlDataReader reader = await cmd. CustomerId = reader. " + ThemeSelectorService. With . updating the live tile with the customers and order counts.NET Standard 2. ViewModel: City = reader.0. I have an app as shown in Figure 13. which will show in using (SqlConnection conn = new SqlConnection( "Database=WideWorldImporters.SetRequestedTheme().GetString(4).Instance. Orders = new ObservableCollection<Order>(orders).Count). "from Sales.OpenAsync().GetString(6) { }.CompletedTask. c. { } Selected = Orders.GetCustomersAsync().UpdateCustomerCount(Customers. As shown in Figure 12.GetString(5). PostalCode = reader. Singleton<LiveTileService>. } } } } With that. if (orders != null) } { return results.Password=pass")) the live tiles how many customers or orders are in the database. } Singleton<LiveTileService>.PhoneNumber " + await Task. } RaisePropertyChanged("Orders"). Update { CustomerCount and UpdateOrdersCount. You can use it for your LOB apps.UpdateOrderCount(Orders. I’ll rename the file to public static async Task<IEnumerable<Customer>> GetCustomersAsync() LiveTileService. in the try { StartupAsync method of ActivationService.CustomerID. I’m going to replace await conn. the UWP isn’t just for small apps. var orders = await DataService. conn).CustomerCategoryID " + At this point. "city.. { UpdateSample was originally called in the initialization. } Category = reader.Both) return null.LobData and add two methods to it. "inner join Application.CustomerName. This app can show the custom- ers and orders retrieved from a local database.Add(customer).Cities city on c. including a local SQL Server (and you can even use Entity Framework as an ORM).GetOrdersAsync().GetString(3). results. c. it with the new UpdateCustomerCount: SqlCommand cmd = new SqlCommand("select c.indd 62 12/12/17 9:01 AM .CustomerCategories cat on c.Instance. Children = var notification = new TileNotification(tileContent.CaptionSubtle.ly/2zH0nZY). HintStyle = AdaptiveTextStyle."Order").com/bsonnino. } new AdaptiveText() } { best practices with the tools you prefer.Caption } }.msmvps. and have worldwide discovery.ToString() : "no")} { orders in the database". n Bruno Sonnino has been a Microsoft Most Valuable Professional (MVP) since 2007. you can send your app to the store the app and the app will run in a wide range of devices: on a phone. HintWrap = true } public void UpdateCustomerCount(int custCount) } { } string tileContent = }. you should certainly consider the UWP. tures to it. { HintWrap = true Visual = new TileVisual() } { } TileMedium = new TileBinding() } { } Content = new TileBindingContentAdaptive() } { }. TileContent tileContent = new TileContent() HintStyle = AdaptiveTextStyle. easy install and uninstall and auto updates. }. If you don’t want to deploy it through the store. Thanks to the following Microsoft technical expert who reviewed this Figure 13 The Finished App article: Clint Rutkas msdnmagazine. Text = TileTitle. the Surface Hub and even on HoloLens without change. TileWide = new TileBinding() UpdateTileData(tileContent. string tileTag) { { Text = tileBody.ToString() : "no")} customers in the database". { } Content = new TileBindingContentAdaptive() { public void UpdateOrderCount(int orderCount) Children = { { string tileContent = new AdaptiveText() $@"There are {(orderCount > 0 ? orderCount. "Customer"). private const string TileTitle = "LoB App with UWP".indd 63 12/12/17 9:01 AM . having written many books and articles about Windows development. $@"There are {(custCount > 0 ? custCount. a desktop. Figure 12 Class to Update the Live Tile internal partial class LiveTileService Text = tileBody. you can do so using the Web (bit. { HintStyle = AdaptiveTextStyle. You can fol- low him on Twitter: @bsonnino or read his blog posts at blogs. new AdaptiveText() private void UpdateTileData(string tileBody. when you have to create a new LOB app for Windows. consultant. He’s a developer. As you can see.GetXml()) { { new AdaptiveText() Tag = tileTag { }. and author.CaptionSubtle. There are great UI controls to enhance the appearance of When it comes to deploying. HintWrap = true UpdateTile(notification). because it can offer you everything you want for this kind of app and more. with the great advantage that it’s being aggressively developed and will bring you a lot of improvements for years to come. and to add Windows fea. Text = $"{TileTitle}". UpdateTileData(tileContent.com January 2018 63 0118msdn_SonninoUWP_v3_56-63. techniques and technologies issue of MIND (Figure 1). only to learn that the first big company in my career. The first article I wrote for were there. yes. If he could write a column for MSJ. 1998 was a memorable year. informing developers of the him was published in the June 1997 latest tools. In May my son Francesco was he had just assumed the role of technical editor at MIND. But. You’re really able to recall that? bit as sharp as the author. started by apologizing for umn called Cutting Edge in the November 1997 issue. At the time I was the epitome of the “real” your first article ever. in the October 1996 issue of MSJ. A few months they needed to get ahead in the world later in January I published what would of Windows programming. you were more painful than him. reply. doing pointer-based stuff in raw C without even the Dino: Right. but felt also that I was every Josh: Your memory is better than mine. do you remem Dobb’s Journal. on something called Active Scripting. 64 msdn magazine 0118msdn_EspositoCEdge_v3_64-66. What was it? CryptoAPI.” he wrote. I really enjoyed Programmer” in MSJ. always been fascinated by writing. I liked thin protections of the emerging C++ language. It’s because I’m busy and Dino: My first column dates back to January 1998. I especially liked the check) that I wanted to get suspicion on things like Microsoft Foundation Classes (MFC). By 1996 I was a published ber my first article in the June 1997 author. I didn’t think highly of those doing because of your dentist.indd 64 12/12/17 8:53 AM . Josh Trupin. Then. but I still hadn’t written for either issue of MIND? Microsoft magazine. working on a second article right away. And what better way to do seemed to suddenly give everybody the that. at Microsoft. going Now. its progenitors Josh and I started collaborating right Microsoft Systems Journal (MSJ) and after that. I wanted to beach-front home on the eastern coast take a moment to look back at the last of central Italy. right? programmer. In an era where e-mail two decades. I worked colleague Josh Trupin to provide some up the courage to propose technical perspective. but after having missed the last couple issues due to a new role he’d taken the first article he resigned and I needed to find a replacement. I had MSDN Magazine. It didn’t born. yet MSDN Magazine— a Digital Friendship or more accurately. Here’s our conversation. I used to look with it so much (well. “If you’ve written to me and I haven’t sent you a Giving you the column solved two problems with a single move. John Grieb had just started writing a new col- existing apps. articles to prestigious magazines like Dr. it’s not because I’m ignoring you. exactly 20 years after my first back to my high school years in a small Cutting Edge installment. and we’ve remained friends Microsoft Interactive Developer (MIND)— ever since. why Dino: Well. “visual” development. decided that I could spend my life writing and coding. But getting a response which seemed designed to shield lazy developers from the harsh from you was hard! You then told me you had been lame on replies realities of programming. Figure 1 Dino’s First Article in the Contents Page Josh Trupin: I remember you send- That all changed when I came of Microsoft Interactive Developer ing me so many e-mails that I couldn’t across a column called “The Visual just ignore you. I still have a paper copy of the magazine. In February I joined not me? So I contacted Josh to praise his work. than to rope in my old friend and chance to talk to nearly anyone. be the first of many Cutting Edge col- The idea of writing for either of these umns. The author. I was impressed with the article. Dino Esposito: Josh. initially in MIND and later in publications was at the time a dream. In September I left the last big company in my career and take me long to offer to write for him. I think it was I’m ignoring you. I read a column that Dino: That’s why you gave me the Cutting Edge column? boldly claimed to teach readers the way to add VBScript to their Josh: Not really. Josh: Really? Well. Cutting Edge DINO ESPOSITO 20 Years of Cutting Edge: A Conversation A lot has changed in the IT world since The Inception of the mid-1990s. for Windows Phone. for example. 2000 shipped. playing on the computer (Figure 2)? There’s an old copy of MIND brute-force algorithms on it. What do you see today in front of the current generation of old men of 30? Dino: Interesting question. Oops. is understanding and modeling Josh: Amazing! problems onto abstract structures. which was furiously evange- lized for a few years before being dropped. Josh: And the other desire? Dino: Joining Michael Freedman’s team at Microsoft. One is to meet Scott Guthrie in person. Dino: Well. I find it excitedly scary. One I recall is ActiveX Documents. stupid. we need to learn about problems was 12 years old. time. which were to cover. For example. He also can’t believe that there was a time when I was more popular and modeling over pure than Scott! I met Scott for the first time back in 1999 when he was unveiling an antediluvian thing called ASP+. Josh: Let’s get back to planet Earth. We were two old men of 30 back in 1998. and with some success I’d add. right? Dino: Michael Freedman is the brains behind the quantum Dino: The funny thing is that I got married when Microsoft computing effort at Microsoft. It seems to be an executive Dino: Well. the other I see the next decade as day he mentioned that he has two goals at this stage of his life. formulated back in the 18th century. Another is Silverlight. years to come? Dino: He has a math mind and loves esoteric things like neural networks and quantum computing. How is your family? You Josh: Awesome. Sure. but I wish I could go back to the early days of scripting. We have neural networks that still in there about e-mails. quantum com- puting could make affordable exponential calculations that today guarantee data privacy in crucial transactions. And what’s that. released Windows 95.com January 2018 65 0118msdn_EspositoCEdge_v3_64-66. Look at artificial intelligence (AI). Dino: You could do a lot of JavaScript today! Josh: Yeah. What was the weirdest thing you wrote about in your 20 years of columns? Dino: Well. Does he do any programming? AI in the real world. had my first son when Windows 98 was on Josh: I heard about Microsoft’s quantum computing work at the its way. You see the picture of my son Today. Have you ever realized that most of our stuff is secured by the unknown binding between a pair of lovely prime numbers? Josh: Call me romantic. I’ve been doing pair programming for quite some summary of the operational research exam when I was at college. We Josh: Does Francesco have more programs planned for the have a lot ahead of us. and we’re two old men of 50 today. Josh: Your son should be a man now. Josh: You survived. But it did manage to survive while scary three-letter acro- nyms like OLE and COM went the way of the dinosaurs. exactly? also have a daughter. I repeatedly assured people that ASP. and maybe enterprise-level Blockchain protocols in the near future. He can’t believe that a demigod the comeback of algorithms like a Microsoft vice president could really have any memory of me.indd 65 12/12/17 8:53 AM . actually. To my great surprise. I always had it around. He wrote his first mobile app when he and articles to the real world. in 20 years there have been plenty of technologies I covered that in the end were fated not to last. Microsoft is giving us wonderful tools like bots and Cognitive Services. but it seems rather futuristic to me. 20 years of technical writing is a long time. in essence. We need to learn how to build effective AI from Microsoft. to make it scale from the level of cool demos Dino: He does. but most of it is still hidden. and our daughter was born around the time that Windows Ignite conference. but even JavaScript is no longer the thing it was 20 years ago.NET themes were about to overtake CSS stylesheets in a very short time. I mean. I was actually reading that magazine cover largely rely on the principles of Bayesian statistics. Perhaps worst of all. To make Figure 2 My Dad Is Not That Good with Computers msdnmagazine. I see the next decade as the comeback of algorithms and modeling over pure technology and tools. technology and tools. the technology to edit Word and other files in a browser. which. we have big amounts of data but only run raw. architectures. over two centuries ago. He even got a free device and problem domains. or getting acquainted with. the amount of knowledge needed to be a good professional has grown unbeliev- ably. I think. • hundreds of reviews and case studies Those who start with computers today should be aware that pro- • fully-functional evaluations gramming languages are like any tool. emails with multilevel Dino: I write because I love writing. just listening to the • See dtSearch. but being quick-to-find information is not the same as learning. multicolor hit-highlighting options Today’s knowledge base is like CosmosDB compared to Microsoft Access.com/magazine/mt185569). Terabytes of Data no see” kind of thing. 1998 we’ve seen the advent of the Internet as a first-class developer platform. On the data Visit dtSearch.0 as being very exciting. Josh: Me too. even in the era of blogs and StackOverflow and Google.NET Core” dtSearch.com for front we went from plain data access to object/relational mapping (ORM) and now toward micro ORM. my Mac and Android afternoon) of 9/11. I was not watching TV. and on Monday be Over 25 search features. We saw the browser evolve from a target for simple JavaScript development into some- thing more. I guess. a new tech- nology or a framework. dtSearch’s document filters support Josh: Is this the reason why you still write articles? popular file types. Google was in beta. It also helps that I probably attachments. That was during the first half of the 2000s. n The Smart Choice for Text Retrieval® since 1991 Dino Esposito is the author of “Microsoft . but I remember the Developers: days of ASP. Dino: The e-mails we exchanged the morning (actually. Developers began writing browser-based Web apps in Silverlight. The way developers gain access to technical information has changed. advanced data Josh: What’s in store for the next 20 years of Cutting Edge? classification. databases. with easy up-to-date on the state-of-the-art of Windows technology. Dino: AI in some way.indd 66 12/12/17 8:53 AM . But it’s great to see across a desktop. Josh: What was your best article ever? Dino: I can’t recall all the articles I wrote. thanks. Esposito shares his vision of software on Twitter: @despos. MS Azure.NET. network. and then in JavaScript again.NET 2.com for articles on radio and one of your e-mails told me a couple of minutes before the radio that the towers had collapsed. web data have a knack for abstracting core facts and concepts and conveying them in compelling and useful ways. Then I left the magazine and a lot has happened since. Dino: When was the last time we met? It’s been a “long time. the rise of scalability as a problem. Java and C++ sourcing and CQRS (msdn. working with SQL. etc. No more kids Instantly Search for me. 2018).com 1-800-IT-FINDS (Microsoft Press.NET: Architecting Applications for the Enterprise” (Microsoft Press. I just disabled automatic updates. and the evolution of serious SQL and then NoSQL databases. At the same time. Cutting Edge 0118msdn_EspositoCEdge_v3_64-66. digital pho- tography was in its infancy. Josh: We didn’t meet more than two or three times. and smartphones were the stuff of science fiction. 2014) and “Programming ASP. faceted search. but you can only do a good job if you know how and where to use it. then in C#. More recently. Handling it well helps. One could spend the weekend in the office—I did it a few times—bent over a collection of MSDN CDs. Since NoSQL & other DBs. Internet or that MSDN Magazine is still alive and kicking. putting out great Intranet site with dtSearch enterprise content. Josh: What will you never forget from these 20 years of Cutting Edge? • SDKs for Windows. Pluralsight author and developer advocate at JetBrains. I loved writing about event • APIs for . but not sure which way yet. and developer products Dino: When we started the Cutting Edge column. UWP. Linux. ® Josh: So you’re on Linux now or you’re still upgrading your editions of Windows? Dino: Haha. Redmond Tomorrow’s Code! facebook.com – Search “VSLive” linkedin. and we want you to be a part of it. VISUAL STUDIO LIVE! (VSLive!™ ) is celebrating 25 years as one of the most respected.com – Join the “Visual Studio Live” group! SUPPORTED BY PRODUCED BY vslive. as we highlight how far technology has come in 25 years. Join us in 2018 for #VSLive25. Perspective. the Microsoft Platform and open source technologies in seven great cities across the US.com/vslive – @VSLive Yesterday’s Knowledge. WHICH LOCATION WILL YOU ATTEND IN 2018? MARCH 11 – 16 SEPTEMBER 17 – 20 Bally’s Hotel & Casino Renaissance Chicago Respect the Past. APRIL 30 – MAY 4 OCTOBER 7 – 11 Hyatt Regency Austin Hilton San Diego Resort Austin San Diego Code Again for Code Like It’s 2018! the First Time! JUNE 10 – 14 DECEMBER 2 – 7 Hyatt Regency Cambridge Loews Royal Pacific Resort Developing Boston Orlando Code Odyssey. CONNECT WITH US AUGUST 13 – 17 Microsoft Headquarters twitter. while looking toward the future with our unique brand of training on .NET.com magazine #VSLIVE25 Untitled-6 1 12/11/17 12:42 PM . independent developer conferences. longest-standing. HELP US CELEBRATE #VSLIVE25. Code Forward. Las Vegas Chicago Look Back to Code the Future. knowledge-share and networking at #VSLive25. intense hands-on labs and fun networking events. hear the latest from Microsoft insiders and tune up on today’s hottest training topics! Plus. unbiased. 2018 Hyatt Regency Austin. TX Austin We’re Gonna Code Like It’s 2018 Visual Studio Live! (VSLive!™) is back in Austin this spring with 5 days of practical. April 30 – May 4. VSLive! 1999 VSLive! 2017 SUPPORTED BY PRODUCED BY magazine Untitled-6 2 12/11/17 12:42 PM . insightful workshops. Come experience the education. join us for hard-hitting sessions. From April 30 – May 4. help us celebrate 25 years of coding innovation as we take a fun look back at technology and training since 1993. Developer training. Code with industry experts. 2018. com – Join the @VSLive Search “VSLive” “Visual Studio Live” group! Untitled-6 3 12/11/17 12:42 PM . 1-800-Contacts “This is my second year attending Visual Studio Live! I want to come back year over year because the variety of sessions allow me to deep dive into tech that I use on a daily basis.NET / Web Server ALM / DevOps Azure / Cloud UWP (Windows) Hands-On Labs “I have been looking forward to attending the event for some years and I was finally able to come. Washington Technology Solutions Register to code with us today! Register Now and Save $300! Use promo code VSLJAN2 CONNECT WITH US vslive.com/vslive – facebook.NET JavaScript / Angular Xamarin Software Practices Database & Analytics BACK BY POPULAR DEMAND ASP.com – linkedin. DEVELOPMENT TOPICS INCLUDE: X VS2017/. The biggest dev improvement I made last year was from the great hands-on experience I got with SignalR at VSLive!” – Jake Clauson. I am advocating for more test-driven dev and using more async as a resulting of attending the conference!” – Yessenia Figueroa. but the option is there to explore something new. I need to help keep my company current and secure.com/austinmsdn twitter. June 10 – 14. UWP and more. MA Boston Developing Perspective Visual Studio Live! (VSLive!™) returns to Boston. Cambridge. Plus.NET Core. Join us as we dig into the latest features of Visual Studio 2017. June 10-14. Code with industry experts AND Microsoft insiders while developing perspective on the Microsoft platform. Come experience the education. 2018. Angular. help us celebrate 25 years of coding innovation as we take a fun look back at technology and training since 1993. Xamarin. VSLive! 2001 VSLive! 2017 SUPPORTED BY PRODUCED BY magazine Untitled-6 4 12/11/17 12:42 PM . ASP. Developer training. with 5 days of practical. unbiased. including NEW intense hands-on labs. knowledge-share and networking at #VSLive25. 2018 Hyatt Regency. I loved the HoloLens introduction. I got so much out of the SOLID principle sessions – it gave me great perspective on the subject.com/vslive – facebook.NET / Web Server ALM / DevOps Azure / Cloud UWP (Windows) Hands-On Labs “I have attended 12+ Visual Studio Live events.NET JavaScript / Angular Xamarin Software Practices Database & Analytics NEW! ASP.com – Join the @VSLive Search “VSLive” “Visual Studio Live” group! Untitled-6 5 12/11/17 12:43 PM . Accuquote “Last year. I work for an aerospace company.com – linkedin. starting with the early days of VBITS and C# Live. 3D design. 3D inspection and many other applications in the near future!” – Mani Nazari. DEVELOPMENT TOPICS INCLUDE: VS2017/. IT Factory Automation Systems Register to code with us today! Register Now and Save $300! Use promo code VSLJAN2 CONNECT WITH US vslive.com/bostonmsdn twitter. This year. I return every year because no one reflects and enhances what is currently happening in and with Microsoft’s developer world like VSLive! I honestly trust and enjoy all the speakers I look to them as both mentors and old friends!” – John Kasarda. and I can see that the technology will be utilized for assembly. Amazon founder Our applications use duct tape internally. The same business structure applies: drivers own their cars and do the driving. the same app works almost every. It’s not doing anything conceptually that David S. Don’t Get Me Started DAVID S. Wells Fargo Wagon to deliver their orders. good squirt of WD-40 on all the joints limbers up a service that is “Where else in this process can we spray WD-40?” n pulverizing the competition. You don’t have to visit an Christmas for Sears as a going concern. where the user can’t see Jeff Bezos became the world’s richest man in late October.ly/2BjLvhz. ATM for cash. display big spray cans of WD-40 around the lab as an inspiration How has Uber reduced the friction of this process? With Uber. We should be asking ourselves. to ask ourselves. The app remembers your most frequent destinations. back their paper catalog this Christmas (cnnmon. We should be trying to to participate. the app takes care of that. the auto-save in One Note has lower friction than manual generation especially prefers this. including “Why Software Sucks” (Addison-Wesley Professional. WD-40 can York City has had radio-dispatched car services for as long as it’s had radios and cars: call 777-7777 and you get Dial 7’s car service. A lower the friction for everyone. Our apps rarely is a-flying down the street …” invent something completely new. we shouldn’t be trying to cram in dles all of that. I had to turn in song.ly/2ACLSYa). 1-Click off because I was buying too much stuff. I promised you a follow-up piece on duct tape’s polar And customers no longer have to wait a week or longer for the opposite. almost anything apart. Maybe. But the external functionality of our Music Man” song will soon need rewriting: “Oh. the service han. The night before code freeze. betting where. call 666-6666 and you get Carmel’s. You can contact him than a paper index. Amazon’s 1-Click Order button is much easier at rollthunder. holding a town parade ing lubricant WD-40 (wd40. 1-Click ordering expired last fall (see bit. 2002). I’m betting it was the last a strange city.ie/2zCHS62). lowering the friction nearly to zero. The automatic disk backup of Carbonite has much needs to hire. This confluence is celebrated retail process. Microsoft named Sears. You’ll find them nestled next to each other Amazon has dumped a barrel of WD-40 into all aspects of the in almost every toolbox in the world. spoof at bit. in vice handles marketing. New anything together. just the smartphone she probably already carries.com. we should exist in many other cities. Now consider Amazon. as they did in “The Music Man” (straight version As duct tape can stick almost anything together. as WD-40 reduces the friction of mechanical parts.com).com/magazine/ than filling out and snailing a paper order form with a paper check. WD-40 can get at bit. brought service in each city you visit. Amazon’s patent on written.NET” (Microsoft Press. The driver doesn’t need an expensive radio console one more feature for our few power users. so I expect to see offering them at a single tap. What we usually do is reduce the friction of existing operations. “The it—lots and lots of duct tape. 2006) and “Introducing Microsoft . Platt teaches programming . PLATT WD-40 In my November 2017 column about duct tape (msdn. when it arrives.indd 72 12/12/17 9:00 AM . the much-maligned but much-much-used ride hailing service. mt845623). You don’t have to describe or even know your location in that nostalgia could bring back buyers. the Amazon drone most successful software owes more to WD-40.ly/2jq9YdC). Sears. the central ser. “How can we lower friction even more?” For you summon a ride without talking to a live person. and its application to software.ly/2AaVng8. As duct tape can stick almost Consider Uber.ly/2hW4IOy and bit. Herewith my ruminations on the all-purpose penetrat. booking and payment. He’s the author of 11 programming ago. but Amazon is drastically lowering friction and hammering books. or even take out your credit card. on the other hand. get almost anything apart. You don’t need to find a new car many companies start using it. 72 msdn magazine 0118msdn_PlattDGMS_v3_72. Amazon’s Web site is easier to distribute and update than him a Software Legend in 2002. see bit. The younger example. and it’s one less body Uber saving in Word. Items are easier to find with a search box of his daughter’s fingers so she learns how to count in octal.NET at Harvard University Extension Sears didn’t do with their mail-order operation a hundred years School and at companies all over the world. Uber isn’t doing anything conceptually new. He wonders whether he should tape down two the Sears paper catalog. Similar operations addition to posters displaying our target user personas. We should use more WD-40 in designing software. lowering costs permanently once you get the code lower friction than backing up data yourself. distribution licenses. and Wijmo lines. All rights reserved. Spread. Build better applications. ActiveReports. Inc. Our team is your team. | Developer Solutions Empower your development. the promo code should be applied in the cart at checkout. designers. Not to be combined with other offers. and architects with the ultimate collection of easy-to-use tools for building sleek. high-performing. Other restrictions may apply. feature-complete applications. . Offer excludes ActiveReports Server. Untitled-1 1 12/12/17 11:29 AM . To take advantage of the offer. and add-on support/maintenance. * Offer applies to products in ComponentOne.com © 2018 GrapeCity. GrapeCity’s family of products provides developers.NET UI CONTROLS REPORTING SOLUTIONS SPREADSHEET SOLUTIONS JAVASCRIPT UI CONTROLS For more information: 1-800-831-9006 Learn more and get free 30-day trials at GrapeCity. we understand your needs and offer the industry’s best support. With over 25 years of experience. volume discount packs. All other product and brand names are trademarks and/or registered trademarks of their respective holders. Design. desktop and mobile development. With Indigo Studio Develop Automate and accelerate your development with powerful UI controls for web. Faster Paths to Amazing Experiences Prototype Get it right the first time. With ReportPlus Embedded For a free trial or demo.231.800. prototype and test usability remotely.com To speak with our sales team or a solutions consultant call 1. visit Infragistics.8588 Untitled-1 1 12/13/17 10:51 AM . With Infragistics Ultimate Drive Insights Make your apps shine with affordable and powerful integrated analytics.