Skip to main content

Posts tagged with 'csadvent'

What is the C# Advent?

The C# Advents in 2018 and 2017 were so much fun. It's now time to sign up for 2019.

Just like last year, each day of the Advent calendar will have up to TWO blog posts. That means that there is a maximum of FIFTY slots! So, tell your C# friends and let's fill up this calendar.

A little history: I heard about the F# Advent Calendar, a tradition that's been carried on since 2010 (2014 in English). I think this is a great idea, and so I organized one for C#! (I asked Sergey Tihon for permission!). If you are running other developer advent calendars, just let me know and I will link to them here:

Let's Get Started

I need you to write a C# blog post, create a video, write an article, etc.

Here are the rules:

  1. Reserve a slot on Twitter (with hash tag #csadvent) or leave a comment on this post. You do not have to announce your topic until the day you reserve.
  2. Prepare your content (in English).
  3. Add a link in your content that links back to here, so that your readers may find the entire advent. You can host your content anywhere you'd like: your own site, dev.to, hackernoon, medium, wordpress, youtube, dzone, etc.
  4. Publish your content on the specified date. Your content must be related to C# in some way, but otherwise the content is completely up to you. I've posted a few ideas below to get your creativity flowing.
  5. Share your post on Twitter with hashtags #csharp and #csadvent

Below are all the slots, and who has claimed each date.

I will do my best to keep this up to date. The slots will be first come first serve. I also allowed last year's authors to get first crack. I will claim the last remaining spot for myself. I will prepare a post just in case someone has to drop out.

DateClaimed byContent
Dec 1, 2019 Brant Burnett Simon Painter  IAsyncEnumerable Is Your Friend, Even In .NET Core 2.x Hacking C#: Programming for the Truly Lazy
Dec 2, 2019 Luis Antonio Beltran Chris Ayers 2FA with Twilio Authy and C# (special guest: Xamarin) Dependency Injection, Architecture, and Testing
Dec 3, 2019 Kelson Ball Morgan Kenyon An Example of Partial Function Application in C# The Difference Between IEnumerable and IQueryable Explained
Dec 4, 2019 Ryan Overton Carl Layton Default Interface Methods in C#: Love 'em or Hate 'em? The Outbox Pattern in C#
Dec 5, 2019 Dave Cook Manuel Grundner To Null, or not to Null?!? The journey of porting pretzel to .NET Core
Dec 6, 2019 Lukáš Lánský Simon Timms Coverage-Driven Test Selection Machine Learning for Boring Applications
Dec 7, 2019 Chase Aucoin Kendall Miller Aurora Serverless with Entity Framework Core Better String Formatting with String Interpolation
Dec 8, 2019 Matt Eland Jeremy Sinclair Experimental C# with Scientist .NET Creating a Simple Wizard Component with Blazor
Dec 9, 2019 Meziantou Cecilia Wirén Thread-safe observable collection in .NET Overflow on integers - count with this security risk!
Dec 10, 2019 Andrew Lock James Hickey .NET Core, Docker, and Cultures - Solving a culture issue porting a .NET Core app from Windows to Linux Modular Monoliths And Composite UIs With .NET Core Razor Class Libraries
Dec 11, 2019 DotNetCoreShow Roman Stoffel The .NET Core Podcast - Episode 40 - Noda Time with Jon Skeet C# Loves Code Patterns
Dec 12, 2019 Brian Jackett James Curran Creating a C# Azure Function to Call Microsoft Graph Cleanup Scaffolded Code with modelbuild
Dec 13, 2019 Barret Blake Ed Charbeneau, Daniel Roth, Chris Sainty, Egil Hansen The Nightmare Before Blazor Getting Started with Blazor: All There is to Know From the Experts
Dec 14, 2019 Benjamin Howarth Martin Zikmund   A Christmas C# riddle
Dec 15, 2019 Jonathan Danylko Hilary Weaver-Robb 10 More Useful C# Extension Methods for 2019 Refactoring RestSharp Sample Tests to Make Them More Maintainable
Dec 16, 2019 Shahed Chowdhuri Ian Bebbington ASP .NET Core code sharing between Blazor, MVC and Razor Pages The Seven GUIs of Christmas
Dec 17, 2019 Joe Zack Chris Sainty Streaming process output to a browser, with SignalR and C# Introduction to Blazor Component Testing
Dec 18, 2019 Garo Yeriazarian Stuart Turner Vertically Sliced Command Line Tools in C# and .NET Core 3.1 Improving Code Readability with Linq (and MoreLinq)
Dec 19, 2019 Baskar Rao Stephen Lorello How to use Subscriptions in GraphQL C# Santa’s Nexmo Helper
Dec 20, 2019 Andrea Angella Layla 15 reasons why you should learn C# in 2020 Get off the naughty list with Twilio Autopilot, Azure Functions and Table Storage
Dec 21, 2019 Muhammad Azeez Patrick Lioi How do Object Relational Mappers (like Entity Framework) work? Patterns for using Entity Framework in C# 8
Dec 22, 2019 James Bender Eric Potter Refactoring for Testability – A Christmas Miracle! C# Strings with Ranges, and Indexes
Dec 23, 2019 Andrew Craven Lee Englestone Microservices and Outside-in Tests Using C# and Docker Compose Compiling Code without Visual Studio
Dec 24, 2019 Thomas Carpe Azmat Ullah Khan   PDF Digital Signatures with Itext7, Bouncy Castle and .NET Core
Dec 25, 2019 Mike Jolley Calvin Allen Adding HATEOAS to an ASP.NET Core API C# 8 is old news. Onward, to C# 9!

Alternates:

  • IF ALL FIFTY SLOTS FILL UP, please leave a comment or tweet with #csadvent anyway and I'll put you on this standby list:
  • Standby list:
    • Myself.
    • You, if you want to be.

Some ideas/topics to help inspire you:

  1. Blazor - C# for the browser
  2. Your latest open source contribution - show the community how you contributed and why
  3. Your favorite C# language feature - it doesn't even have to be a new feature, just blog about something you love about C#
  4. Introduce your favorite NuGet package / library. Even if it's a library you take for granted, not everyone has heard about it.
  5. How to avoid a pitfall you found with performance/memory/etc
  6. Integration/deployment of a C# application with Jenkins, Docker, Kubernetes, TeamCity, Azure, etc
  7. Write a "how to" for one of the many tools discussed in an episode of the Cross Cutting Concerns podcast or the DotNetBytes podcast
  8. Interview someone about C# and post the audio or a transcript.
  9. Implement a simplified example of a design pattern in C#

Thanks to everyone who is participating!

If you were an author of a C# Advent blog post in 2018, you get a chance to sign up earlier than the general public.

Tweet #csadvent or leave a comment below with the date you want to blog on. Each day has up to TWO slots. If someone has already claimed the day you want, that day may still be available.

The general call for C# Advent authors will go out soon, so please claim your dates as soon as possible. Just like last year, you do NOT have to pick a topic right now. If you DO want to pick a topic, I will pencil it in, but you are free to change it at any time up until the date you pick.

Last year's C# Advent was a success beyond anything I expected. I was worried that I wouldn't get enough sign-ups, but I ended up turning some people away. I was worried that people wouldn't get their blog posts done on time, but every single author delivered on time. I was worried there would be too much overlap in topics. There was a tiny bit, but every author's post had a unique, quality perspective, even if there was some overlap.

So, I'm doubling down this year! Each day of the Advent calendar will have up to TWO blog posts. That means that there is a maximum of FIFTY slots! So, tell your C# friends and let's fill up this calendar.

A little history: I heard about the F# Advent Calendar, a tradition that's been carried on since 2010 (2014 in English) and is still going strong in 2018. I think this is a great idea, and so I organized one for C#! (I asked Sergey Tihon for permission!). Other Advent calendars: C# Advent Calendar (in Spanish)Q# Advent Calendar.

So, I need you to write a C# blog post!

Here are the rules:

  1. Reserve a slot on Twitter (with hash tag #csadvent) or leave a comment on this post. You do not have to announce your topic until the day you reserve.
  2. Prepare a blog post (in English).
  3. Add a link in your blog post that links back to here, so that your readers may find the entire advent.
  4. Publish your blog post on the specified date. Your post must be related to C# in some way, but otherwise the content is completely up to you. I've posted a few ideas below to get your creativity flowing.
  5. Share your post on Twitter with hashtags #csharp and #csadvent

Below are all the slots, and who has claimed each date.

I will do my best to keep this up to date. The slots will be first come first serve. I also allowed last year's authors to get first crack. I have already claimed one of the December 25th slots for myself, but I can be persuaded to change if you really want that date.

DateClaimed byBlog Posts
Dec 1, 2018 Lukáš Lánský Steve Smith Namespacer: lightweight spin on architecture validation Double Dispatch in C# and DDD
Dec 2, 2018 Hilary Weaver-Robb Shahed Chowdhuri Can I Put All Of My Smoke Tests For A REST API In One Test? Yes! Your First Razor UI Library with ASP.NET Core
Dec 3, 2018 Bill Sempf Luis Antonio Beltran Insecure Binary Deserialization Azure Blob Storage with Xamarin.Forms
Dec 4, 2018 Tim Corey Matthew Jones How to Be a Great C# Developer Using Stopwatch and ContinueWith to Measure Task Execution Time in C#
Dec 5, 2018 James Hickey Calvin Allen Scalable Task Scheduling In .NET Core With Coravel Using .editorconfig in Visual Studio to create discoverable standards
Dec 6, 2018 Brant Burnett Isaac Levin A Restful Job Pattern For A C# Microservice Six Opinionated Tips to be a Better .NET Developer
Dec 7, 2018 Ryan Overton James Hickey Native API Access in Xamarin.Forms .NET Core Dependency Injection: Everything You Ought To Know
Dec 8, 2018 Carl Layton Shahed Chowdhuri Create Formatted Text Files With csvhelper Exploring .NET Core 3.0 and the Future of C#
Dec 9, 2018 Jeremy Sinclair Ian Russell Secure Data Access with IdentityServer4 and Xamarin Forms Expressing intent with value objects
Dec 10, 2018 James Curran Caleb Jenkins Here, There and Everywhere - A Simple Look at .NET Memory Model [?]
Dec 11, 2018 Andrew Lock Simon Timms Why is string.GetHashCode() different each time I run my program in .NET Core? Linked lists in C#
Dec 12, 2018 Ed Charbeneau Andres Paz Razor Components for a JavaScript-Free FrontEnd in 2019 Implementing a quantum simulator for Q# in C#
Dec 13, 2018 Amber Race Brian Jackett WireMock.Net Introduction to Calling Microsoft Graph from a C# .Net Core Application
Dec 14, 2018 Lee Englestone Daniel Oliver English Language Word Analysis With .NET OpenTracing and C#
Dec 15, 2018 Michael Eaton Kevin Griffin Exercises for Programmers – Weather Checker in C# Introduction to SignalR Streaming
Dec 16, 2018 Barret Blake Doug Mair Flow & Function Together Quick Introduction to C# Span
Dec 17, 2018 Gérald Barré (aka Meziantou) David Pine  Writing a Roslyn analyzer C# all the thing: .NET Core global tools
Dec 18, 2018 Duane Newman Caio Proiete Keeping Observable Collections Up To Date [?]
Dec 19, 2018 Jonathan Danylko Huzaifa Asif 10 More C# Extension Methods For The Holiday Season Create a custom middleware pipeline using .NET Core
Dec 20, 2018 Baskar Rao Eric Potter Testing .Net Core API using Auth0 with VS Tests The code changes in Roslyn between 7 and 8
Dec 21, 2018 Takayoshi Tanaka (vacated) Using Kubernetes readiness and liveness probes for health checks with ASP.NET Core 2.2 on OpenShift  
Dec 22, 2018 Jim Wilcox Chris Bohatka C# and WebAssembly Hit the Ground Running: Create a Starter Kit
Dec 23, 2018 Damian Łączak Chris Sainty An extension that I cannot code without. Blazor Toast Notifications using only C#, HTML and CSS
Dec 24, 2018 Chris Woodruff Gregor Suttie Getting the Most Out of Entity Framework Core - Part 1 Azure Blobs from C# and Visual Studio
Dec 25, 2018 Matthew Groves Calvin Allen Hangfire with ASP.NET Core C#, .NET, and Visual Studio - 2018 Year in Review

Alternates:

  • IF ALL FIFTY SLOTS FILL UP, please leave a comment or tweet with #csadvent anyway!
  • I will put you on this 'standby' list in case someone drops out or can't deliver their post in time.
  • Standby list:
    • Corstiaan Hesselink

Some ideas/topics to help inspire you:

  1. Blazor - now's your chance to experiment with writing C# for the browser
  2. Your latest open source contribution - show the community how you contributed and why
  3. Your favorite C# language feature - it doesn't even have to be a new feature, just blog about something you love about C#
  4. Introduce your favorite NuGet package / library. Even if it's a library you take for granted, not everyone has heard about it.
  5. How to avoid a pitfall you found with performance/memory/etc
  6. Integration/deployment of a C# application with Jenkins, Docker, Kubernetes, TeamCity, Azure, etc
  7. Write a "how to" for one of the many tools discussed in an episode of the Cross Cutting Concerns podcast
  8. Create a video tutorial and embed it in your blog post.
  9. Interview someone about C# and embed an audio player in your blog post.
  10. Implement a simplified example of a design pattern in C#

Thanks to everyone who is participating!

If you were an author of a C# Advent blog post in 2017, you get a chance to sign up earlier than the general public.

Tweet #csadvent or leave a comment below with the date you want to blog on. Note that this year, each day has up to TWO slots. So if someone has already claimed the day you want, that day may still be available.

The general call for C# Advent authors will go out next week, so claim your dates as soon as possible. Just like last year, you do NOT have to pick a topic right now. If you DO want to pick a topic, I will pencil it in, but you are free to change it at any time up until the date you pick.

Swashbuckle is a handy library to easily bring Swagger support to your ASP.NET Core (or ASP.NET) application. It is especially handy when developing an HTTP based API. It creates a form of interactive documentation based on the OpenAPI Specification.

Before diving into Swashbuckle: Merry Christmas! This blog is being posted on December 25th, 2017. It’s the final post of the very first C# Advent Calendar. Please check out the other 24 posts in the series! This event has gone so well, that I’m already planning on doing it again in 2018. Thank you, again, to everyone who participated (whether you are a writer or you’ve just been following along).

The full source code used in this example is available on Github.

ASP.NET Core HTTP API

I’m going to assume some level of familiarity with ASP.NET Core and creating a REST API. Here’s an example of a GET and a POST. These endpoints are reading/writing from a JSON text file (in a way that is probably not thread-safe and definitely not efficient, but it’s fine for this example).

public class ValuesController : Controller
{
    [HttpGet]
    [Route("api/teams")]
    public IActionResult GetTeams()
    {
        var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
        var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
        return Ok(teams);
    }

    [HttpPost]
    [Route("api/team")]
    public IActionResult PostTeam([FromBody]Team team)
    {
        var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
        var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
        teams.Add(team);
        System.IO.File.WriteAllText("jsonFile.json",JsonConvert.SerializeObject(teams));
        return Ok(team);
    }

    // etc...

To try out the GET endpoint, the simplest thing I can do is open a browser and view the results. But to try out the POST endpoint, I need something else. I could install Postman or Fiddler (and you should). Here’s how that would look.

Postman

Postman is great for interacting with endpoints, but Postman alone doesn’t really tell us anything about the endpoint or the system as a whole. This is where Swagger comes in.

Swagger

Swagger is a standard way to provide specifications for endpoints. Usually, that specification is automatically generated and then used to generate an interactive UI.

We could write the Swagger spec out by hand, but fortunately ASP.NET Core provides enough information to generate a spec for us. Look at the PostTeam action above. Just from reading that we know:

  • It expects a POST

  • The URL for it is /api/team

  • There’s a Team class that we can look at to see what kind of body is expected

From that, we could construct a Swagger spec like the following (I used JSON, you can also use YAML).

{
	"swagger": "2.0",
	"info": { "version": "v1", "title": "Sports API" },
	"basePath": "/",
	"paths": {
		"/api/team": {
			"post": {
				"consumes": ["application/json"],
				"parameters": [{
					"name": "team",
					"in": "body",
					"required": false,
					"schema": { "$ref": "#/definitions/Team" }
				}]
			}
		}
	},
	"definitions": {
		"Team": {
			"type": "object",
			"properties": {
				"name": { "type": "string" },
				"stadiumName": { "type": "string" },
				"sport": { "type": "string" }
			}
		}
	}
}

But why on earth would you want to type that out? Let’s bring in a .NET library to do the job. Install Swashbuckle.AspNetCore with NuGet (there’s a different package if you want to do this with ASP.NET).

You’ll need to add a few things to Startup.cs:

In the ConfigureServices method:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Sports API", Version = "v1"});
});

In the Configure method:

app.UseSwagger();

Aside: With ASP.NET, NuGet actually does all this setup work for you.

Once you’ve done this, you can open a URL like http://localhost:9119/swagger/v1/swagger.json and see the generated JSON spec.

Swagger spec in JSON

Swagger UI with Swashbuckle

That spec is nice, but it would be even nicer if we could use the spec to generate a UI.

Back in the Configure method, add this:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sports API v1");
});

Now, open your site and go to /swagger:

Swagger UI generated by Swashbuckle

Some cool things to notice:

  • Expand/collapse by clicking the URL of an endpoint (note that you must use Route attributes for Swashbuckle to work with ASP.NET Core).

  • "Try it out!" buttons. You can execute GET/POST right from the browser

  • The "parameter" of the POST method. Not only can you paste in some content, but you get an example value that acts like a template (just click it).

Giving some swagger to your Swagger

Swagger and Swashbuckle have done a lot with just a little bit. It can do even more if we add a little more information in the code.

  • Response: The ProducesResponseType attribute will let Swagger know what the response will look like (this is especially useful if you are using IActionResult and/or an endpoint could return different types in different situations).

  • Comments: If you are using XML comments, you can have these included with the Swagger output.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Sports API", Version = "v1" });
    var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "swashbuckle-example.xml");
    c.IncludeXmlComments(filePath);
});

(Also make sure you XML Documentation output for your project enabled)

Here’s an example of a GetTeams method with both XML comments and ProducesResponseType:

/// <summary>
/// Gets all the teams stored in the file
/// </summary>
/// <remarks>Baseball is the best sport</remarks>
/// <response code="200">List returned succesfully</response>
/// <response code="500">Something went wrong</response>
[HttpGet]
[Route("api/teams2")]
[ProducesResponseType(typeof(Team), 200)]
public IActionResult GetTeams2()
{
    var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
    var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
    return Ok(teams);
}
  • Customize your info: there’s more to the Info class than just Title and Version. You can specify a license, contact, etc.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info
    {
        Title = "Sports API",
        Version = "v1",
        Description = "An API to list and add sports teams",
        TermsOfService = "This is just an example, not for production!",
        Contact = new Contact
        {
            Name = "Matthew Groves",
            Url = "https://crosscuttingconcerns.com"
        },
        License = new License
        {
            Name = "Apache 2.0",
            Url = "http://www.apache.org/licenses/LICENSE-2.0.html"
        }
    });
    var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "swashbuckle-example.xml");
    c.IncludeXmlComments(filePath);
});

Here’s a screenshot of the UI that has all three of the above enhancements: response type, XML comments, and more customized info.

Swagger with more swagger

Summary

Working on HTTP-based APIs? Bring Swashbuckle and Swagger into your life!

More resources:

Thanks again for reading the 2017 C# Advent!

Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter