Create Your Own .NET Core Templates in 4 Easy Steps

Do you ever develop prototypes, or starter projects/accelerators, that you’d like to use again in the future? A good way to do that is by creating custom templates for dotnet. Once completed, anytime you want to create a new project of that type in the future, you can use key in “dotnet new ” and you’re off, complete with correct namespaces. You can even do conditional checks, or variable replacements.

1. To start, clone or download the MyGameStartup project which will make following along easy. There is nothing special about this, it’s just for the purposes of showing how you can bundle multiple projects, and do some variable replacements. Note: You’ll need .NET Core 2.1 SDK for this at a minimum. Once open, you’ll see a solution file, and a few simple projects with some basic Entity Framework Core behavior.

2. Note that in the downloaded project, there is a folder labeled “.template.config” with a file inside it labeled “template.json”. Let’s review the contents of that file. Feel free to update this file with values you plan to use for your own project type, but you can leave these if you want to just continue with the demo.

I’ve added comments to the file so it is easy to understand, along with a link to the official documentation. There are more features than I am covering here if you wish to add them. A few noteworthy settings in the file are the “shortName” property. This is the trigger for your project, i.e. ‘dotnet new mygamestartup’. Also, if you see the section labeled “symbols”, and then cross-reference this with the projects ‘appsettings.json’ file, you’ll see the connection string’s database will be replaced with the “–db” parameter once we run it.

3. Ready to add this new project type to your available list? I’ll also show you how to remove it if you no longer plan to use this one. Run the following command, from the same folder as the downloaded .sln file and .template.config folder: “dotnet new -i .”. The dot here refers simply to the current directory. You could have also specified the path, but this is easier. If successful, you should see a list of project types, along with your project type added.

New project added screenshot from ConEmu terminal

Woohoo! You now have your own custom accelerator template you can use for other projects. Side note: This screenshot is from the ConEmu terminal which I use. You can download it here.

An important note also on this step. Running the “dotnet new -i .” command will bundle the current folder. I may not have discovered the setting yet, but keep in mind this skips empty folders. So if your wwwroot folder was empty, you will see this is not created after installing. I added a site.css to my version to avoid this.

4. We’re moving along quickly now. Next step… fire up a new project with our new template! Navigate the directory you’d like your project to be a folder within, such as “C:\Users\myusername\source\repos” and then issue the command, “dotnet new mygamestartup –db MyCustomStartupDB -n MyCustomName“. The database name will be set in the connection string in appsettings.json and a folder will be created named MyCustomName. Your projects namespace will also be MyCustomName. Note: If you get an error about a lock, be sure your Visual Studio instance with “MyGameStartup” project you downloaded in step 1 is closed. You may need to remove the MyCustomName folder and try again.

Follow the steps in the README to create the database with the name you specified, and also steps on how to run the Entity Framework Core Update-Database command properly. After that, you’re done! You just created a new project from a template you previously created.

Optional: To Uninstall the project, you can use the “dotnet new -u” command to list the currently installed projects. You should see your “MyGameStartup” project listed here. You can simply remove it with the command “dotnet new -u “Path-To-Folder” such as shown below.

Next Steps: A few steps I haven’t taken yet, but may in the future, is to add the following features to my template:

  • Create a nuget package to easily distribute your new package.
  • Add a new ‘symbol’ to the template.json which has datatype ‘choice’. A choice symbol will allow the user to pick from several options when creating your template.
  • Modifiers can be used to conditionally output certain code or not. You may wish to optionally include authentication as an example. More details here.
 

Exploring Video Games With the New IHttpClientFactory In .NET Core 2.1

REST services are everywhere. It’s tough to find an application that doesn’t leverage an externally hosted REST service in some way. Prior to .NET Core 2.1, a common library that was used to perform REST requests was RestSharp. I love RestSharp, but let’s explore the new alternative IHttpClientFactory that became available as part of .NET Core 2.1.

In this demo, we’re going to cover a bunch of awesome features:

  • Simple dependency injection
  • Named instances
  • Typed clients
  • Message handlers

In addition, for this service, we’re going to leverage the Internet Game Database API to pull in some data about Nintendo Switch games. As an aside, if you don’t already own a Nintendo Switch, it’s a fantastic device for the family, for travel, or just for fun. If you want to follow along with the code, you’ll need to create a free account here. Once you have your API key, you’ll want to be sure to include that in the code. There is a host of functionality available with this API, and you could use it to start building your video game collection, embed information about games in your apps, and much more.

You may also wish to download the source code for this. It is available on Github here.

Basic Usage

To start, let’s open Visual Studio 2017 and create an ‘Empty’ project denoting ASP.NET Core 2.1 as the framework.

Once we’re up and running, let’s add a few lines to our Startup.cs class. It should look like this when we’re done. Specifically, note the new services.AddHttpClient(); extension method on IServiceCollection which is exposed in 2.1.

Next, let’s create a GameController and a Game class for the purposes of deserialization. Notice how we inject the IHttpClientFactory into the controller constructor? We then use the CreateClient() method of the factory inside the controller action to create a basic instance. A noteworthy feature for IHttpClientFactory is that it maintains a pool of reusable clients, each with a lifetime of 2 minutes by default. This keeps the overhead involved with connectivity and instantiation at a more manageable level by default which is great for our overall performance and scalability.

Named Instances

In the above code, we are defining the HttpClient inside the controller class, but it’s also possible to have a “named” instance of the HttpClient. We could re-write our line from our Startup.cs class above to use this code instead:

Then, inside our controller, we would inject the IHttpClientFactory the same way, but we would change the CreateClient() method to use our named instance.

Typed Clients

Cool stuff so far, right? Let’s take it one more step further: typed clients. Let’s add the interface and class below to our application. Note how we have a private HttpClient as part of our IgdbClient object which exposes developer friendly names for each of the Igdb.com API endpoints we can consume in our application. Note: There are plenty more fields available in this API, including artwork, screenshots, and more but we are just keeping it simple for the demo.

Finally, let’s modify our Startup class to inject our configured client for our application, and also modify our GameController class so that it exposes these two new methods for testing purposes. We’re configuring the Startup class to inject our application specific configuration (so we can distribute this class to other applications which each have their own API key, and we’re also injecting IgdbClient this into the controller.

Message Handlers

The last feature we’re going to discuss is message handlers. Handlers can be attached to clients to monitor messages as they go in, or messages as they go out. You could perform logging for messages or duration, request validation, and more. Handlers can be chained as middleware as well. We’re going to keep it simple for our demo, and simply verify that the user-key which is required for the Igdb.com API is specified for the request before it goes out for our application. Let’s add the following class to our app:

Let’s also modify our Startup class, specifically the ConfigureServices method so that the following appears after we registered our IgdbClient.

Now, if we try to call the /game/id or /game/popular endpoints without having specified our user-key, this will result in a 400 Bad Request error before it is even attempted to be sent to the Igdb API. This potentially saves us API usage limits and cost as well as improves our performance by failing before the attempt is made.

 

Adding AppSettings.json Configuration to a .NET Core Console Application

This post will walk you through the steps necessary to add a strongly typed appsettings.json configuration file to your console application. I’ll dispense with the formalities of writing a detailed introduction on why you would be interested in doing this and jump right into the steps involved.

Note: This post assumes .NET Core 2.1, but I believe any 2.x version will work.

1. Add the following NuGet packages to your console application:

2. Right-click your console application, and select “Unload project“. Once the project has been unloaded, right click the project and select “Edit <your_console_project_name>.csproj“.

3. Add the following just below the <TargetFramework> element:
<UserSecretsId>93d033dc-12eb-446a-91a6-efec88dfb437</UserSecretsId>
(note: you should replace this guid with your own)

4. Add the following to a <ItemGroup> with other CliToolReference elements, or add your own:

5. Right-click your console application and select the “Reload project” option.

6. Open the developer command prompt and navigate to the directory with your console application, then run:

Note: This will create a secrets.json file located at: %APPDATA%\Microsoft\UserSecrets\<SecretId_From_Step_3>\secrets.json
Edit the newly created file and change the contents to:

7. Create a new JSON configuration file for your console application and name it appsettings.json. Set the following to the contents of the file to the JSON below. Important: Be sure to right-click this file and select properties. Change the “Copy to Output Directory” option to “Copy if newer”.

8. Create a class named MySettingsConfig:

9. Add the following code to your Main routine inside Program.cs

If your console shows your settings correctly, congratulations! If you’re missing the AccountName and ConnectionString settings, be sure you followed the step to “Copy to Output Directory” listed in step 7.

 

Setting Up A React & Web API Development Environment in Visual Studio 2017

Front-end frameworks like React, Angular, and Vue are making big waves in software development. Microsoft makes great tooling for working with JS frameworks like those in the form of Visual Studio Code. There is also a large trove of information and tutorials getting setup inside the VS Code environment. One specific resource I really appreciated was Cory House’s Pluralsight course on setting up a JS development environment.

Unfortunately, at least in my experience, there isn’t much available out there on how to setup a React dev environment using Visual Studio 2017, for those of us who wish to use only a single editor to maintain our .NET applications. My hope is, that the rest of this guide will serve as a useful resource for anyone else who is facing this same impediment to getting started and will end up saving them time.

Some pre-requisites before we get started:

Disabling Package Restore in Visual Studio

Visual Studio tries to take care of a number of things for you when dealing with npm pacakges. Some people prefer this, other’s don’t. I fall into the latter camp. It took me a bit of headache to figure this out, but by default, when you save a packages.config file, Visual Studio attempts to run ‘npm update’ for you automatically when you save the file or open the solution. So, if you are trying to run the command yourself after updating packages.config, then you are going to run into file locks with the /node_modules/ folder.

Thankfully Visual Studio offers you a way to disable the automatic updates when saving packages.config. Navigate to Tools > Options, then to Projects and Solutions > Web Package Management > Package Restore and set the following settings for NPM (below). What this does is prevents npm from being executed every time you open a project, or run a command line ‘npm update’/’npm install’. You can leave these on if you wish, but for me I found the experience better by being able to execute the npm command line syntax myself.

Setting Up The Application

Instead of walking you through line by line of each step you need to follow, please download the sample application from Github. There are a few important areas that I think are worth mentioning.

  • If you changed the package restore settings above, you’ll want to run “npm install” inside each project after cloning.
  • The ‘Empty’ solution assumes the webpack-dev-server for hosting, so when you run ‘npm start’, webpack will host a simple webserver at the port listed in webpack.config.js.
  • The ‘MVC’ solution assumes it will be hosted by IIS Express or the built in webserver. The ‘npm start’ command on this application will actively watch for JS file changes and rebundle them for you. No need to recompile to see your changes unless you something managed by .net.
  • This approach does leverage Babel as the transpiler. If you would like to use TypeScript, you could do that as well.
  • The webpack configuration assumes that the application start/root is /ClientApp/index.js.
  • The webpack configuration also assumes that everything is written to the /wwwroot/ folder as is convention with ASP.net Core projects in Visual Studio 2017.

I hope you find this post useful. It took me a bit of searching to figure some of this out since most tutorials focus on Visual Studio Code. Feel free to reach me on twitter if you have questions about any of this. Happy programming.

 

Generate Test Data With Faker.js

Here is a common scenario for you. You’re building an application… any application. It could be your side project, a sales tool, an ecommerce site, a REST api, a video game, a reporting dashboard. Anything. You’re building your app, and you reach a point that you’d like to try it out, to see how it would look to a user. How do you simulate a production scenario with no data to test with? If you’re lucky, you have data from an existing customer you can use, or there is a sample dataset available online. If you’re unlucky, you’re left generating dummy data using garbage inputs (random strings, random numbers, etc) – data that passes the regex, but doesn’t provide a good simulation.

Do you wish there was a library that allowed you to programatically generate test data? Enter Faker.js. Faker.js allows you to generate a variety of data types in an intelligent and structured way. You can generate: Addresses, Products (Ecommerce), Companies, Dates, Images, URLs, and random objects as well (numbers, strings, words, uuid, etc). Click here to see a demo.

If you’d like to consume data from faker in another programming language, such as c#, you could use their hosted microservice at http://faker.hook.io (i.e. http://faker.hook.io?property=name.findName&locale=de). A second option would be Bogus, a port of Faker for .net. There are ports available for other languages as well and the API surface is roughly the same in each instance.

I setup a very simple Github repo that demonstrates how to use Faker in a variety of scenarios to help you accomplish your goals. Hopefully you find this utility as useful as I do for prototyping new functionality before it goes into production.

 

My Favorite Visual Studio Shortcuts and Tips

Hey everyone – I’ve been maintaining a list of little shortcuts to save me time and ease my development efforts and figured they would be worth sharing here. If you have any you would like to share here, please email me and I’ll include them as well.

Visual Studio Keyboard Shortcuts

  • Ctrl+. opens up the ‘Smart Tag’. Use it when you see the red squiggle line to add a missing reference, or implement an interface.
  • Ctrl+K,C will comment either the current line, or any block of code you have highlighted.
  • Ctrl+K,U will uncomment either the current line, or any block of code you have highlighted.
  • Ctrl+, opens smart search to quickly find and jump to a class or method name.
  • Ctrl+I allows you to do an inline search (basically search quickly without dialog box)
  • Shift+Alt+Enter for enter and leave full screen mode.
  • Ctrl+- moves cursor to last known position (helpful to navigate back, Ctrl+Shift+- is forward)

Visual Studio Features

  • Snippets, like ‘prop‘ will inject a property into your code, or ‘foreach‘
  • Custom snippets, click here for a starter list and how-to.
  • Right-click file in Solution Explorer, select Source Control > Annotate. This shows all history of the file and who checked in what line of code.
  • Use ‘Package Manager Console’ to install Nuget packages (Alt+T,N,O). (ex: PM> Install-Package Newtonsoft.Json)
  • Tell debugger to ‘break’ when an exception is thrown even if no breakpoint exists (Ctrl+Alt+E, then check Thrown on CLR).
  • From Visual Studio Command prompt, use this command to get a list of all checked out files (and to who): tf status /collection:http://my-tfs-server:8080/tfs/MyCollection $/pathto/mytfsproject /user:* /recursive
 

Techniques For Improving Website Performance

Annotated below is a presentation from Nik Molnar, co-founder of the open source debugging and diagnostics tool Glimpse, who demonstrates several different strategies for improving the performance of your web application. This is easily one of the most useful conference presentations I have ever seen and I wanted to share it with everyone. If were curious about how to do any of the following tasks, this presentation will cover those for you. Next to each point is a bookmark for you to jump to that portion of the presentation.

  • Using browser tools to analyze usable content and latency for each request [13:00]
  • How to use HAR files for analyzing performance metrics [14:30]
  • Using the ‘Audits’ tab in Chrome to make recommendations [15:40]
  • Adding Google PageSpeed to the browser tools and how to use it [16:45]
  • Specifying in the web.config how to use compression for static and dynamic files. [17:50]
  • How to enable client side caching with the expires header [19:00]
  • How to use bundling in ASP.NET to bundle and minify CSS and JS files. [19:35]
  • How to use Web Essentials Visual Studio plugin to easily do image sprites [20:40]
  • Using TinyPNG.com to optimize PNG images with lossy compression [22:00]
  • Using Web Essentials to embed small images as base64 encoded text in CSS [24:22]
  • Using async script attribute and img lazyload attribute to lazy load resources [26:19]
  • Pre-caching client data using dns-prefetch, prefetch, and prerender HTML tags [28:30]
  • Using the RedGate CPU profiler to identify bottleneck code (note: Visual Studio has a simpler built in feature) [35:00]
  • High level thoughts on how to improve server side performance [35:55]
  • Using browser tools like Octane to profile Javascript CPU performance [38:30]
  • High level thoughts on how to improve javascript performance [42:25]
  • Understanding frame rates and the concept of jank [44:05]

Resources:
Link to the video in it’s entirety
Link to baseball demo site used in presentation

 

ThatConference 2014

For the past three years, a group of very smart and very generous people, have hosted a wonderful summer camp themed conference in Wisconsin titled ‘That Conference’.   It’s hosted at a giant indoor/outdoor waterpark and convention center, Kalahari Resorts.  The number and quality of the sessions is impressive, and may shock you a bit when you consider the entire ticket cost is currently under $400.

Most of the presentations I attended were put on by Microsoft MVPs, people who are recognized by Microsoft as leaders in the community and have demonstrated a strong ability to teach and inform others about the technology stack.

Each day starts off with a keynote.  Day 1 was Elizabeth Naramore,  who artfully spoke about how destructive FUD (fear, uncertainty, and doubt) can be.  Day 2 was Tim Huckaby, a long time Microsoft collaborator  turned entrepreneur and founder of Interknowlogy, who spoke on the importance of design.  Day 3 was Mike Mcgee, who is the co-founder of Starter League, a rapid learning school hosted in Chicago.  Mike gave us his inspiring story of how he took risks, turned down offers, and maintained a focus on his business until it reached success.

Some of the favorite talks I participated in were:

SDK for your API by Wade Wegner

Understanding OWIN by Keith Dahlby (author of Posh Git)

RavenDB for the .NET Developer by Judah Himango

ORMs – You’re doing it wrong by Jimmy Bogard (founder of Automapper)

Building a Flexible Client API Library by Darrel Miller

Full Stack Web Performance by Nik Molnar (co-founder of Glimpse)

In addition to all the wonderful technical presentations, there were great opportunities to meet other like minded individuals.  There was a meet & greet for early check-in attendees, a happy hour with great food the first night, a full pig roast the second, and plenty of chances to interact and reflect on the final day.

Generous sponsors brought technology for everyone to experiment with.  Omni Resources brought an Oculus DK2 which I thought was amazing, Skyline Technologies made a flappy bird clone that utilized the Kinect to wave your arms to move, another company brought Google Glasses for people to try.   All the sponsors were developer focused, knowledgeable, and polite to the “campers”.

ThatConference will be 8/10/15 to 8/12/15 next year and I already have it noted on my calendar.

 

Create a push notification system with SignalR and Toastr

Do you have events in your application that you would like to trigger a notification to other users? How about if a user places an order on a website and you want the website administrator to see a notification, or a sale on Apple products is initiated and you want to notify customers?

Note: If you wish to download the code to follow along instead of going step by step, you may download it on Github here.

SignalR is a library for .NET that enables real-time communication. It does this via web-sockets, which is typically available in modern browsers, but also degrades gradually to other methods that are supported by the older browsers. You just need to worry about the SignalR framework not the underlying architecture. Toastr is javascript framework for non-blocking notifications. With just a few lines of code you can get a nice popup system in place.

Let’s walk through the steps, it’s not too difficult.

1. Create a new MVC project in your favorite language, I’ll be using C#. I disable user authentication and name it ‘SignalrToastr’ but you can name it whatever you would like.

2. Open ‘package manager console’ for your application, and install the SignalR package.

3. Create a class file named ‘Startup.cs’ and place it in the root of your application. Give the following contents to your new file. This file is an Owin startup file, which is outside the scope of this discussion, but is worth noting as Owin will become a larger part of ASP.NET vNext. It is a middleware framework that resides outside of IIS. Microsoft also uses Owin for the ‘Individual Accounts’ user manager, so if you left user authentication enabled in step #1, you can simply add the ‘MapSignalR’ line below to the Startup.cs class it created for you.

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalrToastr.Startup))]
namespace SignalrToastr
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

4. Create a folder called ‘Hubs’ and add a file named ‘ContactHub.cs’. Enter the following contents into the file.

using Microsoft.AspNet.SignalR;

namespace SignalrToastr.Hubs
{
    public class ContactHub : Hub
    {
        public void ContactFormSubmitted(string name, string message)
        {
            // Calls the 'notifyUsers' method on the client side.
            //  Note:  You can change 'All' to target only certain clients.
            //  Note:  Code after 'All' is dynamic, and you can specify whatever name you wish.
            Clients.All.notifyUsers(name);
        }
    }
}

SignalR uses ‘Hub’ objects to communicate between the client and the server. We will go over more on what is actually happening here in a later step. For now, you should note that ‘ContactFormSubmitted’ is a method being called on the server, from the client. The client passes this server method two parameters, name and message. This server side method then notifies ‘All’ clients to execute a JS method named ‘notifyUsers’ which takes one parameter, name. Outside the scope of this tutorial is how you can narrow down which clients you want to send the message to.

5. Modify the ASP.NET templated view that comes installed ‘~/Views/Home/Contact.cshtml’ and replace it’s contents entirely with the following:


<form class="form-horizontal">
    <fieldset>

        <!-- Form Name -->
        <legend>Contact</legend>

        <!-- Text input-->
        <div class="control-group">
            <label class="control-label" for="txtName">Name</label>
            <div class="controls">
                <input id="txtName" name="txtName" type="text" class="input-medium">

            </div>
        </div>

        <!-- Textarea -->
        <div class="control-group">
            <label class="control-label" for="txtComments">Comments</label>
            <div class="controls">
                <textarea id="txtComments" name="txtComments"></textarea>
            </div>
        </div>

        <!-- Button -->
        <div class="control-group">
            <label class="control-label" for="btnSubmit"></label>
            <div class="controls">
                <button id="btnSubmit" name="btnSubmit" class="btn btn-primary">Submit</button>
            </div>
        </div>

    </fieldset>
</form>


@section scripts
{
    <script src="~/Scripts/jquery.signalR-2.0.3.js"></script>
    <script src="~/signalr/hubs"></script>    
    <script type="text/javascript">
        $(function() {
            var contact = $.connection.contactHub;

            // Callbacks to the client should be defined here.
            contact.client.notifyUsers = function (name) {
                
            };

            $.connection.hub.start().done(function() {
                // Calls to server should be included within the hub.start() method.
                $('#btnSubmit').click(function() {
                    // Call the ContactFormSubmitted method on the hub.
                    contact.server.contactFormSubmitted($('#txtName').val(), $('#txtComments').val());
                    // Clear text boxes and reset focus for next comment.
                    $('#txtName').val('');
                    $('#txtComments').val('');
                    return false;  // prevent 'form' from submitting.
                });
            });
        });
    </script>
}

This creates a simple two field bootstrap form, and also adds our required JS includes to make SignalR work (jquery.signalR-*, and ~/signalr/hubs). It also creates a placeholder for our client callback notifyUsers, and also adds an event handler for our contactFormSubmitted method to push to the server. If you build your solution at this point and open your browser to your projects location for /signalr/hubs/ (i.e. http://localhost:62279/signalr/hubs/) you’ll see some generated JS markup that SignalR created based on your hub. Note how it lower cases your hub name, and methods. This is what the SignalR framework is creating for you automatically based on your Hub classes.

        proxies.contactHub = this.createHubProxy('contactHub'); 
        proxies.contactHub.client = { };
        proxies.contactHub.server = {
            contactFormSubmitted: function (name, message) {
                return proxies.contactHub.invoke.apply(proxies.contactHub, $.merge(["ContactFormSubmitted"], $.makeArray(arguments)));
             }
        };

6. Repeat step #2, but install the Toastr framework.

7. Add the toastr.css file to either the top of Contact.cshtml or to your Layout.cshtml file:

<link href="~/Content/toastr.css" rel="stylesheet" />

8. Modify your scripts section of Contact.cshtml to look as follows. Note how we have added a reference to taostr.js and also placed the toastr.info call inside our notifyUsers callback method.

 <script src="~/Scripts/toastr.js"></script>
    <script src="~/Scripts/jquery.signalR-2.0.3.js"></script>
    <script src="~/signalr/hubs"></script>    

    <script type="text/javascript">
        $(function() {
            var contact = $.connection.contactHub;

            // Callbacks to the client should be defined here.
            contact.client.notifyUsers = function (name) {
                toastr.info('New contact form submitted by ' + name);
            };

            $.connection.hub.start().done(function() {
                // Calls to server should be included within the hub.start() method.
                $('#btnSubmit').click(function() {
                    // Call the ContactFormSubmitted method on the hub.
                    contact.server.contactFormSubmitted($('#txtName').val(), $('#txtComments').val());
                    // Clear text boxes and reset focus for next comment.
                    $('#txtName').val('');
                    $('#txtComments').val('');
                    return false;  // prevent 'form' from submitting.
                });
            });
        });
    </script>

9. You are done at this point, so let’s try it out. Open two different browsers side-by-side, I’ll be using Chrome and Firefox. This is done to show you how the server is making a callback to ‘All’ clients as shown in step #4. You can narrow this down in the future if you want, to only administrative users for example. If all goes well, you should be able to fill the form out in one browser, and see the popup in both.

toast-notification

 

Create custom NuGet packages and host your own Nuget repository

In this tutorial, we’ll cover some basics on how to create a Nuget package. We’ll also look at a way to host your own private Nuget repository. To complete the tutorial, you’ll need to download the NuGet.exe command line utility.

Note: You should consider putting this utility in your system path. I have a dropbox folder on all my machines C:\Users\Kyle\Dropbox\Utils that I put command line utilities in, and then update the PATH variable for my machine.

1. Start by creating a folder for your NuGet packages. I recommend C:\Users\your_username\.nuget (if you create this folder in explorer, it may complain if you don’t name the folder “.nuget.” with the trailing period. Explorer will strip off the trailing period when it’s created).

2. Download the .zip sample project here, and unzip it into a subfolder with the name of the Nuget package you wish to create (i.e. \.nuget\NugetDemo\)

3. You’ll see folders here for /content/ and /lib/.

/content/ – any files here simply unzip into the root of the project, so anything you put here will dump as is to the project the package is being added to. You just match the structure you want to have it unpack into and Nuget will unzip it into your package accordingly. The example from #2 uses a ‘Controllers’ and ‘Views’ folder from an sample C# MVC project. The root content folder also contains a web.config.transform. The changes in .config.transform files are added to the matching .config file in the project. In this example, I have an appsettings key I am adding.

/lib/ – contains your binary files you want to include in subfolders based on framework version. In the example from #2, I have a .NET 4.5 (net45) subfolder, and a dll called Utils that I am packaging in. This will be added to my project as a referenced dll when I install the Nuget package. Utils just contains some sample extension methods which are used in the Controller and View from /content/.

/tools/ – (not included, but could be here if necessary) is for powershell scripts you wish to have executed automatically at installation time. I haven’t included any in this sample, but there is plenty of documentation out there on Powershell and what can be done with Nuget packages.

readme.txt – this file is in the root folder and is opened automatically (but not added to the project) when the package is installed.

4. From the root folder (the one with readme.txt) run the command ‘nuget spec MyPackageName’. This will create a file named MyPackageName.nuspec. Note: Be sure Nuget.exe is added to your %PATH% variable as noted earlier

5. Open and analyze MyPackageName.nuspec. This file contains information about your package (Author, License URL, Version, Project URL, License, Copyright, and Dependencies). Go ahead and delete the ‘Dependencies’ element and update the rest of the information to match how you would like it to look.

6. After you finish updating the MyPackageName.nuspec, run the command (from the same directory as #4) ‘nuget pack’. This will create your Nuget package. Congratulations, you just wrote your first Nuget package! To make the next step simpler, move the newly created .nupkg file and place it in the ‘C:\Users\your_username\.nuget\ folder.

7. Inside Visual Studio, select “Tools > Nuget Package Manager > Package Manager Settings’. Then select “Package Sources” and use the “+” icon to add a new source. Attached is a screenshot of how I have added my own person Nuget repository.

personal-repo

8. Now, create a basic C# MVC application. Right click your new web project and select “Manage Nuget Packages”. You see your source on the left rail. Go ahead and add your package you created from step #6. Note that ‘Controllers’ now has an ‘Extensions’ subfolder, ‘Views’ now has an ‘Extensions’ subfolder, Web.config has an AppKey named ‘ExtensionsKey’ and your project has a reference named ‘Utils’ that was not there before. Also, a file called “readme.txt” showed up in your solution explorer although it was not added to your project.

add-nuget-package

9. If you debug/run your application and head to the Url /extensions/strings/ you’ll see that the Extensions controller action ‘Strings’ will execute, leveraging the namespace/dll Utils to present some information. Congrats!