<?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 David Reyes-Cairo on Medium]]></title>
        <description><![CDATA[Stories by David Reyes-Cairo on Medium]]></description>
        <link>https://medium.com/@dreyescairo?source=rss-2446b4a1bb43------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Q2k6SXBfWJFuaC6O.</url>
            <title>Stories by David Reyes-Cairo on Medium</title>
            <link>https://medium.com/@dreyescairo?source=rss-2446b4a1bb43------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:50:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dreyescairo/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[Creating a Simple Photo Gallery App]]></title>
            <link>https://medium.com/davidrcwebdev/create-a-simple-photo-gallery-app-using-asp-net-9d7aed97ce16?source=rss-2446b4a1bb43------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d7aed97ce16</guid>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[code-first]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[David Reyes-Cairo]]></dc:creator>
            <pubDate>Thu, 03 May 2018 18:32:59 GMT</pubDate>
            <atom:updated>2018-05-08T16:04:34.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Visual Guide To Creating a Simple Photo Gallery App Using ASP.NET Core 2.0 Razor Pages and Azure Storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23J1aOh8LTNuNov-1sE8ag.png" /></figure><h3><strong>Introduction</strong></h3><p>Microsoft’s .NET framework is a platform for developing applications with a rich library of classes at our disposal. It is also a Windows only platform, and deployed apps are full of dependencies that we may never need or use.</p><p>In recent years, Microsoft saw a need for change and has taken huge strides in refactoring their framework to keep up with other, more modern platforms. As a result, .NET core was born!</p><p>.NET Core is powerful, yet super lightweight compared to the traditional .NET framework.</p><p>Why is this awesome news?!</p><p>Because now we can develop and deploy applications with minimal dependencies. We only add and deploy what we need in our app. It is also truly cross-platform; meaning we can now develop, deploy, and run our apps on systems other than Windows.</p><p>— This is just a brief introduction, but if you are looking for a more in depth overview of .NET Core head over to <a href="https://docs.microsoft.com/en-us/dotnet/core/">Microsoft’s documentation pag</a>e</p><p>With .NET Core, we also got Razor Pages.</p><blockquote><em>Razor Pages is a new feature of ASP.NET Core that makes coding <br>page-focused scenarios easier and more productive <br>-Microsoft Docs — </em><a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-pages/?view=aspnetcore-2.1&amp;tabs=visual-studio">Introduction to Razor Pages in ASP.NET Core</a></blockquote><p>Razor pages are lightweight and flexible to work with. It consists of a <strong>.cshtml </strong>page for the front end markup, and a <strong>cshtml.cs</strong> file for the server side code. In a Razor Page, we can mix HTML and C# code statements using Razor syntax. This makes it extremely easy to manipulate our data and display it as dynamic content.</p><p>In addition to .NET Core Razor Pages, this guide will also leverage another great Microsoft product — Azure. Azure is a cloud service that offers things like file storage, database instances, app hosting, virtual machines, and <a href="https://azure.microsoft.com/en-us/services/">much, much more.</a></p><p>With that said, let’s get started!</p><h3><strong>Project Overview</strong></h3><p>This guide will serve as a simple introduction to just how easy it is to get a Razor Pages project up and running.</p><h4>We will be</h4><ul><li>Creating a new <strong>Razor Pages</strong> Web Application project</li><li>Setting up a local database using <strong>Code First Migrations</strong></li><li>Creating a simple form to upload a photo with a caption</li><li>Storing images to <strong>Azure Storage</strong></li><li>Creating a page that gets image data from our database and displays them</li></ul><h3>What you will need</h3><ul><li>An Azure free account</li><li>Visual Studio Community 2017 with a minimum of these workloads<br><strong>ASP.NET and web development<br>Azure development<br>Data storage and processing<br>.NET core cross-platform development</strong></li></ul><h3><strong>Creating a new project</strong></h3><p>Open Visual Studio and navigate to <strong>File &gt; New &gt; Project</strong></p><p>In the New Project window, select <strong>ASP.NET Core Web Application</strong>, give it a name (in this case I named mine MyPhotoGallery), and pick a directory for your new project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVJuLj4X5PocnKfPY-Ct6Q.png" /></figure><p>In the next window, select <strong>Web Application</strong>. This creates an example ASP.NET Core Razor Page project with a layout and example pages to get you started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvcaNTyPIDB6Kz5_6S62Ug.png" /></figure><h3>Structure Of A Razor Pages Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*4hpVFMx4YW3yYA50rQfcBg.png" /><figcaption>This is just the basic structure. You are not necessarily bound to this structure; making it flexible to use other design patterns.</figcaption></figure><p>Because we created a project with a template, Visual Studio created all of the boiler plate for us. Otherwise, we would have to create most of this manually.</p><ul><li><strong>wwwroot</strong> is where all static content is stored. Stuff like JavaScript files, CSS, images, and libraries like Bootstrap belong here.</li><li><strong>Pages</strong> is where all the pages will live. Typically, each .cshtml file will be paired with a .cshtml.cs file.</li><li><strong>appsettings.json</strong> is where things like connection strings go so we can connect to our database.</li></ul><h3><strong>Setting Up A DbContext</strong></h3><p>Defining a <strong>DbContext</strong> in the project is what allows us to persist data to our database and populate data from the database. <br>We will use this to save our image URL’s and captions and eventually display them back to the person viewing the gallery.</p><p>First, let’s make a new folder to hold our models and our <strong>DbContext</strong>.</p><p>Right click your project and navigate to <strong>Add &gt; New Folder</strong>. <br>Name this folder <strong>Models</strong></p><p>Next, add a Class named <strong>ApplicationDbContext </strong>to the <strong>Models </strong>folder by right clicking the Models folder and navigating to <strong>Add &gt; Class</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*daT8TXVcNVFer6Dp8wuf5A.png" /></figure><p>Now that we have our class in the project, we need to derive it from <strong>DbContext</strong> so that we can have <strong>DbSet</strong> and other related methods and properties exposed (We will use <strong>DbSets</strong> later on in the guide).</p><pre>public class ApplicationDbContext : DbContext<br>{<br>}</pre><p><strong>NOTE: </strong>Remember to add the line <strong>using Microsoft.EntityFrameworkCore; </strong>to the top of the class before the namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*W98kZhZogYwY6-8Lq_oSIA.png" /><figcaption>Using directives tell the compiler which namespaces to look in to find the classes you use in you code such as DbContext.</figcaption></figure><p>Next, let’s add a constructor that takes in <strong>DbContextOptions</strong> as a parameter. the options that are passed in will be used to pass the connection string when we instantiate it at startup.</p><pre>public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options) : base(options)<br>{<br>}</pre><p>Time to setup the connection string to our database so we can start communicating with it.</p><p>Open up <strong>Startup.cs </strong>and in the <strong>ConfigureServices </strong>method, add these lines</p><pre>services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnectionString&quot;)));</pre><pre>services.AddSingleton(Configuration);</pre><p>What this accomplishes is setting up dependency injection for our services. The first statement is setting up the container with an instance of our <strong>ApplicationDbContext </strong>with the connection string named “DefaultConnectionString” passed in. This allows us to communicate with the database wherever we need to within the app without manually having to create new instances.</p><p>The second statement adds a service of <strong>Configuration </strong>to the container. By adding it as a singleton, whenever we access it from another class, it will always be the same instance throughout the app.</p><p>Here is an excellent article explaining <a href="https://joonasw.net/view/aspnet-core-di-deep-dive">ASP.NET Core Dependency Injection</a> in more depth.</p><p>NOTE: Ensure these using directives are at the top of <strong>startup.cs</strong></p><pre>using Microsoft.AspNetCore.Builder;<br>using Microsoft.AspNetCore.Hosting;<br>using Microsoft.EntityFrameworkCore;<br>using Microsoft.Extensions.Configuration;<br>using Microsoft.Extensions.DependencyInjection;<br>using MyPhotoGallery.Models;</pre><p>Before we go on to the next step, we need to add the connection string to <strong>appsettings.json</strong></p><p>In our appsettings, above “Logging:” add the connection string so it looks like this</p><pre>{<br>&quot;ConnectionStrings&quot;: {</pre><pre>&quot;DefaultConnectionString&quot;: &quot;Server=localhost\\SQLEXPRESS;Database=MyPhotoGallery;Trusted_Connection=True;MultipleActiveResultSets=True&quot;,<br>},</pre><pre>&quot;Logging&quot;: {<br>&quot;IncludeScopes&quot;: false,<br>&quot;LogLevel&quot;: {<br>&quot;Default&quot;: &quot;Warning&quot;</pre><pre>      }</pre><pre>   }</pre><pre>}</pre><p>Now that we can connect to our database, let’s start working with data!</p><h3><strong>Creating An Image Model And Running Code-First Migrations</strong></h3><p>Let’s create a model for our Image. This model is going to represent an image in code, and anything related to it such as an Id, URL, and the caption. This model will also be reflected in the database when we do our migration and update the database.</p><p>Right click the Models folder and navigate to <strong>Add &gt; Class</strong>.</p><p>Name your class <strong>GalleryImage </strong>and click <strong>Add.</strong></p><p>In the <strong>GalleryImage </strong>class, declare some properties for <strong>Id</strong>, <strong>URL</strong>, and <strong>Caption.</strong></p><pre>public int Id { get; set; }</pre><pre>public string URL { get; set; }</pre><pre>public string Caption { get; set; }</pre><p>Now, were going to add a migration of the <strong>GalleryImage</strong> model, then update the database with the migration. This workflow is called <strong>Code First</strong>; meaning, we are starting with the code and all the models before transferring it to the database.</p><p>In contrast, Database First workflow means that you start with your database by defining all your tables first, then creating models from the tables that were already created.</p><p>We first need to let our <strong>DbContext</strong> know that we re going to be transferring data of type <strong>GalleryImage</strong>. To do this, add this line in your <strong>ApplicationDbContext</strong> right under the constructor.</p><pre>public DbSet&lt;GalleryImage&gt; GalleryImages { get; set; }</pre><p>A <strong>DbSet</strong> is used to query and save instances of <strong>GalleryImage</strong> (or any other model) in our database.</p><p>Now let’s create our first migration by opening up <strong>Package Manager Console</strong> through <strong>Tools</strong> &gt; <strong>NuGet Package Manager</strong> &gt; <strong>Package Manager Console.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*4pgEi4Z8OOOugf45sirHZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*zzelNVVFGxwUjU0UWUh4ZA.png" /></figure><p>Once Package Manager is opened, simply type <br> <strong>Add-Migration AddGalleryImageToDB</strong>.</p><p>Upon successful completion of the command, you will see a new folder in your project with a couple files. One of the files will have the name of the migration we ran. This is C# code that is generated with all of our Model information, ready to be sent to the database for table creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*_NvPsLAZzmhZKbL9Z9V6CQ.png" /></figure><p>Next, <strong>in Package Manager Console</strong>, run the command <strong>update-database. </strong>This runs all the code that was generated from our migration.</p><p>Upon successful completion, we can see that a database table representing <strong>GalleryImage </strong>was created by navigating to <strong>View</strong> &gt; <strong>SQL Server Object Explorer</strong>.</p><p>This pretty much covers the workflow for creating models and migrating them to the database. Later, we will go over populating the database with data from a form on a web page.</p><h3>Setting Up An Azure Storage Blob Container</h3><p>Now that our database is ready to go and we have a model for our data, we can create an Azure Storage Blob Container where our actual images will live.</p><p>Navigate to <a href="https://azure.microsoft.com/">https://azure.microsoft.com</a> and create a <strong>free </strong>account.</p><p><strong>NOTE: </strong>At the time of writing this article, Microsoft offers a free trial account with $200 credit for 30 days. After those 30 days, you will need to switch to a Pay-As-You-Go account if you want to keep using the service. More information can be found <a href="https://azure.microsoft.com/en-us/free/free-account-faq/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*szjMQdUY-p5hnQjgeuR8HQ.png" /></figure><p>Once logged in, you will notice on the left side bar an option called <strong>Storage Accounts</strong>. click it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*mHHgLtrj-XBpiRBdXBgB2w.png" /></figure><p>Towards the top of the page, click<strong> Add</strong> and fill in the form with this information.</p><p><strong>NOTE:</strong> The <strong>Name </strong>must be unique across all of Azure, so try to find something that isn’t taken but is relevant to the project. Also ensure the <strong>Location </strong>matches where you are.</p><p>Go ahead and leave default values under the Virtual Networks section of the form.</p><p>Click create and wait a few seconds for the account to deploy. This will redirect you to your dashboard and show the new storage account.</p><p>Go ahead and click your storage account to open it.</p><p>Once inside the account, on the left menu bar under <strong>Blob Service</strong>, select <strong>Containers</strong>. After that, add a container by clicking <strong>+Container </strong>towards the top of the page.</p><p>Fill the form in with this data (You can use the same name I used for the container)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdKbB8nJJNDKTC_enhcs4w.png" /></figure><p>Once you click OK, you will see your new container in the list named <strong>photogallery-images</strong></p><p>Now that all this is done, navigate back to your storage accounts and click the account you created.</p><p>Next, we need to get the access key so we can hookup to the account through our app.</p><p>In the Storage account’s left side menu, under <strong>Settings</strong>, select <strong>Access Keys</strong></p><p>It should take you to something that looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIB53JrBJIxwtr5Efd4oug.png" /></figure><p>Copy the connection string and head back over to our projects <strong>appsettings.json</strong></p><p>Paste the string you copied in there like this and associate it with the name <strong>AzureStorageConnectionString.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDhyvIcJIj6GFFoBEF_OkQ.png" /></figure><p>Once that is done, you are finished with setting up your storage container.</p><p>In the next section, we will utilize the <strong>AzureStorageConnectionString </strong>we added in <strong>appsettings.json</strong> to upload images to your newly created container from a form.</p><h3>Creating An Image Upload Form</h3><p>Let’s recap what we have done so far.</p><ul><li>We created a new <strong>ASP.NET Core Razor Pages</strong> project.</li><li>Created a <strong>DbContext </strong>with our connection string so we can hookup to our database.</li><li>Created a <strong>GalleryImage </strong>model and executed our first migration.</li><li>Lastly, we setup a storage container in Azure.</li></ul><p>Now, it’s time to set up a form for uploading our images.</p><p>Create a new <strong>Razor Page</strong> by right clicking the <strong>Pages</strong> folder and navigating to <strong>Add</strong> &gt; <strong>Razor Page</strong>.</p><p>The <strong>Add Scaffold</strong> dialog will show. Just click Add to go to the next dialog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufoVHiGHOIyDUy4warXgKw.png" /></figure><p>Name your new Razor Page <strong>ImageUploadForm</strong>. Leave everything else as the default and click <strong>Add</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAKrjMnXIJWAf3TiZaPu3w.png" /></figure><p>We can now see two new files in our Pages folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*BIC7R_7snTIT78GVsdfQxA.png" /></figure><p><strong>ImageUploadForm.cshtml</strong> is where all of the client-side code will go such as HTML and Javascript.</p><p><strong>ImageUploadForm.cshtml.cs</strong> is where all of our C# server side code will go for example, getting data from our database and serving it to the page.</p><p>When we open <strong>ImageUploadForm.cshtml.cs</strong>, you will notice a single void method called <strong>OnGet()</strong>. When a request is made to the page, this method gets called to initialize the state of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxf0E4e-6XSddN0FV3W0fQ.png" /></figure><p>Before we continue developing the form, let’s create a link to this form in the navbar.</p><p>Open <strong>_Layout.cshtml</strong> and navigate to the navbar links. Lets replace the about page link with a link to the <strong>ImageUploadForm </strong>page by using this line of code instead</p><pre>&lt;li&gt;&lt;a asp-page=&quot;/ImageUploadForm&quot;&gt;Upload an image&lt;/a&gt;&lt;/li&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlgnelZqZ14dKFYqM26VIw.png" /></figure><p><strong>NOTE:</strong> The layout is basically the common template of the page. This style will persist elements on other pages you create so you don’t have to repeat code all over the place.</p><p>Now we will look at <strong>ImageUploadForm.cshtml</strong>.</p><p>Here we notice a couple very important things. <strong>@page</strong> and <strong>@model</strong>.</p><p><strong>@page </strong>is a Razor page directive that enables the page to handle requests. This must always be the first directive.</p><p><strong>@model</strong> is a directive that specifies what type of model is being passed to the razor page. In our case we will be passing the ImageUploadFormModel as defined in the <strong>ImageUploadForm.cshtml.cs </strong>file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*-otGgZkOfdl9J-oDxEO2Yg.png" /></figure><p>If we ever want to <strong>transition into C# code from inside the HTML</strong>, all you have to do is start the markup with an ‘<strong>@</strong>’ symbol; Just like we see here when setting the title of the page.</p><pre>@{<br>ViewData[&quot;Title&quot;] = &quot;ImageUploadForm&quot;;<br>}</pre><p>You will see this syntax referred to as <strong>Razor Syntax.</strong></p><p>Let’s go back to the <strong>ImageUploadForm.cshtml.cs </strong>file and start adding some properties and methods.</p><p>At the very top of the file, make sure to add these <strong>using directives</strong></p><pre>using System;<br>using System.Threading.Tasks;<br>using Microsoft.AspNetCore.Http;<br>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.AspNetCore.Mvc.RazorPages;<br>using Microsoft.Extensions.Configuration;<br>using Microsoft.WindowsAzure.Storage;<br>using Microsoft.WindowsAzure.Storage.Blob;<br>using PhotoUploader_Razor.Models;</pre><p>Then, at the top of the class, add these lines of code</p><pre>//COMMENT:static declaration of the CloudBlobClient so we can //interact with our storage service.<br><strong>static CloudBlobClient blobClient;</strong></pre><pre>//COMMENT:constant to hold the blob container name<br><strong>const string BLOB_CONTAINER_NAME = &quot;photogallery-images&quot;;</strong></pre><pre>//COMMENT:static declaration of CloudBlobContainer which will store //a reference to the blobcontainer that we created earlier<br><strong>static CloudBlobContainer blobContainer;</strong></pre><pre>//COMMENT:declaration of ApplicationDbContext for an instance of our //database context.<br><strong>private ApplicationDbContext _context;</strong></pre><pre>//COMMENT:setup our configuration so that we can have access to the //Azure storage connection string later.<br><strong>public IConfiguration _configuration;</strong></pre><pre>//COMMENT:This is a property for GalleryImage with a //BindPropertyAttribute. This will automatically bind the data from //the form to the properties of GalleryImage when the form is //submitted.<br><strong>[BindProperty]<br>public GalleryImage GalleryImage { get; set; }</strong></pre><p>Add this constructor which will setup our context and configuration</p><pre>public ImageUploadFormModel(IConfiguration configuration, ApplicationDbContext context)<br>{</pre><pre>_context = context;</pre><pre>_configuration = configuration;</pre><pre>}</pre><p>Next, replace the default <strong>OnGet()</strong> method with an asynchronous version</p><pre>public async Task OnGetAsync()</pre><pre>{</pre><pre>// COMMENT:Retrieve storage account information from connection <strong>stringCloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString(&quot;AzureStorageConnectionString&quot;));</strong></pre><pre>// COMMENT:Create a blob client for interacting with the storage //blob service.<strong><br>blobClient = storageAccount.CreateCloudBlobClient();</strong></pre><pre>//COMMENT:this gets a reference to the container that we created earlier<br><strong>blobContainer = blobClient.GetContainerReference(BLOB_CONTAINER_NAME);</strong></pre><pre>//COMMENT:this will create a container with the name that we passed //above in the event that the container doesn&#39;t exist.<br><strong>await blobContainer.CreateIfNotExistsAsync();</strong></pre><pre>//COMMENT:set permissions to public access<br><strong>await blobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });</strong></pre><pre>}</pre><p>Now let’s build our <strong>OnPost() </strong>method. This will get executed when we submit our form.</p><pre>public async Task&lt;IActionResult&gt; OnPost(IFormCollection form)</pre><pre>{<br><strong>try</strong></pre><pre><strong>{</strong></pre><pre>//COMMENT:we are only allowing one upload, so just get the first one //in the file collection.<br><strong>var file = form.Files.FirstOrDefault();</strong></pre><pre>//COMMENT:this block will store the image into the blobContainer //container<br><strong>CloudBlockBlob blob = blobContainer.GetBlockBlobReference(file?.FileName);<br>blob.Properties.ContentType = file?.ContentType;<br>await blob.UploadFromStreamAsync(file?.OpenReadStream());</strong></pre><pre>//COMMENT:set the url of the image that we just uploaded<br><strong>GalleryImage.URL = $&quot;{blobContainer.StorageUri.PrimaryUri}/{file?.FileName}&quot;;</strong></pre><pre>//COMMENT:add a GalleryImage to the database and save it.<br><strong>_context.GalleryImages.Add(GalleryImage);<br>await _context.SaveChangesAsync();</strong></pre><pre>//COMMENT:if we got this far, it was successful so let&#39;s tell the user.<br>//set a tempData variable to a success string. we will use this //variable after the redirect to the gallery.<br><strong>TempData[&quot;SuccessMessage&quot;] = &quot;Image upload success!&quot;;</strong></pre><pre><strong>return RedirectToPage(&quot;ImageGallery&quot;);</strong></pre><pre><strong>}</strong></pre><pre><strong>catch (Exception ex)</strong></pre><pre><strong>{</strong></pre><pre><strong>return RedirectToPage(&quot;Error&quot;);</strong></pre><pre><strong>}</strong></pre><pre>}</pre><p>That covers the server side code. Let’s go to the client side and add our form.</p><p>Underneath the header add the following</p><pre>&lt;div class=&quot;container&quot;&gt;</pre><pre>&lt;div class=&quot;row&quot;&gt;</pre><pre>&lt;div class=&quot;col-md-4 col-md-offset-4&quot;&gt;</pre><pre>&lt;form method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;</pre><pre>&lt;h2&gt;PhotoGallery&lt;/h2&gt;</pre><pre>&lt;div class=&quot;form-group&quot;&gt;</pre><pre>&lt;div&gt;</pre><pre>&lt;label class=&quot;control-label&quot; for=&quot;file&quot;&gt;Select File&lt;/label&gt;</pre><pre>&lt;input type=&quot;file&quot; id=&quot;file&quot; name=&quot;selectFile&quot; class=&quot;&quot; accept=&quot;image/gif, image/jpeg, image/png&quot; onchange=&quot;DisplayFilesToUpload()&quot; /&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;p&gt;</pre><pre>&lt;img src=&quot;&quot; id=&quot;profile-img-tag&quot; width=&quot;200&quot; /&gt;</pre><pre>&lt;/p&gt;</pre><pre>&lt;div class=&quot;form-group&quot;&gt;</pre><pre>&lt;label asp-for=&quot;GalleryImage.Caption&quot;&gt;&lt;/label&gt;</pre><pre>&lt;textarea asp-for=&quot;GalleryImage.Caption&quot; class=&quot;form-control&quot;&gt;&lt;/textarea&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group&quot;&gt;</pre><pre>&lt;p id=&quot;FilesToUpload&quot;&gt;&lt;/p&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;p id=&quot;FilesToUpload&quot;&gt;&lt;/p&gt;</pre><pre>&lt;/form&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;script type=&quot;text/javascript&quot;&gt;</pre><pre>function readURL(input) {</pre><pre>if (input.files &amp;&amp; input.files[0]) {</pre><pre>var reader = new FileReader();</pre><pre>reader.onload = function (e) {</pre><pre>$(&#39;#profile-img-tag&#39;).attr(&#39;src&#39;, e.target.result);</pre><pre>}</pre><pre>reader.readAsDataURL(input.files[0]);</pre><pre>}</pre><pre>}</pre><pre>function DisplayFilesToUpload() {</pre><pre>var element = document.getElementById(&quot;file&quot;);</pre><pre>var html = &quot;&quot;;</pre><pre>html = &quot;&lt;h3&gt;Upload to gallery&lt;/h3&gt;&quot;;</pre><pre>html += &quot;&lt;input type=&#39;submit&#39; class=&#39;upload&#39; value=&#39;Upload&#39;/&gt;&quot;;</pre><pre>document.getElementById(&quot;FilesToUpload&quot;).innerHTML = html;</pre><pre>readURL(element);</pre><pre>}</pre><pre>&lt;/script&gt;</pre><pre>&lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js&quot;&gt;&lt;/script&gt;</pre><p>The above code creates a form where a person can look for a file on their computer, select it and have it display a preview of it before clicking Upload.</p><p>Once you click upload, a <strong>HTTP POST</strong> request will be made and the <strong>OnPost()</strong> method will be executed in the <strong>ImageUploadForm.cshtml.cs </strong>file.</p><p>The form should look like this when finished.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gy7Tk44KZ4mosHfvN1OQIw.png" /></figure><p>That sums it up for the upload form. Let’s go on to creating a page to display all the images that have been uploaded.</p><h3>Creating A Gallery View</h3><p>Now that we have made it this far, let’s get some data back from our database and show it on a page.</p><p>Like we did for the upload form, create a new <strong>Razor Page </strong>and call it <strong>ImageGallery</strong></p><p>Then add a link to this page in the Navbar so we can access it from anywhere when navigating the site. Add it just like we added the upload form link to the Navbar.</p><p>Add these using directives in the <strong>ImageGallery.cshtml.cs </strong>file</p><pre>using System.Collections.Generic;</pre><pre>using System.Threading.Tasks;</pre><pre>using Microsoft.AspNetCore.Mvc.RazorPages;</pre><pre>using Microsoft.EntityFrameworkCore;</pre><pre>using PhotoUploader_Razor.Models;</pre><p>Add your fields, properties and constructor to initialize your context.</p><pre>private ApplicationDbContext _context;</pre><pre>public List&lt;GalleryImage&gt; GalleryImages { get; set; }</pre><pre>public ImageGalleryModel(ApplicationDbContext context)</pre><pre>{</pre><pre>_context = context;</pre><pre>}</pre><p>lastly, the <strong>OnGet()</strong> method</p><pre>public async Task OnGet()</pre><pre>{</pre><pre>ViewData[&quot;SuccessMessage&quot;] = TempData[&quot;SuccessMessage&quot;];</pre><pre>GalleryImages = await _context.GalleryImages.ToListAsync();</pre><pre>}</pre><p>If you look back at the <strong>OnPost()</strong> method of the <strong>ImageUploadForm.cshtml.cs</strong> file, notice where we added the <strong>TempData[“SuccessMessage”] </strong>snippet.</p><p>Now is when we finally get to use that data that we set on that form. When the <strong>ImageGallery </strong>page loads, we set any temp data to this pages <strong>ViewData[“SuccessMessage”]</strong>. In the HTML, we can display whatever message we set to this ViewData.</p><p>Also, since it was originally saved in <strong>TempData[“SuccessMessage”], </strong>when you refresh this page, TempData is cleared and the message will not appear again. Otherwise if we just saved it to ViewData in the first place, it would always persist and show a success message even if we didn&#39;t upload anything.</p><p>After that, we get all of the image data from the database and add it to the list <strong>GalleryImages. </strong>This is declared as a public property so we can access it from the <strong>ImageGallery.cshtml</strong> page.</p><p>And that’s it for the server side code.</p><p>Now for the client side of things.</p><p>Open up the <strong>ImageGallery.cshtml </strong>file and place this code snippet in there</p><pre>&lt;h2&gt;ImageGallery&lt;/h2&gt;</pre><pre>&lt;div class=&quot;row&quot;&gt;<br>&lt;div class=&quot;col-md-12&quot;&gt;</pre><pre>@*COMMENT: This is where we can check when the page loads if there is any data in ViewData[&quot;SuccessMessage&quot;]<br>If there is, show the message in bootstraps alert box*@</pre><pre>@if (ViewData[&quot;SuccessMessage&quot;] != null)</pre><pre>{</pre><pre>&lt;div class=&quot;alert alert-success alert-dismissible&quot; role=&quot;alert&quot;&gt;</pre><pre>&lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;alert&quot; aria-label=&quot;Close&quot;&gt;</pre><pre>&lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;</pre><pre>&lt;/button&gt;</pre><pre>&lt;strong&gt;@ViewData[&quot;SuccessMessage&quot;]&lt;/strong&gt;</pre><pre>&lt;/div&gt;</pre><pre>}</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;row&quot;&gt;</pre><pre>@*COMMENT: Here we loop through the models GalleryImages we got back from the database.<br>If the count is &gt; 0 show a thumbnail of the image and the caption that belongs to it.<br>If there arent any images, display a simple message stating so.*@</pre><pre>@if (Model.GalleryImages.Count &gt; 0)</pre><pre>{</pre><pre>foreach (var image in Model.GalleryImages)</pre><pre>{</pre><pre>&lt;div class=&quot;col-md-2&quot;&gt;</pre><pre>&lt;div class=&quot;thumbnail&quot;&gt;</pre><pre>&lt;a href=&quot;@image.URL&quot; class=&quot;thumbnail&quot;&gt;</pre><pre>&lt;img src=&quot;@image.URL&quot; alt=&quot;...&quot; width=&quot;600&quot;&gt;</pre><pre>&lt;/a&gt;</pre><pre>&lt;div class=&quot;caption&quot;&gt;</pre><pre>@*COMMENT: For the caption, we check if !null<br>Display the caption if there is one, otherwise display a message stating so*@</pre><pre>@if (image.Caption != null)</pre><pre>{</pre><pre>&lt;p&gt;@image.Caption&lt;/p&gt;</pre><pre>}</pre><pre>else</pre><pre>{</pre><pre>&lt;p&gt;No caption available for this image&lt;/p&gt;</pre><pre>}</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>}</pre><pre>}</pre><pre>else</pre><pre>{</pre><pre>&lt;h1&gt;No Images to display!&lt;/h1&gt;</pre><pre>}</pre><pre>&lt;/div&gt;</pre><p>And that’s it!</p><p>Notice that we can transition from C# code to HTML on the fly with <strong>Razor Syntax</strong>. This makes it incredibly easy to manipulate the HTML based on the data in the page model.</p><p>Run the project and go ahead and try uploading an image or two. If successful, you will be redirected to this page and it should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCOt-f0utUGXMJCh64IF1A.png" /></figure><h3>Conclusion</h3><p>I think we can all agree that creating this app was a pretty painless process.</p><p>Together we saw how to connect to a database and Azure storage, how to execute a migration, create Razor Pages, models, and leverage Razor Syntax to loop through our data and present it.</p><p>While it sounds like we did a lot, this is just the tip of the iceberg. There is so much more to ASP.NET Core Razor Pages; so I hope this guide gets you excited to learn more about this sweet tech and start making some exciting things!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d7aed97ce16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/davidrcwebdev/create-a-simple-photo-gallery-app-using-asp-net-9d7aed97ce16">Creating a Simple Photo Gallery App</a> was originally published in <a href="https://medium.com/davidrcwebdev">DavidReyes-Cairo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[David Reyes-Cairo]]></title>
            <link>https://medium.com/@dreyescairo/david-reyes-cairo-e1cfa693fea?source=rss-2446b4a1bb43------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1cfa693fea</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[about-me]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[David Reyes-Cairo]]></dc:creator>
            <pubDate>Thu, 03 May 2018 18:09:05 GMT</pubDate>
            <atom:updated>2018-05-03T18:20:27.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>Passionate Coder, Expert Hobbyist, Devoted Husband and Father</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*Z5E1d5rXkbt27A-Wbe-llA.png" /><figcaption>That’s me!</figcaption></figure><h3><strong>About David</strong></h3><p>Hey there! My name is David Reyes-Cairo and I make a living doing what I love; Coding. Of course, that isn’t all I do. When I am not coding, I am trying new things like playing the guitar, ukulele, gardening, woodworking, practicing photography, and … you get the point. Aside from all of my exciting hobbies, my beautiful Wife and I have 2 amazing kids who always make life rad. Coming home after a long day at work only to be stampeded by my kids (because they missed me, of course!) and kissed by my wife is pure bliss. I have it pretty good.</p><h3>The coding Bug</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3H9EqkN9RUW1TZD0Py9tA.png" /><figcaption>All the essentials to life</figcaption></figure><p>When I was about 11 years old we moved to Miami, Florida. I wasn’t really exposed to any code until I started High school.</p><p>I remember walking in to typing class when I noticed two seniors making designs for the new school website. I was fascinated by the process. I watched intently as they would write code and witnessed the website come to life with the click of the mouse.</p><p>After that, I was obsessed. I wanted to know how to do it, and quickly turned to books to learn how it all worked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*sS70eUV2W12sLHkoyAq5mw.jpeg" /><figcaption>This was definitely a page-turner</figcaption></figure><p>I would spend my time reading books, like “HTML For Dummies” and “Web Design In a Nutshell”. As technology advanced and the web became a place for rich media, I became increasingly entranced in the web and what made it tick.</p><p>Little did I know at the time, but the code bug infected me and it was there to stay.</p><p>I have always been keen on learning new things and applying what I learn. Without that attitude, I might not have ever taken on coding. To me, coding to me was a digital playground. As I progressed, I could literally think of anything I wanted to do on the computer and I would try making it. Dissecting live code was just as fascinating. I would always find myself looking at the page source of a website and just studying how it worked.</p><p>After many years of playing around with code, in 2014 I took a giant leap by turning what I love into a professional career. I started out by developing simple web apps in Adobe Flash and various other small projects that had been on the back-burner. <strong>I quickly learned the “ins and outs” of the company I work for and began to see a need that wasn’t being met.</strong> <strong>Innovation</strong>. We were using old, stale technologies instead of leveraging the power and ease of the newer <strong>Microsoft technologies like</strong> <strong>Asp.NET MVC 5, .NET Core, and Entity Framework</strong>. <strong>I made it my mission to better unify our codebase across the board and change the way we do things — for the better.</strong> Through my work experience, I have become proficient in writing <strong>clean, maintainable code as a full stack .NET developer</strong>. Aside from being a motivated coder, <strong>UX and bringing new ideas to the table are skills I am constantly developing.</strong> It is my ultimate goal that we as a company can provide the best experiences possible for our customers.</p><h3>The Rest of Me</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*YyGFVwyXaTaIL7SBBoSmFQ.jpeg" /></figure><p>Like I mentioned, coding isn’t all I like to do. I wear many hats (metaphorically speaking) and find myself rotating my hobbies and trying new things often. This keeps life exciting and fulfilling!</p><p>Just the other day I tried my hand at crochet and cross stitching. It’s definitely not as easy as some people make it look, but if I stick with it, it will become easy. Just like with anything in life, practice makes perfect.</p><p>My kids are always fascinated with everything that I do. It not only validates what I am doing, but it teaches them how to be self reliant and try new things. Nothing brings me more joy than seeing them learn and grow.</p><p>I am a firm believer that keeping busy and trying new things help open the mind. It is through your experiences that you gain perspective and the ability to think through problems; which in turn can help you in every aspect of your life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1cfa693fea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>