Warning: Cannot use bool as array in /var/www/snede.net/public_html/wp-content/plugins/w3-total-cache/Cache_File.php on line 169

Warning: Cannot use bool as array in /var/www/snede.net/public_html/wp-content/plugins/w3-total-cache/Cache_File.php on line 169

Warning: Cannot modify header information - headers already sent by (output started at /var/www/snede.net/public_html/wp-content/plugins/w3-total-cache/Cache_File.php:169) in /var/www/snede.net/public_html/wp-includes/feed-rss2.php on line 8
dotnet core – André Snede https://snede.net Developer blog Mon, 25 Mar 2019 19:11:28 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.20 Add NuGet package XML documentation to Swagger https://snede.net/add-nuget-package-xml-documentation-to-swagger/?utm_source=rss&utm_medium=rss&utm_campaign=add-nuget-package-xml-documentation-to-swagger https://snede.net/add-nuget-package-xml-documentation-to-swagger/#comments Mon, 25 Mar 2019 19:11:27 +0000 https://snede.net/?p=376 Copy XML documentation from NuGet package to project build folder! At my current client, we are building an API that is put together by re-usable “API parts”, eg. ASP.NET Core Application Parts, which works wonders by the way. We can have multiple parts of the API split into small NuGet packages that can be re-used in other systems, that way we only have to implement system specific code, the rest is reused, including documentation etc. Talking about documentation, brings us directly to the issue. We use SwashBuckle to generate our Swagger definition and Swagger UI, and Swashbuckle requires XML documentation, to be able to include documentation from our Controllers and models. I thought we could probably just add a checkbox “Add XML documentation from NuGet package, on build”, but… Unfortunately...

The post Add NuGet package XML documentation to Swagger appeared first on André Snede.

]]>
Copy XML documentation from NuGet package to project build folder!

At my current client, we are building an API that is put together by re-usable “API parts”, eg. ASP.NET Core Application Parts, which works wonders by the way. We can have multiple parts of the API split into small NuGet packages that can be re-used in other systems, that way we only have to implement system specific code, the rest is reused, including documentation etc.

Talking about documentation, brings us directly to the issue. We use SwashBuckle to generate our Swagger definition and Swagger UI, and Swashbuckle requires XML documentation, to be able to include documentation from our Controllers and models. I thought we could probably just add a checkbox “Add XML documentation from NuGet package, on build”, but… Unfortunately not.

After a lot of research, and looking at NuGets github issues stating this problem I came up with a solution that works both at build time and at publish time (which apparently is handled differently).

The Setup

We have the following projects:

  • RestAPI (Root website, that will contain multiple API packages)
    • ASP.NET Core website
    • Contains Swagger page
    • System specific API Service implementations
  • BasicAPI (NuGet package)
    • ASP.NET Core website
    • Contains API endpoints, Models, Service interfaces etc.
    • Public XML documentation for its own API and Models
  • .. more NuGet packages to come

Include XML documentation, when building NuGet package with .csproj file

Our application is very simple, so we have chosen to pack nuget packages with our .csproj file instead of the more explicit .nuspec file.

Including XML documentation into a NuGet package is thankfully quite easy, and it should be, as it is the main way that documentation follows C# code.

The easiest way is to add the following PropertyGroup into your nuget package .csproj file:

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

This will do as it states, GenerateDocumentationFile. Generate a Documentation file, when you build the project. This file is also automatically added to your NuGet Package when you pack it.

Copy XML docs from NuGet package to your main projects build output

This is where it gets tricky. I was hoping that I could just add another boolean configuration. When looking through the issues for nuget, msbuild and dotnet on github, it did seem like they were working on something, and had implemented a way to add XML documentation from your PROJECT references/dependencies, but not your NuGet dependencies.

Luckily, we can add our own targets to the MSBuild task list and copy the XML docs ourselfs:

First add CopyToOutputDirectory to your main projects .csproj file, for the PackageReference you want to copy XML doc from. Like so:

 <ItemGroup>  
    <PackageReference Include="BasicAPI" Version="0.1.0-develop-6982">
      <CopyToOutputDirectory>lib\netcoreapp2.1\*</CopyToOutputDirectory>
    </PackageReference>
    <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.8" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.2.0" />
    ... etc
    <PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
  </ItemGroup>

The relative path added inside the CopyToOutputDirectory is the relative path from the root of the NuGet package folder, to where the XML docs are located.

In .NET Core, our NuGet packages are located at:

%USERPROFILE%\.nuget\packages\{PackageName}\{PackageVersion}

And the XML documentation file would be located at:

%USERPROFILE%\.nuget\packages\{PackageName}\{PackageVersion}\lib\netcoreapp2.1\{PackageName}.xml

Setup build targets to copy XML docs from NuGet package after Build

To copy the file after build time, we must add a target to MSBuild that does that. Add the following to your main projects .csproj file:

<Target Name="CopyPackages" AfterTargets="Build">
  <ItemGroup>
    <PackageReferenceFiles Condition="%(PackageReference.CopyToOutputDirectory) != ''" 
              Include="$(NugetPackageRoot)\%(PackageReference.FileName)\%(PackageReference.Version)\%(PackageReference.CopyToOutputDirectory)" />
  </ItemGroup>
  <Copy SourceFiles="@(PackageReferenceFiles)" DestinationFolder="$(OutDir)" />
</Target>

To copy the files from the NuGet package to our build output, we add a Target named “CopyPackages”, this name is for our own use and has no effect. After that, we are stating that we want this Target to run after the Build has finished.

When then create a Variable called PackageReferenceFiles that finds all PackageReference that has a property called CopyToOutputDirectory (the one we added in the last section). It then sets that variables value to be a combination of the location of the NuGetPackageRoot and relative path we set earlier.

Finally it asks MSBuild to do a file copy from the variable PackageReferenceFiles to the Builds Output directory.

Setup build targets to copy XML docs from NuGet package before Publish

For some odd reason, publish is done in multiple steps and it is not just a file copy from the build procedure, at least for web applications. That means that our OutDir will not be correct, and needs to be changed to PublishDir, we also need to make sure that this runs before the Target called PrepareForPublish.

I have tried multiple solutions to make this into one Target, but to finally gave into:

Keep it simple, stupid

And just added another Target with this small change.

So to copy XML docs from NuGet package before Publish, add this to your main projects .csproj file:

<Target Name="CopyPackagess" BeforeTargets="PrepareForPublish">
  <ItemGroup>
    <PackageReferenceFiles Condition="%(PackageReference.CopyToOutputDirectory) != ''" 
                Include="$(NugetPackageRoot)\%(PackageReference.FileName)\%(PackageReference.Version)\%(PackageReference.CopyToOutputDirectory)" />
  </ItemGroup>
  <Copy SourceFiles="@(PackageReferenceFiles)" DestinationFolder="$(PublishDir)" />
</Target>

Adding the NuGet packages XML doc to Swagger (Swashbuckle)

Finally, you just have to add the XML docs to your Swagger definition like so:

public void ConfigureSwagger(IServiceCollection services, object identityServerConfiguration)
{
  // Register the Swagger generator, defining one or more Swagger documents
  services.AddSwaggerGen(options =>
  {
      // integrate xml comments
      options.IncludeXmlComments(XmlCommentsFilePath(GetAssemblyName() + ".xml"));
      options.IncludeXmlComments(XmlCommentsFilePath("BasicAPI.xml"));
      // ...
}

private static string XmlCommentsFilePath(string xmlDocFileName) 
                           => Path.Combine(AppContext.BaseDirectory, xmlDocFileName);
private static string GetAssemblyName() 
                           => typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

I hope this saves you some time, as this took me a small evening to get right.

// André Snede Kock

The post Add NuGet package XML documentation to Swagger appeared first on André Snede.

]]>
https://snede.net/add-nuget-package-xml-documentation-to-swagger/feed/ 11
Redis connection issues https://snede.net/redis-connection-issues/?utm_source=rss&utm_medium=rss&utm_campaign=redis-connection-issues https://snede.net/redis-connection-issues/#respond Fri, 28 Dec 2018 19:53:33 +0000 https://snede.net/?p=3 At my current client, we have been dealing with an ongoing problem while scaling their cloud systems to the ever increasing customer-base. As it is with any software that needs to scale, we’ve been seeing and solving scalability problems along the way. Anyone who has ever dealt with scaling a system to accommodate a lot of concurrent users, knows that issues will be showing up places you aren’t expecting. While scaling the system, we’ve made it more resilient and fault tolerant, and also learned to mitigate many of the problems as they are arising. We’ve improved logging and metrics, so we know exactly what is happening, and can see stability problems before they affect the end-users. Redis loses connection, and will not reconnect In our system, we use StackExchange.Redis(v1.2.6) to...

The post Redis connection issues appeared first on André Snede.

]]>
At my current client, we have been dealing with an ongoing problem while scaling their cloud systems to the ever increasing customer-base.

As it is with any software that needs to scale, we’ve been seeing and solving scalability problems along the way. Anyone who has ever dealt with scaling a system to accommodate a lot of concurrent users, knows that issues will be showing up places you aren’t expecting.

While scaling the system, we’ve made it more resilient and fault tolerant, and also learned to mitigate many of the problems as they are arising. We’ve improved logging and metrics, so we know exactly what is happening, and can see stability problems before they affect the end-users.

Redis loses connection, and will not reconnect

In our system, we use StackExchange.Redis(v1.2.6) to communicate with our Redis server. The Redis instance handles all cached data and all communication between services. It is a vital part of our architecture, and currently the architecture is heavily dependent on this connection. The odd thing is that we keep losing connection to it, but Redis is not even breaking a sweat.

StackExchange.Redis is supposed to be able to recover from outages, and in most cases it does. But every once in a blue moon, it doesn’t. It think it does, and it thinks it is connected, but in reality all subsequent calls fail, and the pub/sub connection is completely dead, until the application is restarted.

We have multiple services, and it will always just be one of them that goes down, every other application will continue to run just fine.

At first we thought it was an internal bug, but as time has gone on, and we’ve fixed every issue around the library we could find or even think about it.

Examples:

  • Avoiding IO thread starvation
  • Minimizing load on Redis
    • Removing unnecessary/reduntandt calls
  • Reducing bytes transferred (Protocol buffers)
  • Hard-Reconnect
    • Reconnects managed by our software.

After seeing that not even a hard-reconnect would work, and the Multiplexer would not get a new connection, without restarting the entire application, it has become clear that StackExchange.Redis does have a problem reconnecting itself in some rare cases.

Since the issues have started, until now, similar reports have been showing up on their github page.

Examples of these issues:

The solution

In Marc Gravell’s(the creator of the library) issue #871, he addresses this issue, by saying that they have not been able to find the root cause of these issues and therefor are basically changing the entire network stack internally in the library. This will cause breaking changes for some users, but should fix all the issues that many of us have been having.

As he explains in the issue, the following has been addressed in 2.0:

The deliverables of this work are, in order:

  • network connection stability
  • especially on TLS (cloud), non-Windows systems and .NET Core
  • better protection from thread-pool starvation
  • lower allocations generally
  • better handling of “backlog” network buffers
  • cleaner code

We plan is to release this as the next “major”, 2.0.

Quote from StackExchange.Redis issue #871

The biggest change is the implementation of Microsofts System.IO.Pipelines, which helps them handle the complexity of the network layer, and integrate better with the .NET Core stack.

System.IO.Pipelines was built to run the ASP.NET Core Kestrel web server, so it is well tested in production.

Must network code is boiler plate that everyone has to write, and therefor also need to consider all the many corner cases this code has to cover. That often leads to very complex code, that can be error prone and even hard to maintain.

We know first hand, because one of our internal services, manages TCP Sockets, and that is one of the big areas we’ve spent alot of time and care on, to be able to scale it.

So we upgraded to 2.0

We were expecting to spend a day or two to change our code to fit against the breaking changed they were warning us about. But luckily, there was none; for us anyway. The entire library was plug’n’play and we could ship to our testing servers a few minutes after upgrading.

Our use of Redis is simple though, so that might be why we haven’t seen any breaking changes. We mainly use:

  • GET/SET
  • Sorted Sets
  • Pub/sub
  • Transactions

So far, we’ve been running 30-days in production with this updated library and had no incidents where the connection was lost and not able to be recovered.

Conclusion

As developers, we are quick to judge ourselves and even our predecessors, when odd bugs appear in production. We certainly did, and have torn our application to pieces many times to figure why we would see these problems in production (on multiple different platforms; Azure, AWS, etc..).

In our case, it took us a long time to realize that it might be the tool(StackExchange.Redis), although we did update the library multiple times to its latest version, hoping that this would solve it.

When 2.0 finally arrived, we were unsure if we had time to upgrade because of the breaking changes. Which turned out not to affect us at all.

Sometimes it actually is the tool that is broken. Thankfully, the team at StackExchange, and Marc Gravell especially, are competent and honest developers, so they addressed the issue and rewrote alot of the code to fix this issue, that they could not reproduce themselves.

A big thanks to Marc and the rest of the contributors for making a great tool, for us all to use for free!

The post Redis connection issues appeared first on André Snede.

]]>
https://snede.net/redis-connection-issues/feed/ 0
Re-use Controllers, Views and Tag-helpers in ASP.NET Core https://snede.net/re-use-controllers-views-and-tag-helpers-in-asp-net-core/?utm_source=rss&utm_medium=rss&utm_campaign=re-use-controllers-views-and-tag-helpers-in-asp-net-core https://snede.net/re-use-controllers-views-and-tag-helpers-in-asp-net-core/#comments Wed, 12 Dec 2018 18:35:54 +0000 https://snede.net/?p=43 I recently ran into a situation, where I needed to implement the same functionality, the same views and even the same tag-helpers for different customers. Like most other developers I hate copy-pasting code that should be shared across multiple projects. I had come across a similar need a few years back, but remembered that it was cumbersome in ASP.NET 3-5, to achieve this, and the solutions back then didn’t feel right. But since my recent switch to dotnet core, I knew there was a chance that Microsoft had a prepared an early christmas present for me. So I started researching my options, searching for titles similar to this blog post, and finally found a solution on the third place on google (Yes I was that desperate). Introducing Application Parts /...

The post Re-use Controllers, Views and Tag-helpers in ASP.NET Core appeared first on André Snede.

]]>
I recently ran into a situation, where I needed to implement the same functionality, the same views and even the same tag-helpers for different customers.

Like most other developers I hate copy-pasting code that should be shared across multiple projects. I had come across a similar need a few years back, but remembered that it was cumbersome in ASP.NET 3-5, to achieve this, and the solutions back then didn’t feel right. But since my recent switch to dotnet core, I knew there was a chance that Microsoft had a prepared an early christmas present for me.

So I started researching my options, searching for titles similar to this blog post, and finally found a solution on the third place on google (Yes I was that desperate).

Introducing Application Parts / App Parts

With the introduction of ASP.NET Core v1.0, MVC came with a new concept called “Application Parts”, which is how the features and resources is populated into a ASP.NET Core MVC application.

MVC loads it’s features from different application parts, which is a new type in ASP.NET Core. Specifically for my use-case, it can load the parts of an application from another Assembly (read: dll file). By creating an AssemblyPart object, you can discover controllers, views and tag helpers from a shared library.

Adding controllers from a shared project

Consider that I have a basic MVC site called “MyWebApp”, and another project called “SharedModule”, of which MyWebApp has a reference to. The SharedModule is created as an Empty MVC site, and then later populated with controllers.

The MyWebApp project only contains a HomeController, and the “SharedModule” contains an MVC Controller called “UserController”, that can be shared by multiple projects.

Structure:

  • Solution
    • MyWebApp
      • HomeController
    • SharedModule
      • UserController

By default, the MyWebApp application, will not be able to serve the UserController in the other project, unless it inherits it directly within its own site. But by using application parts, this becomes possible.

// Get assembly type that UserController lives in. 
var assembly = typeof(UserController).GetTypeInfo().Assembly;
services.AddMvc().AddApplicationPart(assembly);

The above code is a shortcut for doing this directly with the ApplicationPartManager.

// Get assembly type that UserController lives in. 
var assembly = typeof(UserController).GetTypeInfo().Assembly;
// Create new assembly part, from assembly type
var sharedModulePart = new AssemblyPart(assembly);
services.AddMvc()
    // Configure the Application Manager
    .ConfigureApplicationPartManager(apm => 
        // Add the SharedModule assembly part, to the application parts list.
        apm.ApplicationParts.Add(sharedModulePart));

The above code examples, loads in all the application parts from the SharedModulewhich in this case, means the UserController.

Managing Application Features

While Application Parts lets you load in controllers, views etc. from other assemblies, the Application Feature provider list within the ApplicationPartManager lets you fine tune exactly what goes into your application. 

By defining and adding an IApplicationFeatureProvider implementation to the FeatureProviders list, you can add, remove or even edit the features that makes up your application.

 services.AddMvc()
     .AddApplicationPart(assembly);            
     .ConfigureApplicationPartManager(apm => 
         // Add the FeatureProvider that can filter out controllers.
         apm.FeatureProviders.Add(new FilterControllerFeatureProvider()));
public class FilterControllerFeatureProvider: IApplicationFeatureProvider<ControllerFeature>
{
    public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature)
    {
        // Find controller in the ControllerFeature object.
        var controllerToRemove = feature.Controllers.FirstOrDefault(x => x.Name == "UserController");
        // Remove the controller we added from Application Parts.
        feature.Controllers.Remove(controllerToRemove);
    }
}

It seems a bit odd to remove the controller we just spent time on adding, but the functionality is great, and I use it to fine tune what exact components goes into my applications. By using configuration, I can go through each of my controllers and decide whether a certain feature is enabled for that customer.

And it becomes extremely powerful, if you start to consider generic Controllers, that can handle basic CRUD operations for a bunch of different models.

Microsoft has provided a great example of that on their documentation page.

Which I encourage you to go read to learn more about Application Parts in ASP.NET Core.

I hope this blog post was helpful, I certainly learned a lot researching this topic, and will be using Application Parts a fair bit, for those pieces of code that absolutely should be shared and not just copied around.

// André Kock

The post Re-use Controllers, Views and Tag-helpers in ASP.NET Core appeared first on André Snede.

]]>
https://snede.net/re-use-controllers-views-and-tag-helpers-in-asp-net-core/feed/ 5