Are you over 18 and want to see adult content?
More Annotations
![A complete backup of sinnvolltechnologies.com](https://www.archivebay.com/archive5/images/5fa2b43f-4f5e-4aa2-8e44-f603b2bcaeca.png)
A complete backup of sinnvolltechnologies.com
Are you over 18 and want to see adult content?
![A complete backup of eminenceorganics.com](https://www.archivebay.com/archive5/images/cf1fa2b8-f561-4ccf-9bfc-d5c21e7d42d1.png)
A complete backup of eminenceorganics.com
Are you over 18 and want to see adult content?
![A complete backup of moolollybar.com.au](https://www.archivebay.com/archive5/images/6bae55ae-9789-40c5-8ad8-bafdf81f776d.png)
A complete backup of moolollybar.com.au
Are you over 18 and want to see adult content?
Favourite Annotations
![A complete backup of overstockbait.com](https://www.archivebay.com/archive2/023d8bae-72d6-4863-a665-4fd37817fc91.png)
A complete backup of overstockbait.com
Are you over 18 and want to see adult content?
![A complete backup of kirpichikblok.ru](https://www.archivebay.com/archive2/2008d07b-eb7a-4b65-b6e4-4899101438fd.png)
A complete backup of kirpichikblok.ru
Are you over 18 and want to see adult content?
![A complete backup of gunghoonline.com](https://www.archivebay.com/archive2/7236b237-b21a-42fe-9c71-72a9fa321e32.png)
A complete backup of gunghoonline.com
Are you over 18 and want to see adult content?
Text
are
CLONING OBJECTS IN C# AND .NET CORE Cloning objects in any programming language is tricky, but I think in C# that’s taken up an extra notch by giving you a couple of tools that look like they would probably solve your problem, but then not letting you know that it’s likely to only solve a very slim use caseand nothing else.
USING CHANNELS IN C# .NET CORE This post is part of a series on Channel in .NET. Of course, it’s always better to start at Part 1, but you can skip anywhere you’d like using the links below. Part 1 – Getting Started Part 2 – Advanced Channels Part 3 – Understanding Back Pressure In our previous post we looked at CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but READING EXCEL FILES IN .NET CORE Opening Excel files in code has been a painful experience long before .NET Core came along. In many cases, you actually needed the Excel application installed on the target/users machine to be able to open excel files via code. If you’ve ever had to use those “OLE DB Jet”
USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core I haven’t used CosmosDB an awful lot over the years, but when I have, It’s been a breeze to use. It’snot
EAGER LOAD NAVIGATION PROPERTIES BY DEFAULT IN EF CORE Eager Load Navigation Properties By Default In EF Core. Normally when loading navigation properties in EF Core, you’re forced to use the “Include” method to specify which navigational properties to pull back with your query. This is a very good practice because it means you are explicitly saying what pieces of data you actually require. FIXING "THIS ASYNC METHOD LACKS 'AWAIT' OPERATORS AND WILL This little “warning” has been the bain of my life recently warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run()’ to do CPU-bound work on a background thread. And after a bit of searching around, I justwanted to
DAPPER IN .NET CORE
The brains behind Dapper are the guys over at StackOverflow. It was created because the burden on the web servers of simply taking the LINQ2SQL statements and generating SQL was often making their web boxes hit 100% CPU. Coupled with the fact that you couldn’t actually control what SQL was output from your LINQ, Dapper was born. USING THE ILOGGER BEGINSCOPE IN ASP.NET CORE While working on another post about implementing your own custom ILogger implementation, I came across a method on the ILogger interface that I had never actually used before. It looks something like _logger.BeginScope(“Message Here”); , Or correction, it didn’t just take a string, it could take any type and use this for a “scope”. It intrigued GETTING SETUP WITH .NET 6 PREVIEW Go Tools -> Options, then select Preview Features as per the screenshot below. Make sure to tick the “Use previews of the .NET Core SDK”. Without this, Visual Studio will use the latest version of the .NET SDK installed, that is *not* a preview version. Obviously once .NET 6 is out of preview, you won’t need to do this, but if youare
CLONING OBJECTS IN C# AND .NET CORE Cloning objects in any programming language is tricky, but I think in C# that’s taken up an extra notch by giving you a couple of tools that look like they would probably solve your problem, but then not letting you know that it’s likely to only solve a very slim use caseand nothing else.
USING CHANNELS IN C# .NET CORE This post is part of a series on Channel in .NET. Of course, it’s always better to start at Part 1, but you can skip anywhere you’d like using the links below. Part 1 – Getting Started Part 2 – Advanced Channels Part 3 – Understanding Back Pressure In our previous post we looked at CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but READING EXCEL FILES IN .NET CORE Opening Excel files in code has been a painful experience long before .NET Core came along. In many cases, you actually needed the Excel application installed on the target/users machine to be able to open excel files via code. If you’ve ever had to use those “OLE DB Jet”
USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core I haven’t used CosmosDB an awful lot over the years, but when I have, It’s been a breeze to use. It’snot
EAGER LOAD NAVIGATION PROPERTIES BY DEFAULT IN EF CORE Eager Load Navigation Properties By Default In EF Core. Normally when loading navigation properties in EF Core, you’re forced to use the “Include” method to specify which navigational properties to pull back with your query. This is a very good practice because it means you are explicitly saying what pieces of data you actually require. FIXING "THIS ASYNC METHOD LACKS 'AWAIT' OPERATORS AND WILL This little “warning” has been the bain of my life recently warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run()’ to do CPU-bound work on a background thread. And after a bit of searching around, I justwanted to
DAPPER IN .NET CORE
The brains behind Dapper are the guys over at StackOverflow. It was created because the burden on the web servers of simply taking the LINQ2SQL statements and generating SQL was often making their web boxes hit 100% CPU. Coupled with the fact that you couldn’t actually control what SQL was output from your LINQ, Dapper was born. USING THE ILOGGER BEGINSCOPE IN ASP.NET CORE While working on another post about implementing your own custom ILogger implementation, I came across a method on the ILogger interface that I had never actually used before. It looks something like _logger.BeginScope(“Message Here”); , Or correction, it didn’t just take a string, it could take any type and use this for a “scope”. It intrigued USING CHANNELS IN C# .NET CORE This post is part of a series on Channel in .NET. Of course, it’s always better to start at Part 1, but you can skip anywhere you’d like using the links below. Part 1 – Getting Started Part 2 – Advanced Channels Part 3 – Understanding Back Pressure I’ve recently been playing around with the USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core I haven’t used CosmosDB an awful lot over the years, but when I have, It’s been a breeze to use. It’snot
GETTING ASSEMBLIES IS HARDER THAN YOU THINK IN C# So the first option you might come across is AppDomain.GetAssemblies. It (seemingly) loads all Assemblies in the AppDomain which is to say essentially every Assembly that is used in your project. But there is a massive caveat. Assemblies in .NET are lazy loaded into the AppDomain. It doesn’t all at once load every assembly possible,instead
LOADING AND PARSING A WEB PAGE IN .NET CORE Many years back, I actually started programming so that I could cheat at an online web browser based game (I know, I know). I started in Pascal/Delphi, but quickly moved onto C#. Back then, I was using things like HttpWebRequest/Response to load the webpage, and using raw regex to parse it. Looking back, some ofDAPPER IN .NET CORE
The brains behind Dapper are the guys over at StackOverflow. It was created because the burden on the web servers of simply taking the LINQ2SQL statements and generating SQL was often making their web boxes hit 100% CPU. Coupled with the fact that you couldn’t actually control what SQL was output from your LINQ, Dapper was born. EAGER LOAD NAVIGATION PROPERTIES BY DEFAULT IN EF CORE Eager Load Navigation Properties By Default In EF Core. Normally when loading navigation properties in EF Core, you’re forced to use the “Include” method to specify which navigational properties to pull back with your query. This is a very good practice because it means you are explicitly saying what pieces of data you actually require. IMPLEMENTING A LEAKY BUCKET CLIENT IN .NET CORE Rate limiting web services and APIs is nothing new, but I would say over the past couple of years the “leaky bucket” strategy of rate limiting has rised in popularity to the point where it’s almost a defacto these days. The leaky bucket strategy is actually quite simple – made even easier by the fact USING THE ILOGGER BEGINSCOPE IN ASP.NET CORE While working on another post about implementing your own custom ILogger implementation, I came across a method on the ILogger interface that I had never actually used before. It looks something like _logger.BeginScope(“Message Here”); , Or correction, it didn’t just take a string, it could take any type and use this for a “scope”. It intrigued AZURE WEBJOBS IN .NET CORE While working on a web project recently that was written in .NET Core, there was a need for a small background task to run either on a timer, or on an Azure queue message. No worries, we can just use an Azure WebJob for that, no extra infrastructure or Azure setup requiredright? Well, it
USING AZURE BLOB STORAGE IN .NET CORE Pretty much any project that allows file uploads is going to utilize some cloud storage provider. It could be rackspace, it could be GCloud, it could be AWS S3, or in this post’s case, it’s going to be Azure Blob Storage. Using Blob Storage in .NET Core really isn’t that different to using it in GETTING SETUP WITH .NET 6 PREVIEW Go Tools -> Options, then select Preview Features as per the screenshot below. Make sure to tick the “Use previews of the .NET Core SDK”. Without this, Visual Studio will use the latest version of the .NET SDK installed, that is *not* a preview version. Obviously once .NET 6 is out of preview, you won’t need to do this, but if youare
USING CHANNELS IN C# .NET CORE This post is part of a series on Channel in .NET. Of course, it’s always better to start at Part 1, but you can skip anywhere you’d like using the links below. Part 1 – Getting Started Part 2 – Advanced Channels Part 3 – Understanding Back Pressure In our previous post we looked at CLONING OBJECTS IN C# AND .NET CORE Cloning objects in any programming language is tricky, but I think in C# that’s taken up an extra notch by giving you a couple of tools that look like they would probably solve your problem, but then not letting you know that it’s likely to only solve a very slim use caseand nothing else.
TESTING XXE VULNERABILITIES IN .NET CORE Testing XXE Vulnerabilities In .NET Core. An XML External Entity vulnerability (Or XXE for short) is a type of vulnerability that exploits weaknesses (Or more so features) in how external entities are loaded when parsing XML in code. Of course, OWASP has a great guide on it here, but in it’s most basic form, we can trick code into loadingan
CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but READING EXCEL FILES IN .NET CORE Opening Excel files in code has been a painful experience long before .NET Core came along. In many cases, you actually needed the Excel application installed on the target/users machine to be able to open excel files via code. If you’ve ever had to use those “OLE DB Jet”
USING AUTH0 WITH AN ASP.NET CORE API I’ve recently had to set up a new project using Auth0 as an “Identity As A Service” provider. Essentially, Auth0 provides an authentication service using an OAuth2 flow, meaning I don’t have to store passwords, worry about passwords resets, or implement my own two factor authentication. Everything about authenticating a user ishandled by Auth0,
FIXING "THIS ASYNC METHOD LACKS 'AWAIT' OPERATORS AND WILL This little “warning” has been the bain of my life recently warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run()’ to do CPU-bound work on a background thread. And after a bit of searching around, I justwanted to
EAGER LOAD NAVIGATION PROPERTIES BY DEFAULT IN EF CORE Eager Load Navigation Properties By Default In EF Core. Normally when loading navigation properties in EF Core, you’re forced to use the “Include” method to specify which navigational properties to pull back with your query. This is a very good practice because it means you are explicitly saying what pieces of data you actually require. 3 ANNOYING AZURE ARM TEMPLATE GOTCHAS (AND HOW TO FIX THEM 3 Annoying Azure ARM Template Gotchas (And How To Fix Them) The most popular method of managing Azure resources in a programmatic fashion is Azure Resource Management Templates – or ARM templates for short. Much like Terraform, it’s a desired state type tool that you can define what you need, but Azure will work out the actual details of GETTING SETUP WITH .NET 6 PREVIEW Go Tools -> Options, then select Preview Features as per the screenshot below. Make sure to tick the “Use previews of the .NET Core SDK”. Without this, Visual Studio will use the latest version of the .NET SDK installed, that is *not* a preview version. Obviously once .NET 6 is out of preview, you won’t need to do this, but if youare
USING CHANNELS IN C# .NET CORE This post is part of a series on Channel in .NET. Of course, it’s always better to start at Part 1, but you can skip anywhere you’d like using the links below. Part 1 – Getting Started Part 2 – Advanced Channels Part 3 – Understanding Back Pressure In our previous post we looked at CLONING OBJECTS IN C# AND .NET CORE Cloning objects in any programming language is tricky, but I think in C# that’s taken up an extra notch by giving you a couple of tools that look like they would probably solve your problem, but then not letting you know that it’s likely to only solve a very slim use caseand nothing else.
TESTING XXE VULNERABILITIES IN .NET CORE Testing XXE Vulnerabilities In .NET Core. An XML External Entity vulnerability (Or XXE for short) is a type of vulnerability that exploits weaknesses (Or more so features) in how external entities are loaded when parsing XML in code. Of course, OWASP has a great guide on it here, but in it’s most basic form, we can trick code into loadingan
CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but READING EXCEL FILES IN .NET CORE Opening Excel files in code has been a painful experience long before .NET Core came along. In many cases, you actually needed the Excel application installed on the target/users machine to be able to open excel files via code. If you’ve ever had to use those “OLE DB Jet”
USING AUTH0 WITH AN ASP.NET CORE API I’ve recently had to set up a new project using Auth0 as an “Identity As A Service” provider. Essentially, Auth0 provides an authentication service using an OAuth2 flow, meaning I don’t have to store passwords, worry about passwords resets, or implement my own two factor authentication. Everything about authenticating a user ishandled by Auth0,
FIXING "THIS ASYNC METHOD LACKS 'AWAIT' OPERATORS AND WILL This little “warning” has been the bain of my life recently warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run()’ to do CPU-bound work on a background thread. And after a bit of searching around, I justwanted to
EAGER LOAD NAVIGATION PROPERTIES BY DEFAULT IN EF CORE Eager Load Navigation Properties By Default In EF Core. Normally when loading navigation properties in EF Core, you’re forced to use the “Include” method to specify which navigational properties to pull back with your query. This is a very good practice because it means you are explicitly saying what pieces of data you actually require. 3 ANNOYING AZURE ARM TEMPLATE GOTCHAS (AND HOW TO FIX THEM 3 Annoying Azure ARM Template Gotchas (And How To Fix Them) The most popular method of managing Azure resources in a programmatic fashion is Azure Resource Management Templates – or ARM templates for short. Much like Terraform, it’s a desired state type tool that you can define what you need, but Azure will work out the actual details of GETTING STARTED WITH .NET 5 So by now you’ve probably heard a little about various .NET 5 announcements and you’re ready to give it a try! I thought first I would give some of the cliffnotes from the .NET 5 announcement, and then jump into how to actually have a play with the preview version of .NET 5 (Correct as of writing this post on 2020-05-22). TESTING XXE VULNERABILITIES IN .NET CORE Testing XXE Vulnerabilities In .NET Core. An XML External Entity vulnerability (Or XXE for short) is a type of vulnerability that exploits weaknesses (Or more so features) in how external entities are loaded when parsing XML in code. Of course, OWASP has a great guide on it here, but in it’s most basic form, we can trick code into loadingan
HOW TO PARSE XML IN .NET CORE One of the most popular posts on this blog is a very simple write-up on how to parse JSON in .NET Core.I mostly wrote it because I thought that there was definitely a “proper” way of doing things, and people were almost going out of their way to make READING EXCEL FILES IN .NET CORE Opening Excel files in code has been a painful experience long before .NET Core came along. In many cases, you actually needed the Excel application installed on the target/users machine to be able to open excel files via code. If you’ve ever had to use those “OLE DB Jet”
GETTING ASSEMBLIES IS HARDER THAN YOU THINK IN C# So the first option you might come across is AppDomain.GetAssemblies. It (seemingly) loads all Assemblies in the AppDomain which is to say essentially every Assembly that is used in your project. But there is a massive caveat. Assemblies in .NET are lazy loaded into the AppDomain. It doesn’t all at once load every assembly possible,instead
CREATING MODERN AND HELPFUL COMMAND LINE UTILITIES WITH System.CommandLine is actually in beta right now. To install the current beta in your application you would need to run the following from your Package Manager Console. Install-Package System.CommandLine -Version 2.0.0-beta1.20574.7. Or alternatively if you’re trying to view it via the Nuget Browser in Visual Studio, ensure you have USING AUTH0 WITH AN ASP.NET CORE API I’ve recently had to set up a new project using Auth0 as an “Identity As A Service” provider. Essentially, Auth0 provides an authentication service using an OAuth2 flow, meaning I don’t have to store passwords, worry about passwords resets, or implement my own two factor authentication. Everything about authenticating a user ishandled by Auth0,
USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core When I first found out EntityFramework supported Azure CosmosDB, I was honestly pretty excited. Not because I thought it would be revolutionary, CREATING AND VALIDATING JWT TOKENS IN ASP.NET CORE It’s pretty simply actually. We create a TokenHandler which is a .NET Core inbuilt class for handling JWT Tokens, we pass it our token as well as our “expected” issuer, audience and our security key and call validate. This validates that the issuer and audience are what we expect, and that the token is signed with the correct key. CREATING A PDF IN .NET CORE Introduction. It’s a pretty common use case to want to generate PDF’s in C# code, either to serve directly to a user or to save locally. When I came to do it recently, suddenly I was over(and under)whelmed with the options available to actually achieve this. GETTING SETUP WITH .NET 6 PREVIEW In the coming months I’ll be covering the new features of .NET 6, including things like MAUI (Cross platform GUI in .NET), PriorityQueue, and so much more. So I thought it would be worth talking a little bit on how to actually get set up to use .NET 6 if you are looking to touch USING CHANNELS IN C# .NET CORE This post is part of a series on Channel in .NET. Of course, it’s always better to start at Part 1, but you can skip anywhere you’d like using the links below. Part 1 – Getting Started Part 2 – Advanced Channels Part 3 – Understanding Back Pressure In our previous post we looked at USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core I haven’t used CosmosDB an awful lot over the years, but when I have, It’s been a breeze to use. It’snot
CLONING OBJECTS IN C# AND .NET CORE Cloning objects in any programming language is tricky, but I think in C# that’s taken up an extra notch by giving you a couple of tools that look like they would probably solve your problem, but then not letting you know that it’s likely to only solve a very slim use caseand nothing else.
CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but EAGER LOAD NAVIGATION PROPERTIES BY DEFAULT IN EF CORE Normally when loading navigation properties in EF Core, you’re forced to use the “Include” method to specify which navigational properties to pull back with your query. This is a very good practice because it means you are explicitly saying what pieces of data you actually require. In fact, up until EF Core 2.1, there wasn’t USING AUTH0 WITH AN ASP.NET CORE API I’ve recently had to set up a new project using Auth0 as an “Identity As A Service” provider. Essentially, Auth0 provides an authentication service using an OAuth2 flow, meaning I don’t have to store passwords, worry about passwords resets, or implement my own two factor authentication. Everything about authenticating a user ishandled by Auth0,
FIXING "THIS ASYNC METHOD LACKS 'AWAIT' OPERATORS AND WILL This little “warning” has been the bain of my life recently warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run()’ to do CPU-bound work on a background thread. And after a bit of searching around, I justwanted to
3 ANNOYING AZURE ARM TEMPLATE GOTCHAS (AND HOW TO FIX THEM Connecting Web Apps/Functions To Application Insights Only Requires The Instrumentation Key. I talked about this a little in a previous post around connecting Azure Functions to App Insights.I think it could be a hold over from the early days of App Insights when there wasn’t as much magic going on, and you really did have to do a bit of work to wire up Web Applications to App Insights. ROWVERSION VS CONCURRENCYTOKEN IN ENTITYFRAMEWORK/EFCORE I recently got asked a pretty good question about EFCore (Although it does also apply in general to database concepts), and that was : Should I use RowVersion or ConcurrencyToken for optimistic concurrency? And the answer is “It depends” and even more specifically, “Do you know what the difference, or lack thereof,there is between
GETTING SETUP WITH .NET 6 PREVIEW In the coming months I’ll be covering the new features of .NET 6, including things like MAUI (Cross platform GUI in .NET), PriorityQueue, and so much more. So I thought it would be worth talking a little bit on how to actually get set up to use .NET 6 if you are looking to touch USING CHANNELS IN C# .NET CORE This post is part of a series on Channel in .NET. Of course, it’s always better to start at Part 1, but you can skip anywhere you’d like using the links below. Part 1 – Getting Started Part 2 – Advanced Channels Part 3 – Understanding Back Pressure In our previous post we looked at TESTING XXE VULNERABILITIES IN .NET CORE An XML External Entity vulnerability (Or XXE for short) is a type of vulnerability that exploits weaknesses (Or more so features) in how external entities are loaded when parsing XML in code. Of course, OWASP has a great guide on it here, but in it’s most basic form, we CLONING OBJECTS IN C# AND .NET CORE Cloning objects in any programming language is tricky, but I think in C# that’s taken up an extra notch by giving you a couple of tools that look like they would probably solve your problem, but then not letting you know that it’s likely to only solve a very slim use caseand nothing else.
USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core I haven’t used CosmosDB an awful lot over the years, but when I have, It’s been a breeze to use. It’snot
CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but EAGER LOAD NAVIGATION PROPERTIES BY DEFAULT IN EF CORE Normally when loading navigation properties in EF Core, you’re forced to use the “Include” method to specify which navigational properties to pull back with your query. This is a very good practice because it means you are explicitly saying what pieces of data you actually require. In fact, up until EF Core 2.1, there wasn’t FIXING "THIS ASYNC METHOD LACKS 'AWAIT' OPERATORS AND WILL This little “warning” has been the bain of my life recently warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run()’ to do CPU-bound work on a background thread. And after a bit of searching around, I justwanted to
3 ANNOYING AZURE ARM TEMPLATE GOTCHAS (AND HOW TO FIX THEM Connecting Web Apps/Functions To Application Insights Only Requires The Instrumentation Key. I talked about this a little in a previous post around connecting Azure Functions to App Insights.I think it could be a hold over from the early days of App Insights when there wasn’t as much magic going on, and you really did have to do a bit of work to wire up Web Applications to App Insights. ROWVERSION VS CONCURRENCYTOKEN IN ENTITYFRAMEWORK/EFCORE I recently got asked a pretty good question about EFCore (Although it does also apply in general to database concepts), and that was : Should I use RowVersion or ConcurrencyToken for optimistic concurrency? And the answer is “It depends” and even more specifically, “Do you know what the difference, or lack thereof,there is between
GETTING STARTED WITH .NET 5 So by now you’ve probably heard a little about various .NET 5 announcements and you’re ready to give it a try! I thought first I would give some of the cliffnotes from the .NET 5 announcement, and then jump into how to actually have a play with the preview version of .NET 5 (Correct as of writing this post on 2020-05-22). HOW TO PARSE XML IN .NET CORE One of the most popular posts on this blog is a very simple write-up on how to parse JSON in .NET Core.I mostly wrote it because I thought that there was definitely a “proper” way of doing things, and people were almost going out of their way to make TESTING XXE VULNERABILITIES IN .NET CORE An XML External Entity vulnerability (Or XXE for short) is a type of vulnerability that exploits weaknesses (Or more so features) in how external entities are loaded when parsing XML in code. Of course, OWASP has a great guide on it here, but in it’s most basic form, we RECORD TYPES IN C# 9 Init-Only Properties In C# 9. Before we go much further, I highly recommend reading our guide on Init-Only Properties in C# 9 here.Record types in C# 9 are borderline an extension of the level of immutability that init-only properties give, and so much of this article will refer back to that. CREATING MODERN AND HELPFUL COMMAND LINE UTILITIES WITH Since really .NET Framework 1, the ability for .NET Console apps to parse command line flags and actually provide helpful feedback to the user on even the availability of such flags has been severely lacking. What do I mean by that? Well when you create a new console application in C#/.NET/.NET Core, your code will USING AUTH0 WITH AN ASP.NET CORE API I’ve recently had to set up a new project using Auth0 as an “Identity As A Service” provider. Essentially, Auth0 provides an authentication service using an OAuth2 flow, meaning I don’t have to store passwords, worry about passwords resets, or implement my own two factor authentication. Everything about authenticating a user ishandled by Auth0,
GETTING ASSEMBLIES IS HARDER THAN YOU THINK IN C# I was writing some reflection code the other day where I wanted to search through all of my assemblies for a particular interface, and call a method on it at startup. Seemed pretty simple but in reality there is no clear, easy, one size fits all way to get assemblies. Thispost may be a
USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core When I first found out EntityFramework supported Azure CosmosDB, I was honestly pretty excited. Not because I thought it would be revolutionary, CREATING AND VALIDATING JWT TOKENS IN ASP.NET CORE I’ve recently been using JWT Tokens as my authentication method of choice for my API’s. And with it, I’ve had to do battle with various pieces of documentation on how JWT token authentication and authorization actually work in .NET Core. CREATING A PDF IN .NET CORE Introduction. It’s a pretty common use case to want to generate PDF’s in C# code, either to serve directly to a user or to save locally. When I came to do it recently, suddenly I was over(and under)whelmed with the options available to actually achieve this. GETTING SETUP WITH .NET 6 PREVIEW Go Tools -> Options, then select Preview Features as per the screenshot below. Make sure to tick the “Use previews of the .NET Core SDK”. Without this, Visual Studio will use the latest version of the .NET SDK installed, that is *not* a preview version. Obviously once .NET 6 is out of preview, you won’t need to do this, but if youare
USING CHANNELS IN C# .NET CORE This post is part of a series on Channel in .NET. Of course, it’s always better to start at Part 1, but you can skip anywhere you’d like using the links below. Part 1 – Getting Started Part 2 – Advanced Channels Part 3 – Understanding Back Pressure In our previous post we looked at USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core I haven’t used CosmosDB an awful lot over the years, but when I have, It’s been a breeze to use. It’snot
CLONING OBJECTS IN C# AND .NET CORE Cloning objects in any programming language is tricky, but I think in C# that’s taken up an extra notch by giving you a couple of tools that look like they would probably solve your problem, but then not letting you know that it’s likely to only solve a very slim use caseand nothing else.
CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but TESTING XXE VULNERABILITIES IN .NET CORE Testing XXE Vulnerabilities In .NET Core. An XML External Entity vulnerability (Or XXE for short) is a type of vulnerability that exploits weaknesses (Or more so features) in how external entities are loaded when parsing XML in code. Of course, OWASP has a great guide on it here, but in it’s most basic form, we can trick code into loadingan
EAGER LOAD NAVIGATION PROPERTIES BY DEFAULT IN EF CORE Eager Load Navigation Properties By Default In EF Core. Normally when loading navigation properties in EF Core, you’re forced to use the “Include” method to specify which navigational properties to pull back with your query. This is a very good practice because it means you are explicitly saying what pieces of data you actually require. GETTING ASSEMBLIES IS HARDER THAN YOU THINK IN C# So the first option you might come across is AppDomain.GetAssemblies. It (seemingly) loads all Assemblies in the AppDomain which is to say essentially every Assembly that is used in your project. But there is a massive caveat. Assemblies in .NET are lazy loaded into the AppDomain. It doesn’t all at once load every assembly possible,instead
FIXING "THIS ASYNC METHOD LACKS 'AWAIT' OPERATORS AND WILL This little “warning” has been the bain of my life recently warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run()’ to do CPU-bound work on a background thread. And after a bit of searching around, I justwanted to
3 ANNOYING AZURE ARM TEMPLATE GOTCHAS (AND HOW TO FIX THEM 3 Annoying Azure ARM Template Gotchas (And How To Fix Them) The most popular method of managing Azure resources in a programmatic fashion is Azure Resource Management Templates – or ARM templates for short. Much like Terraform, it’s a desired state type tool that you can define what you need, but Azure will work out the actual details of GETTING SETUP WITH .NET 6 PREVIEW Go Tools -> Options, then select Preview Features as per the screenshot below. Make sure to tick the “Use previews of the .NET Core SDK”. Without this, Visual Studio will use the latest version of the .NET SDK installed, that is *not* a preview version. Obviously once .NET 6 is out of preview, you won’t need to do this, but if youare
USING CHANNELS IN C# .NET CORE This post is part of a series on Channel in .NET. Of course, it’s always better to start at Part 1, but you can skip anywhere you’d like using the links below. Part 1 – Getting Started Part 2 – Advanced Channels Part 3 – Understanding Back Pressure In our previous post we looked at USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core I haven’t used CosmosDB an awful lot over the years, but when I have, It’s been a breeze to use. It’snot
CLONING OBJECTS IN C# AND .NET CORE Cloning objects in any programming language is tricky, but I think in C# that’s taken up an extra notch by giving you a couple of tools that look like they would probably solve your problem, but then not letting you know that it’s likely to only solve a very slim use caseand nothing else.
CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but TESTING XXE VULNERABILITIES IN .NET CORE Testing XXE Vulnerabilities In .NET Core. An XML External Entity vulnerability (Or XXE for short) is a type of vulnerability that exploits weaknesses (Or more so features) in how external entities are loaded when parsing XML in code. Of course, OWASP has a great guide on it here, but in it’s most basic form, we can trick code into loadingan
EAGER LOAD NAVIGATION PROPERTIES BY DEFAULT IN EF CORE Eager Load Navigation Properties By Default In EF Core. Normally when loading navigation properties in EF Core, you’re forced to use the “Include” method to specify which navigational properties to pull back with your query. This is a very good practice because it means you are explicitly saying what pieces of data you actually require. GETTING ASSEMBLIES IS HARDER THAN YOU THINK IN C# So the first option you might come across is AppDomain.GetAssemblies. It (seemingly) loads all Assemblies in the AppDomain which is to say essentially every Assembly that is used in your project. But there is a massive caveat. Assemblies in .NET are lazy loaded into the AppDomain. It doesn’t all at once load every assembly possible,instead
FIXING "THIS ASYNC METHOD LACKS 'AWAIT' OPERATORS AND WILL This little “warning” has been the bain of my life recently warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run()’ to do CPU-bound work on a background thread. And after a bit of searching around, I justwanted to
3 ANNOYING AZURE ARM TEMPLATE GOTCHAS (AND HOW TO FIX THEM 3 Annoying Azure ARM Template Gotchas (And How To Fix Them) The most popular method of managing Azure resources in a programmatic fashion is Azure Resource Management Templates – or ARM templates for short. Much like Terraform, it’s a desired state type tool that you can define what you need, but Azure will work out the actual details of GETTING STARTED WITH .NET 5 So by now you’ve probably heard a little about various .NET 5 announcements and you’re ready to give it a try! I thought first I would give some of the cliffnotes from the .NET 5 announcement, and then jump into how to actually have a play with the preview version of .NET 5 (Correct as of writing this post on 2020-05-22). GETTING ASSEMBLIES IS HARDER THAN YOU THINK IN C# So the first option you might come across is AppDomain.GetAssemblies. It (seemingly) loads all Assemblies in the AppDomain which is to say essentially every Assembly that is used in your project. But there is a massive caveat. Assemblies in .NET are lazy loaded into the AppDomain. It doesn’t all at once load every assembly possible,instead
TESTING XXE VULNERABILITIES IN .NET CORE Testing XXE Vulnerabilities In .NET Core. An XML External Entity vulnerability (Or XXE for short) is a type of vulnerability that exploits weaknesses (Or more so features) in how external entities are loaded when parsing XML in code. Of course, OWASP has a great guide on it here, but in it’s most basic form, we can trick code into loadingan
RECORD TYPES IN C# 9 Init-Only Properties In C# 9. Before we go much further, I highly recommend reading our guide on Init-Only Properties in C# 9 here.Record types in C# 9 are borderline an extension of the level of immutability that init-only properties give, and so much of this article will refer back to that. CREATING MODERN AND HELPFUL COMMAND LINE UTILITIES WITH System.CommandLine is actually in beta right now. To install the current beta in your application you would need to run the following from your Package Manager Console. Install-Package System.CommandLine -Version 2.0.0-beta1.20574.7. Or alternatively if you’re trying to view it via the Nuget Browser in Visual Studio, ensure you have RELATIONAL PATTERN MATCHING IN C# 9 Relational Pattern Matching In Switch Statements/Expressions. Now we are cooking with gas. In C# 9, we can now turn this big case statement : case int value when value > 0 && value 0 and Options, then select Preview Features as per the screenshot below. Make sure to tick the “Use previews of the .NET Core SDK”. Without this, Visual Studio will use the latest version of the .NET SDK installed, that is *not* a preview version. Obviously once .NET 6 is out of preview, you won’t need to do this, but if you are CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but READING EXCEL FILES IN .NET CORE Opening Excel files in code has been a painful experience long before .NET Core came along. In many cases, you actually needed the Excel application installed on the target/users machine to be able to open excel files via code. If you’ve ever had to use those “OLE DB Jet”
LOADING AND PARSING A WEB PAGE IN .NET CORE Many years back, I actually started programming so that I could cheat at an online web browser based game (I know, I know). I started in Pascal/Delphi, but quickly moved onto C#. Back then, I was using things like HttpWebRequest/Response to load the webpage, and using raw regex to parse it. Looking back, some of SINGLETON PATTERN IN .NET CORE Let’s push .NET Core specifically to one side and actually look at how we might achieve a singleton pattern in just C#. Again, Wikipedia kind of gives us some hints on how we might achieve this. It states : Declaring all constructors of the class to be private; and. Providing a static method that returns a reference to the instance. CREATING A PDF IN .NET CORE Introduction. It’s a pretty common use case to want to generate PDF’s in C# code, either to serve directly to a user or to save locally. When I came to do it recently, suddenly I was over(and under)whelmed with the options available to actually achieve this. ROWVERSION VS CONCURRENCYTOKEN IN ENTITYFRAMEWORK/EFCORE RowVersion (Also known as Timestamp, they are the same thing), is a SQL column type that uses auto generated binary numbers that are unique across that database, and stamped on records. Any time a record is inserted or updated on a table with a row version, a new unique number is generated (in binary format) and given to that record. SETTING JSON SERIALIZATION CONFIGURATION AT RUNTIME ON A I’m currently living the whole snake case vs camel case argument all over again. Me being a web developer, I prefer camel case (myVariable) as it fits nicely with any javascript code. Others, in what seems predominately iOS developers, prefer to use snake case (my_variable). Typically it’s going to be personal preference and on any CLONING OBJECTS IN C# AND .NET CORE Cloning objects in any programming language is tricky, but I think in C# that’s taken up an extra notch by giving you a couple of tools that look like they would probably solve your problem, but then not letting you know that it’s likely to only solve a very slim use caseand nothing else.
USING AZURE COSMOSDB WITH .NET CORE This post is part of a series on using Azure CosmosDB with .NET Core Part 1 – Introduction to CosmosDB with .NET Core Part 2 – Azure CosmosDB with .NET Core EF Core I haven’t used CosmosDB an awful lot over the years, but when I have, It’s been a breeze to use. It’snot
GETTING SETUP WITH .NET 6 PREVIEW Go Tools -> Options, then select Preview Features as per the screenshot below. Make sure to tick the “Use previews of the .NET Core SDK”. Without this, Visual Studio will use the latest version of the .NET SDK installed, that is *not* a preview version. Obviously once .NET 6 is out of preview, you won’t need to do this, but if youare
CREATING WINDOWS SERVICES IN .NET CORE This article is part of a series on creating Windows Services in .NET Core. Part 1 – The “Microsoft” Way Part 2 – The “Topshelf” Way Part 3 – The “.NET Core Worker” Way Creating Windows Services to do batch jobs or in general do background work used to be a pretty common pattern, but READING EXCEL FILES IN .NET CORE Opening Excel files in code has been a painful experience long before .NET Core came along. In many cases, you actually needed the Excel application installed on the target/users machine to be able to open excel files via code. If you’ve ever had to use those “OLE DB Jet”
LOADING AND PARSING A WEB PAGE IN .NET CORE Many years back, I actually started programming so that I could cheat at an online web browser based game (I know, I know). I started in Pascal/Delphi, but quickly moved onto C#. Back then, I was using things like HttpWebRequest/Response to load the webpage, and using raw regex to parse it. Looking back, some of SINGLETON PATTERN IN .NET CORE Let’s push .NET Core specifically to one side and actually look at how we might achieve a singleton pattern in just C#. Again, Wikipedia kind of gives us some hints on how we might achieve this. It states : Declaring all constructors of the class to be private; and. Providing a static method that returns a reference to the instance. CREATING A PDF IN .NET CORE Introduction. It’s a pretty common use case to want to generate PDF’s in C# code, either to serve directly to a user or to save locally. When I came to do it recently, suddenly I was over(and under)whelmed with the options available to actually achieve this. ROWVERSION VS CONCURRENCYTOKEN IN ENTITYFRAMEWORK/EFCORE RowVersion (Also known as Timestamp, they are the same thing), is a SQL column type that uses auto generated binary numbers that are unique across that database, and stamped on records. Any time a record is inserted or updated on a table with a row version, a new unique number is generated (in binary format) and given to that record. SETTING JSON SERIALIZATION CONFIGURATION AT RUNTIME ON A I’m currently living the whole snake case vs camel case argument all over again. Me being a web developer, I prefer camel case (myVariable) as it fits nicely with any javascript code. Others, in what seems predominately iOS developers, prefer to use snake case (my_variable). Typically it’s going to be personal preference and on any HOW TO PARSE XML IN .NET CORE One of the most popular posts on this blog is a very simple write-up on how to parse JSON in .NET Core.I mostly wrote it because I thought that there was definitely a “proper” way of doing things, and people were almost going out of their way to make USING NEWTONSOFT.JSON IN .NET CORE 3+ PROJECTS Recently I’ve been working a lot in .NET Core 3.0 and 3.1 projects. Both upgrading existing 2.2 projects and a couple of new greenfields projects. The thing that I’ve had to do in each and every one is switch from using the new System.Text.Json package back to usingNewtonsoft.Json. In
FIXING "THIS ASYNC METHOD LACKS 'AWAIT' OPERATORS AND WILL This little “warning” has been the bain of my life recently warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run()’ to do CPU-bound work on a background thread. And after a bit of searching around, I justwanted to
FIXING JSON SELF REFERENCING LOOP EXCEPTIONS And for Newtonsoft.Json (Or JSON.NET as it’s sometimes called, default for .NET Core 2.2 and lower) : JsonSerializationException: Self referencing loop detected with type. They mean essentially the same thing, that you have two models that reference each other and will cause an infinite loop of serializing doom. KNAPSACK ALGORITHM IN C# The Knapsack Problem is where you have a “bag” that can hold a limited number of items, given that you have a set of items to choose from each with individual “values”, how can you maximize filling your bag with only the most valuable items. Let’s take a real world example. A robber has broken into a jewellery store and wants to steal SETTING JSON SERIALIZATION CONFIGURATION AT RUNTIME ON A Awesome! So here we have managed to create our own resolver and naming strategy to allow clients to specify which naming convention they want. To be honest, it’s still a work of progress and this thing is definitely at the proof of concept stage, I’m still getting to grips on the internal workings of JSON.net, but it’s definitely a good start and OK to use on any small project you have USING THE ILOGGER BEGINSCOPE IN ASP.NET CORE While working on another post about implementing your own custom ILogger implementation, I came across a method on the ILogger interface that I had never actually used before. It looks something like _logger.BeginScope(“Message Here”); , Or correction, it didn’t just take a string, it could take any type and use this for a “scope”. It intrigued CSV PARSING IN .NET CORE A CSV may or may not have a header row. If there is a header row, then the order of the columns is not important since you can detect what is actually in each column. If there is no header row, then you rely on the order of the columns being the same. Any CSV parser should be able to both read columns based on a “header” value, and by index. REQUEST CULTURE IN ASP.NET CORE Culture in ASP.net has always been a bit finicky to get right. In ASP.NET Core there is no exception but with the addition of middleware, things are now configured a little differently. Lifting and shifting your standard ASP.NET code may not always work in USING MAILKIT TO SEND AND RECEIVE EMAIL IN ASP.NET CORE In previous posts I’ve talked about how you can now use the legacy SMTPClient class inside .NET to send emails.As commentators on this post have pointed out however, this has now been deprecated and the official documentation actually points you towards a very popular email library called “MailKit“. It’s open source, it’s super extensible, and it’s built on .NET Standard meaning__ __
* About
* Consulting/Speaking* Contact
Search
RECENT POSTS
* Dapper In .NET Core – Part 4 – Dapper Contrib * Dapper In .NET Core – Part 3 – Updates/Inserts/Deletes * Dapper In .NET Core – Part 2 – Dapper Query Basics * Dapper In .NET Core – Part 1 – The What/Why/Who * What Does The CreateDefaultBuilder Method Do In ASP.NET Core?POPULAR POSTS
* Using Automapper In ASP.net Core * Sending Email In .NET Core 2.0 * How To Target .NET Core 2.2 * CSV Parsing In .NET Core * Publishing A Single EXE File In .NET Core 3.0 * Cannot Consume Scoped Service From Singleton – A Lesson In ASP.net Core DI Scopes * Uploading Images In A Pure JSON API * Uploading Files In ASP.NET Core * IAsyncEnumerable In C# 8 * Using MailKit To Send And Receive Email In ASP.NET CoreCATEGORIES
* Coding Tutorials
* General/News
* Hosting/Deployments * Integration Tutorials* Tooling Tutorials
DAPPER IN .NET CORE – PART 4 – DAPPER CONTRIBAugust 5, 2019
by Wade ·0 Comments This article is a series on using Dapper in .NET Core. Feel free to jump around, but we highly recommend you start in Part 1 and work yourway through!
Part 1 – The What/Why/Who Part 2 – Dapper Query Basics Part 3 – Updates/Inserts/Deletes PART 4 – DAPPER CONTRIB ------------------------- WHAT IS DAPPER CONTRIB? Dapper.Contrib is a “helper” library built on top of Dapper, that adds a couple of “quality of life” enhancements to otherwise annoying Dapper hurdles. Most notably, updates and inserts become much simpler with Dapper.Contrib. So let’s jump right in! INSTALLING DAPPER.CONTRIB From your Package Manager console window you can install the Dapper.Contrib package.1
Install-Package Dapper.Contrib If you haven’t already installed Dapper, this will drag Dapper in as a dependency too! Note that at times you do have to do a juggle with versions of Dapper if you install it first, then Contrib second. The easiest way if you really want to use Contrib is remove the direct reference to the Dapper nuget, and simply install Contrib and let it drag in the version it needs. MODEL OUR C# CLASS FOR WRITES IN DAPPER.CONTRIB The important thing when using Dapper.Contrib is that you need a C# model to match that of your database model. Again I can’t stress enough that this should really only be used in the case of _writes_. When reading data, the entire point of using Dapper is that you don’t over-select and so you should attempt to use applicable DTO’s whenever possible. From earlier, we have our C# model ready to go :1
2
3
4
5
6
7
8
class Event
{
public int Id { get; set; } public int EventLocationId { get; set; } public string EventName { get; set; } public DateTime EventDate { get; set; } public DateTime DateCreated { get; set; }}
This works as is, but there are a couple of things to note. Firstly, Dapper.Contrib requires an “Id” to be able to update a record. In our case, we have a property called “Id” and Dapper.Contrib uses this convention and knows it’s our primary key on our table. But what if we use something like “EventId” as our primary key? That’s easy too.1
2
3
4
5
6
7
8
9
class Event
{
public int Id { get; set; } public int EventLocationId { get; set; } public string EventName { get; set; } public DateTime EventDate { get; set; } public DateTime DateCreated { get; set; }}
We just add the “Key” attribute from our Dapper.Contrib library to tell it that’s our primary key. Next, we are also required that the class name be the same as the SQL Table name, but as a plural. So in our case, our class name is Event and it expects that our database table be called “Events”. So how can we say nope, we want to stick with the singular?1
2
3
4
5
6
7
8
9
class Event
{
public int Id { get; set; } public int EventLocationId { get; set; } public string EventName { get; set; } public DateTime EventDate { get; set; } public DateTime DateCreated { get; set; }}
Again, another attribute. There is actually a couple more attributes that do come in handy, but these are the main ones you should knowright off the bat.
INSERTING RECORDS USING DAPPER.CONTRIB This should hopefully make things easier.1
2
3
4
5
6
7
8
9
10
11
using (SqlConnection connection = new SqlConnection(connectionString)){
var newEvent = new Event{
EventLocationId = 1, EventName = "Contrib Inserted Event", EventDate = DateTime.Now.AddDays(1), DateCreated = DateTime.UtcNow};
connection.Insert(newEvent);}
… Pretty awesome right! So we are back to having this nice “Insert” method that takes our object and creates an insert statement. It takes some of that perfect control away from us, but when it comes to inserts there isn’t much that we would want to be careful of when it comes to generating the insert statement so I’mhappy with it.
GET A RECORD BY ID USING DAPPER.CONTRIB Contrib also has this nifty feature where it can get a full record by Id. I feel like this sort of strays a little from the intention of Dapper because you should be trying to avoid doing a “SELECT *” and instead only get what you need. But we’ll use it later so I wanted to show it off.1
2
3
4
5
using (SqlConnection connection = new SqlConnection(connectionString)){
var eventId = 1;
var myEvent = connection.Get}
Because it knows we are requesting a type of “Event”, it knows what table that’s from and grabs us the entire object based on it’s primary key Id. UPDATING RECORDS USING DAPPER.CONTRIB Contrib can also do updates. Although they are a little less slick. First off, we can obviously get our object by ID, update it, thenwrite it like so :
1
2
3
4
5
6
7
using (SqlConnection connection = new SqlConnection(connectionString)){
var eventId = 1;
var myEvent = connection.Get}
So Contrib has given us that handy “Update” method. But the problem is when we check the actual SQL that got run :1
2
exec sp_executesql N'update Event set = @EventLocationId, = @EventName, = @EventDate, = @DateCreated where = @Id', N'@DateCreated datetime,@EventDate datetime,@EventLocationId int,@EventName nvarchar(4000),@Id int',@DateCreated='2019-01-20 02:11:46.453',@EventDate='2019-01-11 00:00:00',@EventLocationId=1,@EventName=N'New Name',@Id=1 So it basically updated ALL fields even if they weren’t touched. Because of this we HAVE to get the record by Id before updating because we need to make sure all other fields (Not just the one we want to update) are set correctly. Now Dapper.Contrib does have dirty tracking, but IMO that’s just as pointless as you still need to get the full object by ID in the first place to do entity tracking, and the entire point is that we aren’toverselecting.
In my opinion, Updates are still a good candidate for doing custom SQL instead of using Contrib, but that’s just my personal feeling! DELETE RECORDS USING DAPPER.CONTRIB Deleting is actually fairly simple. As long as Dapper.Contrib knows what your primary key is, it can delete records based on that.1
2
3
4
using (SqlConnection connection = new SqlConnection(connectionString)){
connection.Delete(new Event { Id = 5 });}
To be honest, this syntax annoys me somewhat as we are creating an object for no reason! Wouldn’t it just be easier to pass in a simpleInt parameter?
WHAT’S NEXT?
That’s actually it! We could get into the nitty gritty of Dapper, or even explore some of the other Dapper extension libraries such as Dapper.Rainbow or DapperExtensions, but they are largerly the same as Dapper.Contrib with minor differences. They are definitely worth investigating however! Feel free to drop a comment below on your thoughts on Dapper and what project’s you’ve used it on in the past, I’d love to hear them! DAPPER IN .NET CORE – PART 3 – UPDATES/INSERTS/DELETESAugust 5, 2019
by Wade ·0 Comments This article is a series on using Dapper in .NET Core. Feel free to jump around, but we highly recommend you start in Part 1 and work yourway through!
Part 1 – The What/Why/Who Part 2 – Dapper Query Basics PART 3 – UPDATES/INSERTS/DELETES Part 4 – Dapper Contrib -------------------------UPDATING A RECORD
So.. Here’s where things with Dapper get kinda rough. You see, to update a record we use the “Execute” method from Dapper like so :1
2
3
4
using (SqlConnection connection = new SqlConnection(connectionString)){
connection.Execute("UPDATE Event SET EventName = 'NewEventName' WHERE Id = 1");}
And of course you can use parameters with the execute statement also. So we could change that to look like :1
2
3
4
5
6
using (SqlConnection connection = new SqlConnection(connectionString)){
var eventName = "NewEventName";var eventId = 1;
connection.Execute("UPDATE Event SET EventName = @EventName WHERE Id = @EventId", new { EventName = eventName, EventId = eventId });
}
I mean yeah, it works but… It’s kinda rough right? Imagine if we wanted to update multiple fields at once how unweildy this statement might get. But then again, maybe that’s good. We are only updating exactly what we want to update and nothing more. It’s sort of a “Great power comes great responsibility” typeissue.
INSERTING A RECORD
If you thought updating a record was rough, wait till you seeinserting.
1
2
3
4
using (SqlConnection connection = new SqlConnection(connectionString)){
connection.Execute("INSERT INTO Event (EventLocationId, EventName, EventDate, DateCreated) VALUES(1, 'InsertedEvent', '2019-01-01', GETUTCDATE())");}
Again… It’s pretty basic. Infact all dapper is really doing is executing our insert statement, but we are kinda doing all the leg work here. Similar to updating, we can use parameters here to clean the values up a bit, but it’s still a lot of manual work. Obviously each time we create a new column, we need to come back to this statement and make sure it works as we intend it to.DELETE A RECORD
No big surprises here.1
2
3
4
using (SqlConnection connection = new SqlConnection(connectionString)){
connection.Execute("DELETE FROM Event WHERE Id = 4");}
The execute method kinda becomes our catch all for “Execute this statement and don’t worry about the result”.HOW ABOUT CQRS?
It’s pretty common for CQRS to be a hot topic when talking about Dapper. After all, we’ve kind of seen that while reading data in Dapper is super powerful, slick, and easy. Writing feels cumbersome. For this reason I’ve found myself using doing writes using a different ORM (EF or NHibernate), but sticking with Dapper for querying. It works, but it’s not required (As we will soon see!).WHAT’S NEXT?
So updating and inserting records is a bit oof. But there is an extension library for Dapper called Dapper.Contrib that actually makes this super simple. Let’s take a look at that! DAPPER IN .NET CORE – PART 2 – DAPPER QUERY BASICSAugust 5, 2019
by Wade ·0 Comments This article is a series on using Dapper in .NET Core. Feel free to jump around, but we highly recommend you start in Part 1 and work yourway through!
Part 1 – The What/Why/Who PART 2 – DAPPER QUERY BASICS Part 3 – Updates/Inserts/Deletes Part 4 – Dapper Contrib -------------------------INSTALLING DAPPER
Dapper is a nuget package that does nothing more than “augment” the existing SQLConnection object in .NET Core….. Reading that line back I’m not sure it makes sense but hopefully it will at the end. In simple terms you can install the Dapper nuget package by running the following from your Package Manager Console.1
Install-Package Dapper In the following examples I’m just running them from a simple console application, but you can install Dapper into any type of .NET Full Framework/.NET Core application.FOLLOW ALONG DATA
For much of this tutorial, I’m going to be using some data that I created for a simple “Event” database. There really isn’t much to it, but if you want to follow along at home you can grab the script to create the database/tables/data from this Github Gist here : https://gist.github.com/mindingdata/00c2d608c4a0b4ea22e76e95c1d1417e It’s not required and for the most part everything we do here will be super simple. But if you want to write the queries in your own console application as we go, that’s cool too! CREATING A DATABASE CONNECTION As you might have seen earlier, when using Dapper we have to create our own SQL Connection to the database. Dapper doesn’t do this for us. But.. It’s simple enough. For example in a console application that I’ve already installed Dapper from Nuget in, all it takes is :1
2
3
4
5
6
7
8
9
static void Main(string args){
var connectionString = "Data Source=(local);Initial Catalog=DapperExample;Integrated Security=SSPI"; using (SqlConnection connection = new SqlConnection(connectionString)){
//Do some magic here}
}
That’s it! We now have a connection to our database that is “Dapper” ready. You’ll also notice that at this point, the only “Using” statement we would actually be using is using System.Data.SqlClient; . That’s because the SqlConnection object is the regular one from the .NET library, so far we haven’t even usedDapper yet!
QUERY A SINGLE ROW
Let’s add some magic and actually get the above SQL Connection actually doing something. In my example database, I have a table called “Event” that has a list of events in it. I want to know specifically what the name of the event is with the Id of 1.1
2
3
4
5
6
using (SqlConnection connection = new SqlConnection(connectionString)){
var eventName = connection.QueryFirstConsole.ReadLine();
}
… That’s it. We can of course write our initial SQL in something like SQL Management Studio, and then copy it across. We have complete control over the query and it’s going to run *exactly* what we toldit to.
The actual magic part of this is the “QueryFirst” method on our connection. If we jump into the source code of Dapper we can see this is just an extention method on the SqlConnection object.1
public static T QueryFirst1
2
3
4
5
6
7
class Event
{
public int Id { get; set; } public int EventLocationId { get; set; } public string EventName { get; set; } public DateTime EventDate { get; set; }}
Then we modify our statement a bit to instead be a SELECT * and instead use the return type of Event instead of string. So it lookslike so :
1
2
3
4
5
6
using (SqlConnection connection = new SqlConnection(connectionString)){
var myEvent = connection.QueryFirstConsole.ReadLine();
}
If you’ve ever used raw ADO statements before in .NET, you’ll know the pain of manually mapping each property from the database to our C# class. But Dapper does that all for us. It takes the results from the statement, and checks to see if there is a property with the same name as a column, if there is, great map it! If not, don’t worry, just throw it away for now. QUERY STATEMENT INTO A DTO So the above example maps an entire database table to a C# class, but the annoying part of that is maybe we don’t need everything. Infact a very common SQL performance issue is overselecting. In our above example we actually only use the Id and EventName fields, so let’s first create a DTO with only those fields.1
2
3
4
5
class EventDto
{
public int Id { get; set; } public string EventName { get; set; }}
Then we can modify our query a bit to only select the columns we need, and make Dapper map it to our DTO :1
2
3
4
5
6
using (SqlConnection connection = new SqlConnection(connectionString)){
var myEvent = connection.QueryFirstConsole.ReadLine();
}
Too easy!
USING PARAMETERIZED QUERIES We haven’t really been taking user input at this point. But let’s pretend instead of always getting the Event with the ID of 1, we allowed the user to specify the Id. How can we pass that to our Dapper query while still following best practice (aka parameterizing thequery).
Well again, Dapper takes care of this for us :1
2
3
4
5
6
7
using (SqlConnection connection = new SqlConnection(connectionString)){
int eventId = 1;
var myEvent = connection.QueryFirstConsole.ReadLine();
}
Pretend that eventId actually came from a GET param or any other user input. All we do is substitute an @VariableName in our SQL statement, then we add a new parameter of an anonymous object where the “Key” is the same as the @VariableName and the value is what you want it tobe.
But why couldn’t I just change the line to the following?1
var myEvent = connection.QueryFirst1
exec sp_executesql N'SELECT Id, EventName FROM Event WHERE Id = @Id',N'@Id int',@Id=1 Notice how the parameter is specified after the query, and yet for the second example where we just use string substitution :1
SELECT Id, EventName FROM Event WHERE Id = 1 Uh Oh, no parameters here. This opens us up for SQL Injection a plenty. But again, Dapper handles this for us with properparameterization!
QUERY MULTIPLE ROWS
Up until now, we’ve been querying just a single row at a time. If we want more than one, that’s just as easy :1
2
3
4
5
6
7
8
9
using (SqlConnection connection = new SqlConnection(connectionString)){
var allEvents = connection.Query{
Console.WriteLine(myEvent.Id + " : " +myEvent.EventName);
}
Console.ReadLine();
}
We just change our “QueryFirst” to a “Query” and away we go! We are instead returned a list of mapped objects which we can cycle through. Pretty easy stuff!WHAT’S NEXT
With the basics of querying using Dapper out of the way, obviously reading and writing is up next! You can check that out here! DAPPER IN .NET CORE – PART 1 – THE WHAT/WHY/WHOAugust 3, 2019
by Wade ·0 Comments This article is a series on using Dapper in .NET Core. Feel free to jump around, but we highly recommend you start in Part 1 and work yourway through!
PART 1 – THE WHAT/WHY/WHO Part 2 – Dapper Query Basics Part 3 – Updates/Inserts/Deletes Part 4 – Dapper Contrib ------------------------- For some time now I’ve been a huge fan of using Dapper in both personal and commercial projects. With more and more projects lending themselves to Microservices architecture, or at the very least a large application being made up of many smaller components, Dapper justmakes sense.
But I’m getting a little tired of telling the same story of what Dapper is and what it’s capable of doing, so here’s my attempt at a “crash course” in Dapper with .NET Core.WHAT IS DAPPER?
Dapper is classed as a “micro” ORM. That is, it’s an ORM but is extremely lightweight and gives only very basic functionality. Whereas we might class something like Entity Framework or NHibernate as a fully featured heavyweight ORM, Dapper provides minimal overhead and really only helps you out with some core basics. Put simply, it runs your database queries from your .NET Core code, and returns results in an easy to manage fashion.WHY DAPPER?
The core reason people tend to pick Dapper over something like Entity Framework is the control it affords. Under Dapper, gone are the days of using a long complex LINQ queries that generate ghastly SQL that would make any DBA shriek at first sight. Infact, with Dapper you know exactly what SQL is going to be executed…. because you wrote it. As an example, if I have a “Event” table where I want to get the “EventName” of the record with an “Id” of 1. That would looklike :
1
2
3
4
5
6
7
8
9
10
11
static void Main(string args){
var connectionString = "Data Source=(local);Initial Catalog=DapperExample;Integrated Security=SSPI"; using (SqlConnection connection = new SqlConnection(connectionString)){
var eventName = connection.QueryFirstConsole.ReadLine();
}
}
No ambiguity here, I know EXACTLY what’s going to get run. But that probably leads us to the question of “_When should I NOT use Dapper_“. And it’s actually a pretty good question. Realistically I think there are two types of developers/projects that mean that Dapper may not be on the cards. The first is if you are thinking of moving an existing project to Dapper, and that project already makes heavy use of things like EntityTracking in Entity Framework – or really any Entity Framework specific feature, then Dapper may be a stretch. There is no entity tracking to speak of in Dapper – atleast out of the box (It’s all just POCO’s), so if you are expecting some of that EF magic, Dapperisn’t for you.
The second is actually developer specific and I debate if I should even put this in here. When trying to teach junior developers Dapper, they get annoyed that they have to write raw SQL. Personally I think if you are interacting with a database at all you should know SQL to a pretty high degree. But some developers really are just happy using the LINQ they already know and love, and for some the learning curve of ASP.NET Core is large enough without adding in databases to the mix. If that’s you, and you are just getting started with C# and don’t want to learn SQL just yet, then yeah, maybe this isn’t foryou.
WHO IS BEHIND DAPPER? The brains behind Dapper are the guys over at StackOverflow. It was created because the burden on the web servers of simply taking the LINQ2SQL statements and generating SQL was often making their web boxes hit 100% CPU. Coupled with the fact that you couldn’t actually control what SQL was output from your LINQ, Dapper was born. Best of all, Dapper is completely open source . That means you can go check out how things work, and even fix bugs if you feel that way inclined!NEXT TIME
So with our history lesson out of the way, let’s actually get stuck in and write some simply Dapper statements. Click here to get cracking on Querying With Dapper.
WHAT DOES THE CREATEDEFAULTBUILDER METHOD DO IN ASP.NET CORE?July 31, 2019
by Wade ·0 Comments If you’ve started a new ASP.NET Core project recently, chances are you would have seen the following lines :1
2
3
public static IWebHost BuildWebHost(string args) => WebHost.CreateDefaultBuilder(args) .UseStartup.Build();
And chances are, you’ve also followed a tutorial that was written about a year ago that doesn’t include this line and instead has this big long winded builder instead :1
2
3
4
5
6
var host = new WebHostBuilder().UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup.Build();
Or maybe you could be coming here because you’ve been told to add the following configuration lines somewhere in your code :1
2
3
4
var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange:true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:true);
But yours just “works” without it. Somehow. Magically. I know that people comment on old tutorials from 2+ years ago that their boilerplate code no long matches what they get when creating a new project in Visual Studio. I’ve thought about going back and editing all tutorials, but instead I felt it was important to understand the simplicity of what’s going on here and that it’s really not such a big deal.Let’s demystify.
OPENING UP THE CODE
Before we go much further I have to say that until a few years back, I probably wasn’t as big on the open source train as I could be. But with ASP.NET being open source, I lost count of how many times I just skipped the documentation and went to the actual source code to work out what was going on or how I should approach something. This is oneof those times!
We can actually head to the source code for CreateDefaultBuilder andtake a look
!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static IWebHostBuilder CreateDefaultBuilder(string args){
var builder = new WebHostBuilder(); builder.ConfigureAppConfiguration((hostingContext, config) =>{
var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);})
}
I’ve removed a lot of code for brevity. But as we can see, the CreateDefaultBuilder actually adds in both appsettings.json and the appsettings for our current environment. Hence why we don’t see configuration code being required elsewhere! If we look deeper into the code we can actually see it doing a lot more of the work that we previously had to build ourselves. WHAT ELSE IS DONE FOR US? When we use the CreateDefaultBuilder method, out of the box we get : * Sets the “Content Root” to be the current directory * Allows Command Line args to be pushed into your configurationobject
* Adds both appsettings.json and appsettings.{Environment}.json to be loaded into the configuration object * Adds environment variables to the configuration object * If in Development, allows the loading of secrets.
* Adds Console/Debug loggers * Tells the app to use Kestrel and to load Kestrel configuration fromthe loaded config
* Adds Routing
* Adds IIS Integration That sounds like a lot, but if we again go back to what we used towrite :
1
2
3
4
5
6
var host = new WebHostBuilder().UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup.Build();
It’s just now doing all of this under the hood for us (and more!).Nice!
.NET CORE 3.0 (PREVIEW 7) RELEASEDJuly 25, 2019
by Wade ·0 Comments .NET Core 3.0 Preview 7 has been released as of July 23rd. You can grab it here : https://dotnet.microsoft.com/download/dotnet-core/3.0WHAT’S INCLUDED
The official post from Microsoft is here : https://devblogs.microsoft.com/dotnet/announcing-net-core-3-0-preview-7/ but you’re not going to find anything shiny and new to play with. Infact the post explicitly states “_The .NET Core 3.0 release is coming close to completion, and the team is solely focused on stability and reliability now that we’re no longer building new features_“. So if something hasn’t made it into .NET Core 3.0 by now, you might be waiting until 3.1. But that doesn’t mean we can’t take a look at what’s been happening under the hood. So I took a look at the Github issue list to see what did make it to this release, even if it wasn’t worth a shout out in the official blog post. In particular, there seems to be two main areas that has garnered quite a few taggings.JSONSERIALIZER BUGS
Unsurprisingly with .NET Core moving away from JSON.NET and instead moving to use their own JSON Serializer, there has been bugs a plenty. At a glance, it mostly looks like edgecase stuff where in particular scenarios, serializing and deserializing is not working as expected. Things like JSON Should be able to handle scientific notation.BLAZOR BUGS
Blazor has been getting a major push recently – I’m seeing it show up more and more in my twitter feed. And along with people using it for realworld work loads, comes people logging bugs. To be brutally honest, I haven’t used Blazor at all. It feels like it’s trying to solve a problem that doesn’t exist somewhat like the early days of ASP.NET WebForms. (And feel free to drop a comment below about how I’m totally wrong on that!).WORTH UPDATING?
One thing worth mentioning is that Microsoft say “_NET Core 3.0 Preview 7 is supported by Microsoft and can be used in production_“. So they obviously feel confident enough that this is a proper Release Candidate. But in terms of getting this because there is something new in there that you definitely need to get a hold of, it’s probably worth skipping for now. CREATING A PDF IN .NET COREJuly 2, 2019
by Wade ·7 Comments So… This post spun a little out of control. What turned into a hunt for a simple use case (Turn an HTML string into a PDF) turned into a full blown thesis. So here’s some quick links to jump to various parts of the article if you are coming here straight from Google, it may make things a bit easier. But I do highly recommend reading from the start to get an idea of what PDF Generation really looks like on.NET Core.
* Introduction
* What I Was Looking For* PDF Sharp
* SelectPDF
* IronPDF
* The Rest (WKHTMLTOPDF, Spire PDF, EO PDF, Aspose PDF, ITextSharp)* Summary
-------------------------INTRODUCTION
It’s a pretty common use case to want to generate PDF’s in C# code, either to serve directly to a user or to save locally. When I came to do it recently, suddenly I was over(and under)whelmed with the options available to actually achieve this. Certainly natively, there is nothing in C# or .NET Core that can generate PDF’s for you. And when it came to actually looking at feature sets of third party libraries (e.g. I want to use HTML as a template option), there were all sorts of problems. So with that being said, instead of giving you code to generate a PDF with a particular PDF library, I’ll talk about how I evaluated eachoption.
------------------------- WHAT I WAS LOOKING FOR Before I set out on my journey, I wrote down 3 really crucial points that I would judge the libraries on. These aren’t too complex or even that much of an ask (Or so I hoped).PRICE
Obviously free is ideal. Something open source that I can debug myself is even better. But if I do have to pay for a “premium” library. I’m looking for a one time fee that isn’t some stupid “per user/seat/machine/server” model. If I’m looking at this library as a company, I don’t want future architecture or decisions to be made based on the pricing of a library. If there is some sort of freemium model in play, then I also wanted to make sure that the limitations weren’t too crazy (e.g. single pages only, set number of images allowed per PDF). Freemium is OK as long as the free version is actually useable. HTML TEMPLATING (OR SOMETHING CLOSE) I had already decided that I wanted to use HTML as my templating mechanism. I was open to using some other reasonable alternative (e.g. HTML with some XSLT engine), but ideally I just want to feed an HTML file to the library and out comes my PDF. What I really don’t want to do is have to place each element manually on the PDF like we had to back in the day when printing a document from a WinForms application. EASE OF USE/ALL IN ONE This is probably a pretty subjective one, but when you start seeking out libraries from the corners of the web or that stackoverflow answer from 3 years ago, you often end up getting some really half baked library that just doesn’t work. Whether it’s some C++ library converted to C#, a library that needs X number of other libraries to actually function, or things just plain don’t work how they should, I’m probably going to see it all. So above else, I just want to be up and running in minutes, not hours. -------------------------PDF SHARP
First up is PDF Sharp, I feel like I’ve used this one previously but I’m not entirely sure. The whole ____Sharp thing was all the rage in the early days of C#. Anyway straight off the bat PDFSHARP DOES NOT WORK WITH .NET CORE. There may be ported versions floating around but the version on Nuget does not support .NET Core. So it’s pretty much dead in the water. But this one was suggested to me over and over so I still want to do a quick write up about it.PRICE
PDF Sharp is free and open source. They do offer paid support but don’t give any specifics on how this works and how much it costs. Free is free though so you can’t complain too much.HTML TEMPLATING
Oh boy. HTML Templating doesn’t make it into the PDF Sharp library unfortunately. Instead we are stuck with writing syntax like we are back in the GDI+ dark days of C# :1
2
3
4
5
6
7
8
// Get an XGraphics object for drawing XGraphics gfx = XGraphics.FromPdfPage(page);// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center); I get it that this was what you had to do in the year 2000, but it’s just not going to fly right now. There are ways around this using another library that extends PDFSharp… But that’s still another library that you have to grab and work with. So basically, in terms of a decent template engine out of the box, it’s a fail.EASE OF USE
Well. It doesn’t work with .NET Core which is probably going to be a blocker. The last published version was 2013. And it doesn’t have HTML rendering packaged (And the library that currently does extend it to do HTML templating also doesn’t support .NET Core). So all in all. Forget about it. -------------------------SELECTPDF
I got pushed to SelectPDF by a tonne of stackoverflow answers (Kinda felt like maybe they were astroturfing a little…). It’s a paid library (Which made it all the more annoying they were commenting on stackoverflow answers with “Sure just use this great library called SelectPDF” and not mentioning the cost), But regardless I wanted to check them out and see what they offered.PRICE
It ain’t free, that’s for sure. Licensing starts at $499 and goes up to $1599. Interestingly they do offer an online version where they can generate the PDF for you by sending a URL or HTML code. Honestly I think that’s way more interesting as a business model, but the pricing again starts at $19 but goes all the way up to $449 a month so I can’t really see many people taking this option. EDIT : So weirdly enough, there seems to be a “hidden” free community edition that you can only find via a tiny footer link. You can read more about the Community Edition here . It seems like the only limitation is that you can’t generate PDFs over 5 pages. Doesn’t seem to be any limitation on commercial use. But again, seems strange to only make this a tiny footer link and not sure it anywhere else…HTML TEMPLATING
HTML Templating is definitely here. And it seems to work well. In just a few lines we are up and running. While documentation is pretty good, I found it sort of all over the place. Loading HTML from a string versus loading HTML from a URL was all mixed together and so when reading examples, you had to check the code example to see what it was actually used for. But that being said, HTML Templating works so tick!EASE OF USE
Here’s the code to render HTML :1
2
3
4
5
6
var myHtml = "Test
Test Bold
"; HtmlToPdf converter = new HtmlToPdf(); PdfDocument doc = converter.ConvertHtmlString(myHtml); doc.Save("output.pdf");doc.Close();
So on that level, ease of use seems good. I would say that many code examples were done using old school .NET WebForms which made me uneasy. Not sure why but using such an old technology like that doesn’t make me feel like I’m using the best in class. It’s hard to fault SelectPDF on the actual bones of what it’s doing. It generates PDF’s and does what it says on the tin. But I can’t help but feel like it’s a “budget” option for the price – It’s probably the logo not being transparent. -------------------------IRONPDF
Last up, IronPDF . These guys create a bunch of libraries called IRON______ so you may have run into them before. I’ve run into them a few times for their OCR library, and that’s unfortunate because as soon as they came up, I knew the pricing was gonna be out of this world.PRICE
For starters they have all these tiers. Like you can get a single project license, but you have to pay per developer (ugh). But.. If you are a SAAS company, then you have to pay per user of your SAAS product. If you are developing desktop software or something distributed, well that’s a new license again. But let’s just stick with being a SAAS company for now, for 1000+ users I’m going to be paying $1599USD for the library and a years worth of support. In fairness, most large companies aren’t going to bat an eye at that. It’s not super crazy, and it is one off, but it’s stillpretty pricey.
HTML TEMPLATING
Yes and yes. In IronPDF it just works. What impressed me the most about IronPDF was their documentation. It wasn’t just
“Here’s a snippet, good luck!”. They even went as far to show you examples of how you might use Handlebars as a templating engine, implementing page breaks in your HTML, and even watermarking. To say that it’s feature rich would be an understatement.EASE OF USE
Again, IronPDF comes up trumps when it comes to ease of use. In literally 4 lines everything just works and the output PDF is exactlyas it should be :
1
2
3
4
var myHtml = "Test
Test Bold
"; var htmlToPdf = new HtmlToPdf(); var pdf = htmlToPdf.RenderHtmlAsPdf(myHtml); pdf.SaveAs("output.pdf"); Now here I’m using inline HTML, but I can load an HTML file or load a remote URL even and it still just works. Compared to the other libraries we’ve tried, this one is certainly the best when it comesto ease of use.
-------------------------THE REST
Here are the other libraries I looked at but didn’t even bother going past the first hurdle (I sort of learnt my lesson after PDFSharp didn’t even work on .NET Core).WKHTMLTOPDF
This shouldn’t really even be considered on the face of it. WKHTMLTOPDF is actually a binary that can generate PDF’s from HTML files, but there are a bunch of .NET wrappers to make use of it. Just felt odd to me and didn’t feel like a solution as much as it was a bunch of pieces hobbled together that should get you there in the end. Even if you do want to go through that pain, features are rather limited. But it’s free!SPIRE PDF
Ridiculous pricing. Starts at $599 for a single developer and goes up to $9000 for over 10 developers. Might be OK for people who hate money but I skipped this one.EO PDF
Another one for haters of money. Pricing starts at $749 and goes up to $4000. Support for .NET Core also seemed extremely sketchy. With the documentation half saying they support .NET Core, but to target FullFramework
.
ASPOSE PDF
You guessed it, another one with ridiculous pricing. Starts at $999 and goes up to $14000 (Fourteen thousand) for an OEM license that still only allows 10 developers. Of course if you want the enterprise support edition you’re going up to $22000 (Twenty two thousand).Pass.
ITEXTSHARP/ITEXT 7
Hidden pricing which typically means “enterprise” priced where some salesman will call you to sell you on the library. Seems to work on AGPL license for free applications but rather not get into that. -------------------------SUMMARY
So after all of that. Where does it leave us? Honestly in my opinion the only valid option right now to generate PDF’s on .NET Core is IronPDF . I know it costs but relatively speaking, $1500 is actually nothing compared to some of these other libraries. And again in my opinion, it seemed to have the most fully featured API along with the most up to date documentation. If you have another PDF option in .NET Core, feel free to drop a comment below! EDIT : It’s been pointed out that SelectPDF does have a free community so that’s worth a crack too if you really want something out and out free. But it’s definitely still a two horse race. THE PUBLISHTRIMMED FLAG WITH IL LINKERJune 27, 2019
by Wade ·0 Comments In a previous post we looked at how we can publish a single exe from a.NET Core project
.
Now in it, I talk about how the resulting binary is absolutely massive, 70MB for a simple hello world console app! But I also talked about how there are now ways to significantly chop that down. Despite that, when shared with Reddit, there was some comments that weren’t so impressed. Most notably this gem : But that’s cool. For Scellow and anyone else that wasn’t impressed with the size of the exe, let’s look at how we can chop it down. YOU NEED .NET CORE 3.0 (PREVIEW 6+) Like all these features I’m writing about recently, you’re gonna need the very latest version of .NET Core 3.0. At the time of writing it’s Preview 6. Any version earlier will simply not fly. And again, if that isn’t you and you don’t want to muck around with preview versions, then you’ll just have to wait! PUBLISHEDTRIMMED FLAG Before we go on, you might hear IL Linker talked about a lot. Possibly because it’s in the title of this post! But that’s because IL Linker is essentially the backbone of this entire feature. However where previous it was this external tool you had to grab from a nuget feed, now it’s built directly into .NET Core 3.0+ which is pretty impressive! Anyway we previously published our application using the followingcommand :
1
dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true And with that, we ended up with an exe over 70MB big : Not good. But literally all we have to do is add one flag and we can chop it down a bit :1
dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true /p:PublishTrimmed=true So… 29MB. And this is about the time where you go “but shouldn’t this be KB in size?”. And honestly the answer is yes. It should be. But we have to remember that this is still a completely self contained application that doesn’t even require the target machine to know what .NET Core is. So even if we aren’t using things like say.. cryptography so we can get rid of that, there is probably a lot of basic and primitive .NET Core features that we just can’t get ridof.
Still. It’s an exe half the size with no functional differencebetween the two.
REFLECTED ASSEMBLIES Through various forms of reflection, we may end up loading assemblies at runtime that aren’t direct references. Take this (very convoluted) example of loading an assembly at runtime :1
2
3
4
5
static void Main(string args){
Console.WriteLine(Assembly.Load("System.Security").FullName);Console.ReadLine();
}
Now when debugging this locally, and we have .NET Core installed, we ask for System.Security and it knows what that is because we are using the installed .NET Core platform. So running it, we get :1
System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a But if we publish this using the PublishTrimmed flag from the commandline, then run it :
1
2
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Security, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified. Unsurprisingly, we have trimmed a bit too much off. Because I don’t actually reference System.Security anywhere, it’s decided we aren’t actually using it. But there is a way to specify that we know best, and to package it up for us. All we need to do is edit our csproj file for our project and add :1
2
3
June 25, 2019
by Wade ·0 Comments GETTING SETUP WITH C# 8 If you aren’t sure if you are using C# 8, or you know you aren’t and want to know how to access these features. Read this quick guide on getting setup with .NET Core and C# 8.
On top of that, you will need atleast .NET Core 3.0 Preview 2 – The preview is important! And then also, atleast for me, I had issues with Visual Studio going crazy and not accepting Switch Expressions but VS Code was OK. Again, this is almost like early access so if you don’t want to deal with the pain now, wait until .NET Core 3.0 and C# 8 is officially released! EXISTING SWITCH STATEMENTS So just in case we aren’t sure what existing Switch statements look like, let’s grab some super basic dummy code. Let’s say I have a Bank class that has a status. And based on this status I want to work out if I can walk into the bank or not.1
2
3
4
5
6
7
8
9
10
11
class Bank
{
public BankBranchStatus Status {get;set;}}
enum BankBranchStatus{
Open,
Closed,
VIPCustomersOnly
}
So I might have a super simple method like so that returns if I can orcan’t walk in :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
static bool CheckIfCanWalkIntoBankSwitch(Bank bank, bool isVip){
bool result = false;switch(bank.Status)
{
case BankBranchStatus.Open :result = true;
break;
case BankBranchStatus.Closed :result = false;
break;
case BankBranchStatus.VIPCustomersOnly :result = isVip;
break;
}
return result;
}
Now I know this is a super obtuse example but I want to point out acouple of things.
I know that in my example, I’m returning the result anyway, but let’s pretend I want to use the value. Mind you, even if I wanted to I can’t do something like result = switch(bank.Status) to set the result. You’ll also notice just how much cruft there is in this example. Each line needs an almost redundant case and break statement even though it’s just doing one thing each.SWITCH EXPRESSIONS
Again I have to stress that this is only for C# 8 and above! But let’s rewrite this as a switch statement :1
2
3
4
5
6
7
8
9
10
11
static bool CheckIfCanWalkIntoBank(Bank bank, bool isVip){
var result = bank.Status switch{
BankBranchStatus.Open => true, BankBranchStatus.Closed => false, BankBranchStatus.VIPCustomersOnly => isVip};
return result;
}
What the… So straight away look how succinct this is. We can assign the result of our switch statement directly to our variable, and we do away with all of that case/break junk. Pretty nice. Heck we can even rewrite it a bit to return immediately :1
2
3
4
5
6
7
8
9
static bool CheckIfCanWalkIntoBank(Bank bank, bool isVip){
return bank.Status switch{
BankBranchStatus.Open => true, BankBranchStatus.Closed => false, BankBranchStatus.VIPCustomersOnly => isVip};
}
Hell if we really wanted to, we could get rid of some curlys as well :1
2
3
4
5
6
static bool CheckIfCanWalkIntoBank(Bank bank, bool isVip) =>bank.Status switch
{
BankBranchStatus.Open => true, BankBranchStatus.Closed => false, BankBranchStatus.VIPCustomersOnly => isVip};
I’ve been kinda critical with some C# features lately. Namely Default Interface Implementations,
but.. This just makes sense! EXTENDING THIS FURTHER Finally, I want to just riff a little bit and show you even more of what the switch expression can do and/or look like. Some of these are actually existing features in C# to do with pattern matching, but I thought I would throw them in here because while you’re here, you may as well get them all out of the way incase you haven’t seen them yet. Now some of my examples again will seem a bit overkill, but coming up with specific examples to show all of these is actuallypretty hard!
You can use a when statement to further your switch statement. Forexample :
1
2
3
4
5
6
7
8
9
10
static bool CheckIfCanWalkIntoBank(Bank bank, bool isVip){
return bank.Status switch{
BankBranchStatus.Open => true, BankBranchStatus.Closed => false, BankBranchStatus.VIPCustomersOnly when isVip => true, BankBranchStatus.VIPCustomersOnly when !isVip => false};
}
But you can also now do something called Tuple Patterns which means passing more than one parameters to the switch statement.1
2
3
4
5
6
7
8
9
10
static bool CheckIfCanWalkIntoBank(Bank bank, bool isVip){
return (bank.Status, isVip) switch{
(BankBranchStatus.Open, _) => true, (BankBranchStatus.Closed, _) => false, (BankBranchStatus.VIPCustomersOnly, true) => true, (BankBranchStatus.VIPCustomersOnly, false) => false};
}
Note that you can use the under score (_) character to signify that it should match anything. In this case because it doesn’t matter whether they are a VIP, if the bank is closed it’s closed, then whatever that value is just match it. And finally, you actually can now pass objects to a switch statement and inspect their properties!1
2
3
4
5
6
7
8
9
static bool CheckIfCanWalkIntoBank(Bank bank, bool isVip){
return bank switch
{
{ Status : BankBranchStatus.Open} => true, { Status : BankBranchStatus.Closed } => false, { Status : BankBranchStatus.VIPCustomersOnly } =>isVip
};
}
This is so that instead of creating a Tuple from your properties, you just pass in the single object and you can have multiple matching statements separated by a comma. It’s really awesome stuff! PUBLISHING A SINGLE EXE FILE IN .NET CORE 3.0June 20, 2019
by Wade ·7 Comments Say I have a simple “Hello World” console application that I want to send to a friend to run. The friend doesn’t have .NET Core installed so I know I need to build a self contained application for him. Easy, I just run the following command in my project directory :1
dotnet publish -r win-x64 -c Release --self-contained Pretty self explanatory : * Publish the project from the current directory * Build the project to run on Windows 64 bit machines * Build in release configuration mode * Publish everything as “self-contained” so that everything required to run the app is packaged up with our executable So this works right, we end up with a folder that has our exe and everything that is required to run it, but the issue is that there is a tonne required to run even a HelloWorld console app. All up it’s a little over 200 files. Crazy – but it makes sense. It’s essentially having to package the .NET Core runtime just to runHello World.
So functionally, this works. But optics wise, it looks like a mess. I’ve sent folders like this to clients and had to say “uhh.. So I’m going to send you a folder with hundreds of files in it… But… Can you just find the one titled MyApplication.exe and run that and don’t worry about the rest?”. When people are used to having an icon on their desktop they double click and things just.. work… This just doesn’t cut it. YOU NEED .NET CORE 3.0 (PREVIEW 5+) I need to put that in bold because this will not work if you don’t have .NET Core 3.0. And if you are an early adopter (At the time of this post .NET Core 3.0 is not GA yet), you will need atleast preview 5 upwards. If you’re not one to mess around in preview’s, then you can just wait a few months till .NET Core 3.0 is released! THE PUBLISHSINGLEFILE FLAG All that intro and it literally comes down to a single command flag :1
dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true All this does is runs our publish command but tells it to package it within a single file. You’ll notice that we no longer specify the self-contained flag. That’s because it’s assumed that if you are packaging as a single exe, that you will want all it’s dependencies along with it. Makes sense.And the output :
A single tidy exe! When this is executed, the dependencies are extracted to a temporary directory and then everything is ran from there. It’s essentially a zip of our previous publish folder! I’ve had a few plays around with it and honestly, it just works. There is nothing more to say about it. It just works. _Helpful Tip : Make sure you clean your publish directory or just outright delete your bin folder. It doesn’t break anything to not do so, but all those old DLL’s just hang around until you do so your nice single EXE is hard to spot. _ FILE SIZE AND STARTUP COST Keen eyes will notice something about the above screenshot. The file size. It’s over 70MB! That’s crazy for an application that does nothing but print Hello World to the screen! This is solved in Preview 6 of .NET Core 3.0 with a feature called IL Linker or Publish trimmer that omits DLL’s that aren’t used. You can read more about thathere!
The other issue you may find is that there is a slight startup cost when running the self contained executable for the first time. Because it needs to essentially unzip all dependencies to a temporary directory on first run, that’s going to take a little bit of time to complete. It’s not crazy (5 seconds or so), but it’s noticeable. Luckily on subsequent runs it uses this already unzipped temp folder and so startup is immediate.POSTS NAVIGATION
1 2 … 14
__
Proudly powered by WordPress . Theme: Flat 1.7.11 by Themeisle.
Details
Copyright © 2024 ArchiveBay.com. All rights reserved. Terms of Use | Privacy Policy | DMCA | 2021 | Feedback | Advertising | RSS 2.0