<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dan Cokely on Medium]]></title>
        <description><![CDATA[Stories by Dan Cokely on Medium]]></description>
        <link>https://medium.com/@dan.cokely?source=rss-7d1b09a82e42------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OO8wdyPu_uBfyhzt</url>
            <title>Stories by Dan Cokely on Medium</title>
            <link>https://medium.com/@dan.cokely?source=rss-7d1b09a82e42------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:02:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dan.cokely/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[More ADLS Gen2 API with C#]]></title>
            <link>https://medium.com/@dan.cokely/more-adls-gen2-api-with-c-f1f3e9438be4?source=rss-7d1b09a82e42------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1f3e9438be4</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[azure-storage]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-data-lake]]></category>
            <dc:creator><![CDATA[Dan Cokely]]></dc:creator>
            <pubDate>Fri, 03 Jan 2020 03:06:13 GMT</pubDate>
            <atom:updated>2020-01-09T02:19:59.954Z</atom:updated>
            <content:encoded><![CDATA[<h3>ADLS Gen2 API with C#</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fWo_yVjZ_p5HJ6nO" /><figcaption>Photo by <a href="https://unsplash.com/@paul_?utm_source=medium&amp;utm_medium=referral">Paul Hanaoka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Intro</h4><p>In a previous article (<a href="https://medium.com/@dan.cokely/using-the-azure-data-lake-storage-gen2-adls-gen2-api-with-c-ea7506a7fca5">here</a>) I looked into the basics of Azure Data Lake Storage Gen2 (ADLS Gen2), setup a storage account, and looked at some basic auth calls to interact with the ADLS Gen2 API. Given the ability to create a storage account and authenticate calls against the ADLS API, it only makes sense to show some basic CRUD style calls to dig a bit deeper into the API. This article will walk through some basic operations (using C#) to expand on the work started in the previous one. Full API documentation on the ADLS Gen2 API can be found from MSFT <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/data-lake-storage-gen2">here.</a></p><h4>Setup</h4><p>First and foremost make sure you have a storage account with hierarchical storage enabled.</p><p>The examples below were done as part of a C# console app (.NET Core 3.0), using Visual Studio Community Edition, Version 16.4.1. The only NuGet package I installed was Microsoft.Azure.Services.AppAuthentication which allows the generation of a JWT Bearer token using Visual Studio credentials when developing locally, and MSI when deployed. This makes it very easy to authorize our API calls. Ill be looking at each method individually, but the full class can be found <a href="https://gist.github.com/dcokely7/236ec4ada8f785ba0d0fcace086b0023#file-adlsexample-cs">here</a>.</p><p>One last note, these methods are only a demonstration of using the API from C#, many production quality conventions (DI, try/catch, logging, etc.) have been omitted for brevity. That said, lets dig in.</p><h4>Authorization</h4><p>This method will look familiar from the last article, you will need the tenant id of the tenant in which the ADLS account is located. If you are running from Visual Studio, the library will pull your credentials from VS to authenticate with Azure services. This method will get called by all other methods to provide the bearer token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95a5cd190f347a8036b4b80513366e28/href">https://medium.com/media/95a5cd190f347a8036b4b80513366e28/href</a></iframe><h4>Create a Filesystem</h4><p>Before creating a new filesystem we’ll need a few values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ff292c2de994ddb0a1095852df97a9e/href">https://medium.com/media/3ff292c2de994ddb0a1095852df97a9e/href</a></iframe><p>The _adlsStorage variable is the storage account name I created in Azure (in my case dcstoragetest02), _adlsSuffix is universal, so no need to modify that, and finally _rootFileSystem is the name of whatever you want your filesystem to be called (every example here is based on the same filesystem “dansfilesystem2”, but you can setup however you like).</p><p>Creating a new filesystem is a PUT call against the storage account, with the values defined above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2df81f7a700945a911fda14a20a128bb/href">https://medium.com/media/2df81f7a700945a911fda14a20a128bb/href</a></iframe><h4>Uploading a file</h4><p>This upload example takes place in 3 parts, first a PUT with the filesystem name, directory path (in my examples the directory is simply ‘testpath’), and file name as the URL. Once that call returns success, we open a stream and provide that as the content to a PATCH call with the same path. This second call adds the parameter ‘action=append’ and the starting position 0. The final call is another PATCH with ‘action=flush’ to persist the file to the filesystem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe37d03a116cd78d8d72425daa74caf/href">https://medium.com/media/3fe37d03a116cd78d8d72425daa74caf/href</a></iframe><h4>File and Directory Info</h4><p>Now with the ability to create files and filesystems, lets looks at some simple ways to get metadata back. The first call is a way to enumerate a directory, and using the ‘recursive’ parameter it can crawl the hierarchy starting at the depth given.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a66ae95574dc2cee78bc54b776dd8e43/href">https://medium.com/media/a66ae95574dc2cee78bc54b776dd8e43/href</a></iframe><p>As an example, I have 2 files in the filesystem ‘dansfilesystem2’ under the directory ‘testpath’. In this case, if I pass in ‘testpath’ as the directory path, and set recursive to ‘true’, it will return the 2 files under that directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVuB827js_uCLejIf5WFew.png" /></figure><p>Next we’ll look at individual file info, by making a HEAD call to the file path (full path including the filesystem and any directories). The metadata is returned in the Headers of the response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0250a6f782cd3fc9bf46d8cd239123ae/href">https://medium.com/media/0250a6f782cd3fc9bf46d8cd239123ae/href</a></iframe><p>Notice reading the response Content yields nothing of real value, its all in the Headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*XVP8frb2Rzki3FOTAs8Yvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*gJ5X4HU13EF_Wy-SHUsuOQ.png" /></figure><h4>Downloading a file</h4><p>Download is straightforward, simply provide the path to download, and read the response. This example reads the entire file, but you can grab pieces using range requests as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62292b2a61cdba70a6e8e77ca8ff850/href">https://medium.com/media/e62292b2a61cdba70a6e8e77ca8ff850/href</a></iframe><h4>Deleting a file</h4><p>Lastly, lets delete a file, again a straightforward operation, send DELETE with the full path to the file… and its gone!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ffd5502a12efb2d15f50feb0b3778c6/href">https://medium.com/media/7ffd5502a12efb2d15f50feb0b3778c6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0slEjTE4a0rUyxuAac3kQ.png" /></figure><h4>Wrap up</h4><p>While the API has some quirks and strangeness, overall its fairly straightforward to use. Hopefully these examples can help jumpstart your next project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1f3e9438be4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Azure Data Lake Storage Gen2 (ADLS Gen2) API with C#]]></title>
            <link>https://medium.com/@dan.cokely/using-the-azure-data-lake-storage-gen2-adls-gen2-api-with-c-ea7506a7fca5?source=rss-7d1b09a82e42------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea7506a7fca5</guid>
            <category><![CDATA[azure-data-lake]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[blob-storage]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[adls-gen2]]></category>
            <dc:creator><![CDATA[Dan Cokely]]></dc:creator>
            <pubDate>Fri, 30 Aug 2019 21:49:18 GMT</pubDate>
            <atom:updated>2020-01-03T03:17:25.833Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DAgQ4lX_4xTRQi_H" /><figcaption>Photo by <a href="https://unsplash.com/@echaparro?utm_source=medium&amp;utm_medium=referral">Edgar Chaparro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Update 1/2/2020</p><ul><li>I’ve added a second part to this story, diving into some basic CRUD operations, published <a href="https://medium.com/@dan.cokely/more-adls-gen2-api-with-c-f1f3e9438be4">here</a></li></ul><h3>Intro</h3><p>Azure Data Lake Storage Gen2 is an interesting capability in Azure, by name, it started life as its own product (Azure Data Lake Store) which was an independent hierarchical storage platform, mainly focused on providing a storage backing for big data platforms such as HDInsight through a WebHDFS compatible API. Azure Data Lake Storage Gen2 (ADLS Gen2) takes the key advantage of the original ADLS, the hierarchical storage structure, and applies it to the ubiquitous Blob Storage. The merging of these two technologies has become ADLS Gen2 (docs <a href="https://docs.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction">here</a>). The value prop is the scale, performance, and security of hierarchical storage, combined with the cost effectiveness, tiering, and prevalence of Blob Storage. Big data platforms like Databricks, Hadoop, HDInsight, Hortonworks, and others can be mounted, connected, integrated, or are otherwise supported by ADLS Gen2. While using ADLS Gen2 as a backing for a big data platform is a point and click operation (or simple scripts etc.), connecting and leveraging ADLS Gen2 in a custom application through its API can be a bit trickier to get set up and running.</p><h3>Demo</h3><p>The API for ADLS Gen2 has all the standard commands you would expect to find to manage a hierarchical file system: CRUD, properties, metadata, directories, paths etc. (<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/data-lake-storage-gen2">docs here</a>). Microsoft’s docs say to use the Shared Key authorization for API calls, which isn’t a common form of authorization to use, so we’ll dig into setting it up correctly, as well as look at a library alternative that works just as well (probably better… and is easier to use).</p><p>We’ll use Visual Studio 2019 Community (16.1.1) and make a simple console app that can generate a token and create a basic filesystem through the ADLS Gen2 API, first with Shared Key authorization, then with the Microsoft.Azure.Services.AppAuthentication Nuget package.</p><h3>The ADLS Gen2 Instance</h3><p>First we need to create our storage instance, we’ll create it from the Azure Portal. We start off creating a standard Azure Storage Account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*oyz-N26qShRV7eAFJCmlgg.png" /></figure><p>Fill out the name, resource group, location, and other basic metadata however you like, keeping in mind ADLS Gen2 requires standard performance tier, and either Storage V2 or Blob account kind (as of writing):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*_lfn17lz1Ri-GcnGKNtQEw.png" /></figure><p>Im enabling the secure transfer option (essentially forcing https for all connections), and the setting that makes this ADLS Gen 2, “Hierarchical namespace”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*wo1MGrBs8e3Qy0H-sb6NBg.png" /></figure><p>Lastly Azure will make sure all the setting are valid, then we can create the account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*VIBhf9-toS-MMY1mYFYX0g.png" /></figure><p>Once the storage account creation is completed, we will need the access keys in order to use the Shared Key approach. “key1” (the key itself, not the connection string) will be the one we will use later on, so make note of where to find it once we need to use it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9bkXVeO3ZtW97dGHhB2ew.png" /></figure><p>Lastly, lets double check that the hierarchical section of the account shows up, you should see the Data Lake Storage section, but no file systems yet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkNsL02p9OKZc7_5lW57gA.png" /></figure><h3>The Shared Key</h3><p>The ADLS Gen2 documentation references using the Shared Key approach as the authorization mechanism when accessing the API(docs on Shared Key <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key">here</a>). While this is not the only access mechanism that works, since its the only way referenced in the documentation (for now) we’ll start by implementing Shared Key (Full disclosure, I think the second method we’ll look at is far more useful).</p><p>The Shared Key is a keyed digest, where the parameters of the request are hashed along with the storage account key, and the result is base64 encoded and attached as the authorization header. The receiving side (Azure) will then take all the parameters of the request, and hash them along with the same storage account key to make sure the request was not altered, and that a valid storage account key was used.</p><p>The parameters of our request are concatenated into the string to be signed with the storage account key, so using the MSFT docs as a guide, we’ll create the following helper program to generate keys, note the below method is essentially hardcoded to only create a key for the create file system operation, but could easily be adapted to generate keys for other operations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/338b3c7f8952bd219475177ac831e93f/href">https://medium.com/media/338b3c7f8952bd219475177ac831e93f/href</a></iframe><p>Notice how most of the parameters are not required, the required pieces are the HTTP Verb (PUT), CanonicalizedHeaders, and CanonicalizedResource. The CanonicalizedHeaders for us are simply the x-ms-date (in GMT) and x-ms-version (2018–11–09) headers concatenated together with newlines (full format and options are detailed in the docs linked at the beginning of this section, or <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key">here again</a>). The CanonicalizedResource header is a standardized way to represent the path to a resource and can include additional parameters about the resource. Since we will only be at the file system depth, the header is pretty straightforward. The resource header becomes more complicated as the depth and resource being request changes, but for now its simple since the file system is the highest level of resource. We take all these pieces along with the storage key pointed out in the earlier section, and produce the Shared Key.</p><p>Once we run the program, we can take the output (the Shared Key) and all the other parameters and plug them into a REST client of choice (im using Insomnia) to actually create a file system. We need the path to the hierarchical API (*.dfs.core.windows.net), the rest of the parameters come from the values used in the above code used to create the key (this makes sense, because Azure will be validating the parameters in our call against the key we send, so they should match). Plugging all of this in gives us the request we are going to send (left side), and once we send it, we should get a valid response, in this case a 201 (right side).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIZV14qwdVjGE1qMEv5g8g.png" /></figure><p>Now if we go back into the Azure Portal, our new dansfilesystem exists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLpRbqZKNi58-f55o9agCQ.png" /></figure><h3>The Library</h3><p>The Shared Key is fairly generic and can be used in most scenarios where you need to programmatically access the API. However, it can be cumbersome to need to build the strings and pass all the parameters required for each call every time. It would be a lot easier if we could simply generate a token independent of all the call parameters. As it turns out, we can use the Nuget package Microsoft.Azure.Services.AppAuthentication to do just that! The library will use your local developer credentials, either through the account you’re logged into Visual Studio with, or an active AZ login session (docs <a href="https://docs.microsoft.com/en-us/azure/key-vault/service-to-service-authentication">here</a>). Even better, once the code is deployed to Azure it will use a managed identity (see more on managed identities for Azure Resources <a href="https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview">here</a>) to authenticate, so no other config (other than enabling managed identity on the resource) is required.</p><p>The first step is to verify that Visual Studio is using the correct identity when its running the program (it will need to be an account that has some type of access to the resource being requested, in this case storage). Under “Tools” -&gt; “Options) you will find the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*7XH5u9Zgw2mIRC1JCZp6Sg.png" /></figure><p>Make sure the account listed in the dropdown has access to the storage account.</p><p>This time our method to generate the file system is much simper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f70de993fa96ace5b0de97ab4dfd9eb/href">https://medium.com/media/8f70de993fa96ace5b0de97ab4dfd9eb/href</a></iframe><p>Finally, running the above code and going back to the portal, we will again see our new dansfilesystem created.</p><h3>Next steps</h3><p>Now that a file system exists and we have multiple ways to add authorization to our API requests, we can begin creating directories, files, etc.</p><p>I’ll be following up with another article soon diving into those file and directory operations to put the authorization header to work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea7506a7fca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating NuGet packages in Azure DevOps with Azure Pipelines and YAML]]></title>
            <link>https://medium.com/@dan.cokely/creating-nuget-packages-in-azure-devops-with-azure-pipelines-and-yaml-d6fa30f0f15e?source=rss-7d1b09a82e42------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6fa30f0f15e</guid>
            <category><![CDATA[nuget]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[azure-pipelines]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[yaml]]></category>
            <dc:creator><![CDATA[Dan Cokely]]></dc:creator>
            <pubDate>Wed, 29 May 2019 03:00:01 GMT</pubDate>
            <atom:updated>2019-05-29T03:07:11.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CiAOL_KTuuDXgtOF" /><figcaption>Photo by <a href="https://unsplash.com/@waldemarbrandt67w?utm_source=medium&amp;utm_medium=referral">Waldemar Brandt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro to Azure DevOps</h3><p>Azure DevOps is Microsoft’s cloud CI/CD platform covering repos, build and release pipelines, work tracking, artifact feeds, testing, and many more features (<a href="https://docs.microsoft.com/en-us/azure/devops/user-guide/what-is-azure-devops?view=azure-devops">full docs here</a>). It&#39;s a very actively developed platform, and as such, sometimes functionality evolves as you’re using it. A great example is the CI portion of Azure DevOps, aka build pipelines. What initially started as a wysiwyg set of choosable build tasks has quickly moved into a YAML based end-to-end pipeline definition where the pipeline code can live directly in your project repo. Even better, the pre-canned tasks are still available as templates and produce YAML directly into your pipeline file. Currently in preview is the ability to support multi-stage build pipelines; meaning you can build, test, and deploy to lifecycle environments all from one pipeline definition. This article will outline the basics of setting up an Azure Pipeline in YAML for creating a custom NuGet package from a .NET Standard project, and publishing it to a private feed where it can be consumed by other projects. We’ll first go over some basics of NuGet, then start on building our NuGet package.</p><h3>NuGet</h3><p>The easiest description is nuget.org’s own: “NuGet is the package manager for .NET”. You would be hard pressed to find a .NET (full or Core) project that doesn&#39;t utilize NuGet packages, they are the standard packaging format for the .NET platform. They are zip files with a manifest of metadata, and some set of data, typically dlls, but can have symbols, config files, or anything really (its just not a normal convention), saved as .nupkg files. A great deeper dive on the spec can be found on the MSFT docs site<a href="https://docs.microsoft.com/en-us/nuget/reference/nuspec"> here</a>, or you can get the current xsd from the NuGet repo <a href="https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Core/NuGet.Packaging/compiler/resources/nuspec.xsd">here.</a> The manifest (the .nuspec file) has basic metadata such as the id, version, authors, and other basic descriptive metadata, as well as any dependencies the package requires. This is an important point: say you have written a great library for your company to use, it has a collection of Azure utilities, and custom JSON handling. Chances are, this project is going to pull in multiple external packages (Newtonsoft, Azure/MSFT libraries etc.). In order for someone to consume your library, they will need all the dependencies your library references. By adding these references as dependencies in your .nuspec file, they can be automatically pulled down anytime someone installs your package. Building and publishing your own NuGet packages for a project can be very advantageous, even if they are only privately available to your organization. Common cross cutting libraries can be standardized and reused across projects, apps, teams, etc. and versioning can be handled in a more manageable way than 20 copies of a dll, or worse yet, a copy and pasted around shared codebase. The good news is that creating and publishing a custom NuGet package using a .Net Core or .Net Standard library and Azure DevOps is fairly straightforward.</p><h3>Demo</h3><p>This demo will walk through creating a .NET Standard library, then creating a CI/CD pipeline in Azure DevOps for the project, which will build and publish a NuGet package for consumption by other projects. We’ll be using the YAML style pipeline definition.</p><h4>Prerequisites</h4><p>This demo assumes you have an active Azure DevOps organization, if you dont, its free to create one (with some usage caveats) and you can get started <a href="http://dev.azure.com/">here</a>. I’m using VS Community 2019 (16.1.1) for the code development. Working knowledge of git/version control is assumed.</p><h4>Setup</h4><p>We are going to start by creating a repo in which the library will reside. In order to make things simple I’ll create a new Azure DevOps project which will automatically get a repo. Log into your Azure DevOps org and from the home page select “Create Project”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*ctyzY-hmVixIb8dqgOl6gA.png" /></figure><p>Next fill out some basic project info:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*MtZOsdaK293Fc0djPnwBEw.png" /></figure><p>Next either clone the default repo created with the project, or create a new repo under the project (I suggest you don&#39;t put spaces in the project name otherwise the default repo will have spaces and the whole %20 thing can get ugly, or create a new repo without spaces), and clone it locally. If you’re working from within Visual Studio you can simply connect to the Azure DevOps instance under the “Team Explorer” tab and select the repo, then create a new project within it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*1KzbnG03x7tYH1af-25pcg.png" /></figure><p>The new project is going to be a .NET Standard Class Library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*8Z1uAoo_Z3H0pATOuVvISA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*9g8Sho2ab_jLcuzhZYgSmQ.png" /></figure><p>The code is going to be very simple, there will be one class, CommonUtils.cs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/453b967d2e0854ac57b885544c4154fb/href">https://medium.com/media/453b967d2e0854ac57b885544c4154fb/href</a></iframe><p>Next we need to edit the csproj file. When we create the NuGet package, we are going to be using the ‘dotnet pack’ command. This is slightly different from the traditional NuGet CLI where you create a nuspec file and run ‘nuget pack’ against the nuspec. The ‘dotnet pack’ command will create a nuspec file from the csproj, and then package the code into a nupkg file. There are a few key pieces of information that will need to be added to the csproj file to ensure it can create the NuGet package correctly. First we need a PackageId, this will be the name of the NuGet package itself. Depending on where you’re going to publish it, this will need to be globally unique as it can&#39;t conflict with existing public (nuget.org) packages. Next is the Version, which will be the published package version number. There are entire articles on just how to version packages, but in general a safe bet is to follow semantic versioning (<a href="https://semver.org/">read more here</a>), so for now we’ll statically set the package version to 1.0.1, and if we need to push a new version, we’ll increment the version manually in the csproj file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1a9397877f9bca92b17d2e48e6d4dee/href">https://medium.com/media/a1a9397877f9bca92b17d2e48e6d4dee/href</a></iframe><p>The last important part is the YAML pipeline definition, the code of the pipeline below has been commented to give an idea of what&#39;s happening at each point. Name the file azure-pipelines.yml and put it in the root of the repo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0515c019f98b57bd6d4bd9dff0bc5de/href">https://medium.com/media/a0515c019f98b57bd6d4bd9dff0bc5de/href</a></iframe><p>This yaml schema can get fairly complicated, for a more complete definition check out <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&amp;tabs=schema">here</a>.</p><p>At this point the project will look something like the following on disk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*cN7nrlfKrAKF2cIQTpQYoA.png" /></figure><p>Inside the CommonLib folder is our CommonUtils.cs and CommonLib.csproj files.</p><p>There is one last step before pushing our code to the remote and trying to see if we can publish our NuGet package to a feed, and that&#39;s the feed itself. We are going to create a feed within Azure DevOps, this way we can keep our packages private to just our Azure DevOps organization and easily integrate with our repo and pipeline.</p><p>First log into Azure DevOps and go to the ‘Artifacts’ section. Since we don&#39;t have any exiting feeds, we need to create a new one, select ‘New Feed’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQAfFMaTfY7kzxQWYa5h2Q.png" /></figure><p>Next you have the option to set the visibility of the packages, as well as the option to have this feed pull through packages from public repos. This is useful because if you have your development and build environments point to this feed, you are able to find any publicly available package as well as your privately published ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*--J2UZSOCmqB9-FdJ9N2HA.png" /></figure><p>Finally we can commit and push all our code, for simplicity I added a .gitignore so all the lib and obj and .vs stuff can be filtered out. Notice as soon as you push and go to the Pipeline section of Azure DevOps, you should see a build definition, which should be in the process of being run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gj00Ip12fSaqqcH_C-YPaw.png" /><figcaption>Look for a build in progress</figcaption></figure><p>Sometimes the first run after the build YAML has been added doesnt kick off, if you don’t see a build in progress, hit “Queue”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JTaUUbFZKgQ3-mQuHydLA.png" /></figure><p>If you click into a build, you can see the steps of the pipeline being run, as well as a tail of the job itself. All steps should complete successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-V6auLCzJ6oAMeuA9gcFpw.png" /></figure><p>Finally with the build succeeded, our new package should be available in the “Artifacts” tab, under our newly created Feed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bd3MsgNPBCrVzuDwS0aVcQ.png" /></figure><p>Notice the Dan.CommonLib version 1.0.1 is now available!</p><h3>Wrap Up</h3><p>With the package now available, you can point Visual Studio to the feed, and download the newly published package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0rEGzri3kJ8cW3X0Rdq5A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6fa30f0f15e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Durable Functions Part 2]]></title>
            <link>https://medium.com/@dan.cokely/azure-durable-functions-part-2-e6053b50eaaa?source=rss-7d1b09a82e42------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6053b50eaaa</guid>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[durable-functions]]></category>
            <dc:creator><![CDATA[Dan Cokely]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 00:43:36 GMT</pubDate>
            <atom:updated>2019-03-15T00:43:36.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tvFRPYsAPmgEghJe" /><figcaption>“empty arranged theater” by <a href="https://unsplash.com/@rgrzybowski?utm_source=medium&amp;utm_medium=referral">Radek Grzybowski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is an extension of a <a href="https://medium.com/@dan.cokely/azure-durable-functions-part-1-intro-f99ed8fb7b45">previous article</a> where I looked at the basics of Durable Functions, themselves an extension to Azure Functions and part of Microsoft&#39;s serverless offerings. We’ll be building on the basics, and assume some basic Azure Functions knowledge (documentation <a href="https://docs.microsoft.com/en-us/azure/azure-functions/">here</a>). The Durable Functions documentation can be found<a href="https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-overview"> here</a>.</p><h4>The Problem</h4><p>Azure Functions allow developers to easily spin out new functionality without needing to worry about provisioning infrastructure, or building out large complex frameworks. Using triggers and bindings such as HTTP, storage, Service Bus, and <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings">many more</a>, you can quickly integrate Functions into existing workflows or build out new workflows with minimal integration and coding. This is great when Functions operate as one-off processes, or in small, isolated, or loosely coupled scenarios.</p><p>However, what happens when you have multiple Functions chained together, where each is dependent on the output of the previous? How about when you need to do work across multiple Functions as a single transaction, where if one Function fails, subsequent Functions process differently, or maybe you have to undo previous work to maintain a consistent system? In these cases, you need some kind of state that is maintained between steps (Functions), and some form of orchestration. This need for a persistent process state and orchestration isn&#39;t just restricted to failure scenarios, most complex systems will have more than one forward path even for simple workflows. Think of how Functions could mirror business workflows, with each Function performing one step in the process. There is also the case of long running or non-deterministic jobs, where the Functions could potentially run for hours. Keeping state in all these different scenarios will require some kind of persistent store, shared context, complex messaging capability, or all the above.</p><p>The need to handle coordination, retrying, logging, concurrency, etc. falls to the developer when using standard Azure Functions. Often some kind of persistent store such as Cosmos, SQL, or even Blob Storage will fill the roll of storing a document or record for the jobs that are processing, along with any interim state. This works great, but it requires you to provide access to all the participating Functions, as well as handle concurrent access, rollback, schemas etc. etc. You will also need to manage the calling of the Functions in the correct order, via a queue or similar.</p><h4>Why Durable Functions are useful</h4><p>The key to Durable Functions is the Orchestrator, this is a special type of Function that will be, as the name suggests, the orchestrator for a workflow. The Orchestrator Function is responsible for coordinating the Activity Functions (aka the individual worker Functions performing an individual task), and applying a particular pattern for distributing the work (Fan-Out, Chaining, Async/start and wait, etc.). The Orchestrator will also handle errors and retries. Through the Orchestrator you can easily pass state information to each Activity Function, as well as get state and progress information back, without requiring manually passing messages on a queue, using Cosmos or similar. The Orchestrator also has the ability to rebuild its execution state (more on this later).</p><p>The last Function type used in the Durable Functions framework is the Client Function, which can be triggered however you like, and contains a binding to start the Orchestrator Function.</p><h4>Demo</h4><p>In order to better see the uses of Durable Functions, I’ll walk through a demo to show the following functionality:</p><ul><li>An HTTP triggered Client Function to kick off an Orchestrator</li><li>An Orchestrator using Function chaining to call three Activity Functions (we cheat a little on the chaining part because we pass the same object into and out of each Function, but it still counts)</li><li>The ability to pass state between the Orchestrator and Activity Functions without needing to explicitly wire up a Service Bus or Cosmos</li><li>Demonstrate how the Orchestrator will replay calls when long running or async calls to an Activity Function occur.</li></ul><p>You can skip to the code walkthrough section if you dont need to see the project setup.</p><p>Create a new project in VS (im using VS 2017 Community 15.9.4):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnuAMWW68IBFTwOmCaKl3g.png" /><figcaption>Create a new Azure Functions Project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*iDoeivbftczNeXS-Ca5HQQ.png" /><figcaption>Select Azure Functions V2 (.NET Core) and we’ll start with an Empty Project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xJM9MZjDcc-OXiwNIGgFw.png" /><figcaption>Once the new project is scaffolded, right click the project, and select Add -&gt; New Azure Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zPO2QDGqe_1CYZpOmSceA.png" /><figcaption>Choose Azure Function and name it something accordingly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*4_GjToGaz4PgKXtvOpbHUA.png" /><figcaption>The type will be Durable Functions Orchestration</figcaption></figure><h4>Code Walkthrough</h4><p>Now that we have a working Durable Functions project, i&#39;m going to add the following class with all the Functions required for the Demo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32660f50ace6b015c6f252e88abfaedc/href">https://medium.com/media/32660f50ace6b015c6f252e88abfaedc/href</a></iframe><p>I’ll skip over the basics of triggering the Orchestrator via the Client (available <a href="https://medium.com/@dan.cokely/azure-durable-functions-part-1-intro-f99ed8fb7b45">here</a> if you want a more detailed look), and instead focus on how history and state are persisted throughout the Orchestrator lifetime. In order to illustrate this, I have created a workflow that consists of an Orchestrator calling three separate Functions that will each perform some basic task, with the overall state being held in our fake job record, JobState.cs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/907f79735b7032e4ad70593aeedc235f/href">https://medium.com/media/907f79735b7032e4ad70593aeedc235f/href</a></iframe><p>So to recap, the orchestrator will create an instance of JobState, then call the three individual Activity Functions, with each one adding some data to the JobState. This will allow us to see both how the Durable Function framework handles replay and state, as well as how to easily pass data between otherwise async isolated processes without needing to explicitly wire up anything.</p><p>The best way to illustrate the flow and replay functionality is through debugging. We’ll start with the Orchestrator, it will create an instance of JobState with the initial values (null, null, and false).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*GcHhCuN0tL69ZyWIAaX3jA.png" /></figure><p>The next step is to call the first Function “ProcessPart1”. Notice how the Function accepts an input of JobState from the Orchestrator, triggered as an ActivityTrigger. Each Function will only modify a small part of the job record.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/517779eaeb08584329684463e6118c76/href">https://medium.com/media/517779eaeb08584329684463e6118c76/href</a></iframe><p>The Function ProcessPart1 simply sets the RequiresEmail in our job to true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*ToDwfqkhAevu8X_T1h9zmA.png" /></figure><p>Notice when the Function ProcessPart1 returns, control is returned to the Orchestrator, but it does not continue immediately from the last call, instead it will start over and replay from the beginning of the Function, checking a history table to see if there has already been an output value from each call, and if a value exists it will load that data instead of calling the replayed Function again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*Gx9mCiXfSwQljgeEh_MG4A.png" /></figure><p>Starting with the initialization of job, we can see it holds the default values from its creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*JbDLeSBCE8CZ0NfhDbirCw.png" /></figure><p>The Orchestrator will now move on to the call to ProcessPart1, notice it continues execution past the call without falling into a breakpoint within the ProcessPart1 Function. However if we hover over the job record, we see that it holds the RequiresEmail flag that was set by ProcessPart1, without needing to execute ProcessPart1 again. This is the Durable Function framework at work, it stores an execution history, allowing the Orchestrator to essentially “sleep” between invocations of long running async jobs, then wake up, start from the top, reload context, and move on to the next step in the process. In order for this process to work, the framework employs a pattern known as Event Sourcing, where the state of a process consists of a series of individual pieces of data, which are appended into a replayable set of steps to recreate the object at any point in the process (this is paraphrased and simplified, but there are some great in-depth explanations, like <a href="https://martinfowler.com/eaaDev/EventSourcing.html">here</a>). The Orchestrator is checking a history account that is maintained by the Durable Function framework, transparent to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*XWx4o5H_tZ5R_DfTG-K2Dg.png" /></figure><p>The Orchestrator will now call into ProcessPart2. Similar to ProcessPart1 this Function modifies the job record, this time by setting the BlobPath to the string “somethingDeterministic”. This is an important point, because the Orchestrator relies on storing the output of invocations as it processes, therefore the calls should be deterministic, since the framework assumes the calls would result in the same response as it replays.</p><p>The process of the Orchestrator calling the Activity Functions, then rebuilding its progress will continue as it calls ProcessPart3, now loading the data from the calls to ProcessPart1 and ProcessPart2 out of history.</p><p>And thats it! The execution has completed, and we have our final job object fully populated from the Activity Functions.</p><h4>Wrap Up</h4><p>One final piece to note is that we were passing the JobState job both into the Activity Functions as well as returning JobState back to the Orchestrator. This was to help show how we can easily send shared state back and forth between the various Functions and the Orchestrator, but there is no requirement that the input and output match. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6053b50eaaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET Core API with EF Core and Cosmos]]></title>
            <link>https://medium.com/@dan.cokely/net-core-api-with-ef-core-and-cosmos-f6157945b617?source=rss-7d1b09a82e42------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6157945b617</guid>
            <category><![CDATA[cosmosdb]]></category>
            <category><![CDATA[cosmos]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dan Cokely]]></dc:creator>
            <pubDate>Tue, 20 Nov 2018 04:39:32 GMT</pubDate>
            <atom:updated>2018-11-20T04:49:08.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F6oUTtVfUw5c77ZW" /><figcaption>“multicolored abstract painting” by <a href="https://unsplash.com/@joelfilip?utm_source=medium&amp;utm_medium=referral">Joel Filipe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Intro</h4><p>In a previous article, I walked through how the preview Cosmos Provider for EF Core could be used to read and write basic documents to and from your Cosmos instance (you can read it<a href="https://medium.com/@dan.cokely/entity-framework-core-with-cosmos-25caa7256326"> here</a>). While it shows EF Core with Cosmos works at a basic level, it doesn&#39;t really leave you with a usable setup. This article will expand on that original experiment and build out a .NET Core API that will use EF Core with the Cosmos Provider, to give a bit more realistic idea of how it could be used.</p><h4>Setup</h4><p>We are going to re-use the same Cosmos instance as before, so we can take the URI and Primary Key and copy those to use later (If you used an older preview of the Cosmos Provider, you may have an old auto-generated “Unicorn” Collection that was created, sadly they have updated the Cosmos Provider to name the Collection after the context class, instead of “Unicorn”, so that old Collection can stay if you want to keep it).</p><p>Next we’ll setup a .NET Core API and then configure it to use EF Core with the Cosmos Provider.</p><p>Using Visual Studio 2017 (Im using Community Edition 15.8.9), create a new ASP.NET Core Web project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OyIJb9iIx8U6Fj1-rdp2A.png" /></figure><p>Name it whatever you want and select “OK”, next we’ll select to use .NET Core/ ASP.NET Core 2.1 for our API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dl9bAMbe99phJu4l6Z6SJg.png" /></figure><p>Now its time to install the NuGet packages, we need the Cosmos Provider and EF Core packages, and we’ll throw in Swashbuckle as well so we can use Swagger to test (not required but helpful for demonstration purposes):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jux7j2fbnItxi5HJ_qhvg.png" /></figure><p>Note we are using the latest preview release (preview 3) of EF Core, but the versions will change frequently as its in preview, you can find a lot of great info about the latest fixes, roadmap updates, and changes in preview 3 <a href="https://blogs.msdn.microsoft.com/dotnet/2018/10/17/announcing-entity-framework-core-2-2-preview-3/">here</a>, as well as links to GitHub issue trackers and more.</p><h4>Basic Setup</h4><p>We’ll use a standard .NET Core startup class, there are a few key pieces to note: there is an extension method AddDbContext which allows us to add our context class (defined in the next section), and make it available via dependency injection. We’ll also setup Swagger so we can test out our API easily. You will want to swap out the “YourPrimaryKeyHere” with the key from the Cosmos instance, same for the “<a href="https://eftest.documents.azure.com,/">https://eftest.documents.azure.com:443”,</a> swap it with your instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cd3e487eceffbac0be2d239267056c7/href">https://medium.com/media/0cd3e487eceffbac0be2d239267056c7/href</a></iframe><h4>Entities:</h4><p>This time we are going to have a slightly more complicated set of entities, consisting of 2 separate documents: User, and Car. User will contain an id, name and address, and Car will be an entirely separate document containing an id, make and model.</p><p>Our context class looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/608439c63822ae704b38ed9301ee4df2/href">https://medium.com/media/608439c63822ae704b38ed9301ee4df2/href</a></iframe><p>Notice we expose the id field, which Cosmos will automatically add, or we can set it to a Guid ourselves. This is a useful field to identify our entities later.</p><p>So we now have our context with our 2 DbSets available to be injected to our controller. Next we’ll make a basic API controller with methods to get/create our CarDocs and UserDocs, as well as lookup a car by make.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/445b51a56a38821dbeef23476b6fc30d/href">https://medium.com/media/445b51a56a38821dbeef23476b6fc30d/href</a></iframe><p>Lets run the project and try it out!</p><p>I did edit the launchSettings.json to have Swagger be the default launch page by adding the following profile:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c3d782f95d4eadf5edcb057553d1b25/href">https://medium.com/media/2c3d782f95d4eadf5edcb057553d1b25/href</a></iframe><p>Now if we run the project we get our default Swagger page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcHUDDem-z4PzPMLQkLDgA.png" /></figure><p>The first thing we need to do is run the /api/Values/configure route, which is a bit of a shortcut so we can setup our Cosmos Collection before saving/retrieving anything from it, this route calls _context.Database.EnsureCreated()</p><p>This is going to create a Collection for us to save our entities into, you can build the Collection yourself, EF Core has plenty of configuration settings you can manage yourself.</p><p>We are starting with an empty collection, so lets try adding a few of each document type first, since we‘ll let Cosmos create our id field, we wont bother with creating it here. We just fill out the fields we care about:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjesNwHq9mRdp3RRrg32QQ.png" /></figure><p>You can see the inserts are working correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EK_lGbiGZvgxGByXAtUI_A.png" /></figure><p>We’ll insert a few Car Entities following the exact same steps as above, just using the /api/Values/car route instead.</p><p>If we look at Cosmos, we can see the default strategy EF Core is using to store the documents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dqz1n6yfUuT1FTdW-01V8g.png" /></figure><p>Note how EF Core is applying a Discriminator field to our documents with the entity type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msv1SNh0B6w_hb-IuDw9bg.png" /></figure><p>Finally, lets try our GET routes to see if we get back our newly created entities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojFYkCidx8aazs8-aRtv2A.png" /><figcaption>Response for <a href="https://localhost:5001/api/Values/user">https://localhost:5001/api/Values/user</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMRZLQGaYpCpoyQAqzpPDg.png" /><figcaption>Response for <a href="https://localhost:5001/api/Values/car">https://localhost:5001/api/Values/car</a></figcaption></figure><h4>Final Thoughts</h4><p>As you can see there is no security model and no real error handling, and we cheat a little and just return Ok on our POST routes instead of Created and the entity, but the API shows how easily you can quickly spin up an API and data layer using EF core with Cosmos. I think the next interesting test will be trying some performance metrics to see how it stacks up to other solutions out there. If you’re interested in the full working demo, the API project is available on GitHub <a href="https://github.com/dcokely7/efcorecosmos">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6157945b617" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entity Framework Core with Cosmos]]></title>
            <link>https://medium.com/@dan.cokely/entity-framework-core-with-cosmos-25caa7256326?source=rss-7d1b09a82e42------2</link>
            <guid isPermaLink="false">https://medium.com/p/25caa7256326</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[cosmos]]></category>
            <dc:creator><![CDATA[Dan Cokely]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 05:30:23 GMT</pubDate>
            <atom:updated>2018-11-20T04:51:45.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ermYnHpwQKFoVUzx" /><figcaption>“stars overlooking body of water during nighttime” by <a href="https://unsplash.com/@mischievous_penguins?utm_source=medium&amp;utm_medium=referral">Casey Horner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Update 11/19/2018</p><ul><li>I’ve expanded on this intro article to walk through what a .NET Core API could look like running the EF Core Cosmos Provider, you check it out <a href="https://medium.com/@dan.cokely/net-core-api-with-ef-core-and-cosmos-f6157945b617">here</a></li></ul><h4>Intro</h4><p>Microsoft&#39;s upcoming release of Entity Framework Core 2.2 has some cool features, including a preview Cosmos provider, allowing you to manage your Cosmos documents through EF Core (with caveats). While the full GA of the Cosmos provider may not be fully done before sometime in 2019, its still worth a look, and with the latest release getting close, it seemed like a good time to try out some of these features.</p><h4>Quick Background</h4><p>Entity Framework Core is Microsoft&#39;s ORM for managing data access by allowing developers to operate on classes representing business objects, instead of using T-SQL or similar to directly manage data in the database. EF Core is the cross platform rewrite of Microsoft’s traditional Entity Framework (now in EF 6). Using a provider like MS SQL Server you represent data objects as classes, with EF Core mapping your database tables and columns to these classes and properties (these classes are your Entities, and while technically the Entities should represent business objects, not DB tables, by design they often match your table structure, but a 1–1 mapping is not required). Through binding these Entities and building a Model, you can manage the data in the database tables using .NET code. This removes most of the need for custom SQL queries and manually managing inserts and selects, you can instead query using LINQ against the entity structures you define, and inserts become as simple as creating a new class and saving it to the database through EF Core.</p><p>Traditionally this functionality was mainly limited to relational providers ( aka SQL Server). This upcoming functionality in EF Core will allow first class support for the document based Cosmos DB (using the SQL API, which we’ll see later). This is great, as the documents in Cosmos are typically represented as classes anyway in your backend application. So now, adding a way to directly insert, read, etc. using EF Core will allow you to easily manage your documents without having to write your own data service layer to provide this same functionality (as is the main option now).</p><h4>Demo</h4><p>We’ll start out with setting up a Cosmos instance, then create a console app to write a document and then read it back using EF Core.</p><p>Starting from the Azure Portal we’ll create a Cosmos DB instance, you can create one from the top level “Create a resource” or the Cosmos DB section directly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*et_lSYZnjyUQY88VonOdNA.png" /></figure><p>The important part of the Cosmos config is to use the SQL API for talking with Cosmos (we’ll still be dealing with documents, this is just the API we’ll use to talk with Cosmos).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRBf1oJNertrP5VUrbyfPA.png" /></figure><p>Now with support of Cosmos being a preview feature, we’re not going to push our luck and enable Geo-Redundancy or Mult-region Writes, you will need to check the issue tracker on Github for the latest support/release issues <a href="https://github.com/aspnet/EntityFrameworkCore/issues/12086">HERE</a></p><p>You can review and create the instance, and let it provision. The next step is collecting the keys for communicating with the DB, we need the URI and PRIMARY KEY, which we’ll use later in the console app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHOOk9I-GvGKg0iP2YPdRA.png" /></figure><p>Next we’ll set up our Visual Studio project, for this example we’ll use a .NET Core Console App, but realistically this would be part of an API or Class Library project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0YHbqehaAORMnnlnuIxsbw.png" /></figure><p>The next part is the NuGet packages, we need a few preview packages to make this work. Keep in mind these preview packages will change fairly frequently as they release updates, so these may be different, but install the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLy5UvcG-evg9NNFXAkqKw.png" /></figure><p>We only need two files to prove that our EF Core Cosmos setup is working. The first is a DbContext, which everyone who has used EF before will be familiar with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c39eccd0fadb65bee1af5415c7883cb7/href">https://medium.com/media/c39eccd0fadb65bee1af5415c7883cb7/href</a></iframe><p>We are first going to define one entity, TestDoc, which has three properties: Name, Email, and id. Id is automatically added to the Cosmos document, but it can be set by us, or can be created by Cosmos automatically. It is often useful to expose this identifier as a unique key to the document, so we’ll add it to the document ourselves. Since our EfTestContext class is so small, we’ll stick our entity definition (TestDoc) in the same file.</p><p>The other part of our class is the EF Core specific settings, starting with our DbSet TestDocs:</p><pre>public DbSet&lt;TestDoc&gt; TestDocs { get; set; }</pre><p>This exposes a DbSet of type TestDoc through the context, allowing us to take actions (create, read, etc.) on the collection of TestDoc entries in the DB.</p><p>This is an extremely simple example. We are not configuring OnModelCreating(…) and many of the other common EF configurations. We will go into more elaborate mappings later.</p><p>Next we are going to wire up our Main method. We have 2 methods, InsertDocAsync and FindDoc. In our Main we are going to create a new document with the name “FirstName LastName” and an email of “test@home.com”. We set the GUID of the id field on the client, but this can also happen on the Cosmos side. After we save the document, we are going to look it up by name, print it on the console window, then wait for user input to close.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83d32c3973fc3603dfd55bbbd6ffc6d5/href">https://medium.com/media/83d32c3973fc3603dfd55bbbd6ffc6d5/href</a></iframe><p>For simplicity we just force the async calls to run from our Main() method, this is not a safe or efficient way to do this in a production setting, but for demonstration purposes it does the trick. Notice we create a new Cosmos document simply by creating a new TestDoc, adding it to our DbContext, then saving the changes back. Reading values out is just as simple, we can simply look documents up in our Context’s DbSet of TestDocs and filter out what we are looking for. Lets run the project and see what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBc4i6kCWLQX-0kk3C7Vpw.png" /></figure><p>As you can see from above we got back the “FirstName LastName” from the document we just inserted. This means our round trip works!</p><h4>Some interesting notes</h4><p>Since we didn’t specify a collection for our documents, only a database name, Microsoft helpfully created one for us… named Unicorn</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*qLipP1mT9E61r-RrBsNPgg.png" /></figure><p>Its also important to note the line in our InsertDoc method:</p><pre>await context.Database.EnsureCreatedAsync();</pre><p>This will scaffold out what we need behind the scenes so we can just insert our docs. Typically you would have a more elaborate policy for creating a collection.</p><h4>Wrap up</h4><p>While the Cosmos provider is still in its infancy, you can begin to see the power in being able to represent your domain/business objects directly as Cosmos documents and using EF Core in between. Very little code is required to have a fully built out data model with CRUD support, essentially doing little more than defining your entities.</p><p>I’ll be following this up with another article, digging deeper into the setup of a more elaborate configuration, so stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25caa7256326" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Durable Functions (part 1 — Intro)]]></title>
            <link>https://medium.com/@dan.cokely/azure-durable-functions-part-1-intro-f99ed8fb7b45?source=rss-7d1b09a82e42------2</link>
            <guid isPermaLink="false">https://medium.com/p/f99ed8fb7b45</guid>
            <category><![CDATA[azure-durable-functions]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[durable-functions]]></category>
            <dc:creator><![CDATA[Dan Cokely]]></dc:creator>
            <pubDate>Fri, 31 Aug 2018 00:50:18 GMT</pubDate>
            <atom:updated>2019-03-15T00:47:37.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nwFz-URKaRKQoIII" /><figcaption>“A view from over a conductor&#39;s stand on an elegant concert hall in Katowice” by <a href="https://unsplash.com/@rgrzybowski?utm_source=medium&amp;utm_medium=referral">Radek Grzybowski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro</h3><p>The goal of this article is to introduce Azure Durable Functions. Starting with the basics, we’ll walk through the simplest setup. The plan is to add more articles building on this initial setup to explore more complex architectures and designs in the near future. A basic understanding of Azure Functions will be helpful.</p><p><em>Update 3/14/19 — I’ve added another article digging deeper into Durable Functions </em><a href="https://medium.com/@dan.cokely/azure-durable-functions-part-2-e6053b50eaaa"><em>available here</em></a></p><h3>Background</h3><h4>Serverless</h4><p>The Serverless Architecture movement makes a lot of sense as workloads shift to cloud platforms: consumption billing, microservice oriented, event driven, and the general decoupling of workloads from their associated hardware. Cloud vendors and developers alike see the power in simply writing code to perform an isolated unit of work, and then only paying when its performing work. Isolated workers that do a single (independent) piece of functionality can also achieve massive scale, be globally distributed, support HA and many other enterprise features. While it can be difficult to adapt an existing application to leverage serverless, it can be a great (and fast) way to get new apps and features off the ground.</p><p>Enter Azure Functions as one of Microsoft&#39;s services to capture this type of application workload. Azure Functions allow you to write the functions that constitute your business logic, without most of the framework and infrastructure typically required. You are billed on consumption and have an ever growing list of supported triggers (storage, queue, HTTP, Cosmos DB, and many more), making integration and initial configuration easy. Full documentation <a href="https://docs.microsoft.com/en-us/azure/azure-functions/"><em>here</em></a><em>.</em></p><h4>Challenges</h4><p>So far, Azure Functions seem great: pay for what you use, lots of integration triggers, easy deployment, just write your logic and little else, etc. etc. so whats the catch? Well, once an application begins to scale to many Azure Functions, each performing parts of a larger process (take processing a Purchase Order as an example), coordination, retrying, logging, concurrency, etc. all start to become issues that need to be addressed in the system. Many times your application will require a state for the processing of complex tasks (i.e. whats been processed so far, whats left, what errors have occurred, or just driving different processing paths depending on the input or intermediate results). With a single Azure Function with all your code in it, life was much easier, because everything was right there, you could share and process whatever common state you needed. This is not so easy when dealing with multiple Azure Functions. They are meant to be stateless, and much like a function, take input, perform some operations and give an output (although Azure Functions often have side effects, change states, etc. so they are rarely pure functions). What you are then left with is writing your own orchestrator/coordinator to deal with all the dependencies with multiple interconnected Azure Functions.</p><h4>Enter Durable Functions</h4><p>Durable Functions are essentially Azure Functions that use the Durable Function extension to allow for new types of Functions and triggers (We’ll drop the Azure part and just call them Functions now). The Orchestrator Function and Activity Function (you can find Microsoft’s explanation and documentation for Durable Functions <a href="https://docs.microsoft.com/en-us/azure/azure-functions/durable-functions-overview">here</a>) are the main ones we’ll focus on for this demo.</p><p>The Orchestrator Function as the name suggests allow for scheduling and calling of Activity Functions in a repeatable and reliable way. It can chain Functions together, call multiple Functions in parallel, replay Functions, and many other complex coordination activities. The Activity Functions become the workers that get called to do the business logic (calling APIs, accessing/manipulating data etc.). Behind the scenes the Orchestrator and Activity Functions are using queues and other storage structures to interact, and maintain state/history, but this is dealt with behind the scenes for you. Your Orchestrator can compose complex business logic across multiple Functions with minimal code.</p><h3>Demo</h3><p>We are going to build out a demo Durable Function using Visual Studio, which chains several calls together. The Orchestrator Function will start multiple Activity Functions, wait until they have all completed, then aggregate their responses together.</p><h4>Setup</h4><ul><li>Visual Studio 2017 (v 15.3 +, this demo was made with 15.8.1 Community Edition)</li><li>Latest Azure SDK for .NET (<a href="https://azure.microsoft.com/en-us/downloads/">here</a>)</li><li>Azure Storage Emulator (this should come with the sdk, but check just in case)</li><li>Azure Functions Extensions (installed through Visual Studio Extensions, the version used here was 15.8.5023.0)</li></ul><p>Create a new project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NGC04BCagYQyw8lxdUdQw.png" /><figcaption>Create a new Function App</figcaption></figure><p>Create V2 Function type with empty trigger and access to storage emulator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfEutR1vsB2XGvsukerKyg.png" /></figure><p>Lets build and run our empty project to make sure everything is installed and working, you should have no build errors and see the Azure Function startup screen similar to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*zTLOWVIbZ6F29mFHmD5AKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZLKScsTNPtdUbcCUo0HRw.png" /></figure><p>If you get a warning about setting the Function Worker Runtime, make sure your local.settings.json file has the following entry under the “Values” section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*Hf4vtPDZc1TuPPVPSNkzEw.png" /></figure><p>Great, our Function is up and running, now lets add the Nuget packages for creating a Durable Function:</p><ul><li>Microsoft.Azure.WebJobs.Extensions.DurableTask (v 1.5)</li></ul><p><em>NOTE: I was actually getting an error when trying to install the above Nuget, I was getting a vague Newtonsoft error about a mismatch, I ended up having to upgrade the Microsoft.NET.Sdk.Functions from 1.0.6 to 1.0.14 and then everything worked. Depending on your Sdk/Visual Studio version, you may see some strangeness, installing the latest version of both should fix it.</em></p><p>Next we need to add a Function so we can actually do something useful with our project, hold Ctrl+Shift+A to bring up the screen to add a new item and select Azure Function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGiGU47VoYVr1RWqCB7JeA.png" /></figure><p>Hit “Add” and then set the type to Orchestrator Trigger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9tuNa8gfUR6X7Awr54TKw.png" /></figure><p>This will now scaffold your “hello world” Durable Function. Lets walk through the Functions that were created.</p><p>If the example Visual Studio creates for you differs from the code highlighted below, the full example file is available here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abadf0e8f6b5b43385fa5fef7f0c96f7/href">https://medium.com/media/abadf0e8f6b5b43385fa5fef7f0c96f7/href</a></iframe><h3>The Code</h3><h4>OrchestrationClient</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a51aab107383424a1fe18bd70f71aed/href">https://medium.com/media/4a51aab107383424a1fe18bd70f71aed/href</a></iframe><p>The Orchestration Client is how we get the process started. The key here is the DurableOrchestrationClient, the client is how you interact with the Orchestration Functions, including: starting, stopping, getting status, etc. Here you can see we are calling StartNewAsync on the Orchestrator Funtion “Function1” (NOTE: the Function names are the names that come from [FunctionName(“FunctionNameHere”)], not the actual method name). We can also pass input into the Orchestrator using the second parameter, but for now its just null.</p><p>Function1_HttpStart happens to be an HTTP trigger but it could be any type of trigger, the important part is starting the Orchestrator.</p><p>The other important part is that we are returning a status, not the finished result. Once we hit this HTTP trigger, we call the Orchestrator which returns URLs for getting status back, that way the HTTP caller is not waiting on the wire for what may be hours while the Functions process.</p><h4>Orchestrator Function</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d34f285fdc07dbee4084b55d04b6a6eb/href">https://medium.com/media/d34f285fdc07dbee4084b55d04b6a6eb/href</a></iframe><p>Note the trigger type of this function is OrchestrationTrigger, this is triggered from our Client in the first Function. We are passed a DurableOrchestrationContext, this is how we call Activity Functions which this orchestrates, as well as get input parameter, or start a timer. In this case you can see we call Activity Functions.</p><pre>outputs.Add(await context.CallActivityAsync&lt;string&gt;(&quot;Function1_Hello&quot;, &quot;Tokyo&quot;));</pre><pre>outputs.Add(await context.CallActivityAsync&lt;string&gt;(&quot;Function1_Hello&quot;, &quot;Seattle&quot;));</pre><pre>outputs.Add(await context.CallActivityAsync&lt;string&gt;(&quot;Function1_Hello&quot;, &quot;London&quot;));</pre><p>Above is the real work in the Orchestrator, using our DurableOrchestrationContext we are calling the Function “Function1_Hello” three times with different inputs, then putting the results of each call into our output object. Since we are awaiting each call consecutively this is an example of Function chaining. This is where we could implement our retry policies, or do a fan out policy (running the calls in parallel), or other processing flow logic.</p><p>The Orchestrator Function as the names says should be the Function to call the Activity Functions which do the real business logic, the Orchestrator’s job is to orchestrate, calling Activities, passing inputs and outputs between Activity Functions.</p><p>Orchestrator Functions should be deterministic (ie multiple re-runs should produce the same output). This is because behind the scenes, the Orchestrator will replay logic if something fails, times out, or other conditions, so if the Orchestrator is generating values randomly or other non-deterministic operations, there can be problems. We can handle retry logic, try/catch etc. in the Orchestrator as well.</p><h4>Activity Function</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e1054d99f6baeb51af1c7a1c915d405/href">https://medium.com/media/8e1054d99f6baeb51af1c7a1c915d405/href</a></iframe><p>Notice the trigger type is Activity Trigger, meaning its started from an Orchestrator, and this is the real worker of the system. The Activity Function is the one that does the API calls, or logic/processing etc. and actually has the business logic. In this case its just getting a string, and returning a string back.</p><p>Lets try it all out:</p><p>When you start the project, it will tell you the path that the HTTP trigger is running on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gaRcuhkCm8KYxjtaCxcjA.png" /></figure><p>Try the URL in your favorite REST client, i’m using Insomnia below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6drfMe6Hy6Oh2zKfFvLuAw.png" /></figure><p>Notice we get back the URLs to perform various operations against the running Durable Function, not the actual processing response. If we hit the statusQueryGetUri we can see what is happening, paste it into a browser and lets check out our response…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHlS8IUQiTmo4HA92vddzQ.png" /></figure><p>Success! You can see the three Activity Functions each ran, reported their values back to the orchestrator, which aggregated them together. We could extend the orchestrator to call another Activity Function to save these values to Cosmos, or put a result to a status queue or similar.</p><h4>Whats next</h4><p>This is an extremely simple example, but shows how the Durable Function framework can coordinate Functions to chain logic and work together. You can build from this base to create more complex workflow. The plan is to get another article to show some more advanced flows building on this setup as well, so stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f99ed8fb7b45" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>