.status-msg-wrap { display: none; }
Friday, November 30, 2018
no image

Create data collector sets to collect performance data (e.g. privaye bytes)?

Is there a way to create data collector sets to gather perfoance data?

I understand PerformanceCounter() can be used, but as I understand it getting the data requiress some manual implementation(?).

I was thinking something like the IDataCollectorSet with the Start() method.

Create data collector sets to collect performance data (e.g. privaye bytes)? Click here
no image

Utilizing time : How to contribute in Open Source Projects

I am new to open source and have been actively programming in C#. Have some free time and would like to contribute to Open Source projects. Wondering where to start with.

Since there are so many open source projects out there, I think there would be people looking for contribution. So the question is how to find open source project which are in need of contribution?

Utilizing time : How to contribute in Open Source Projects Click here
no image

Call webApplication method

Hey guys. I'm relatively new to dotnet. I have a method i need to run weekly.

i made some research and i guess the best way to do it is using a consoleApplication, but i don't really know where to start.

i would appreciate some help, please.

thanks in advance ;)

Call webApplication method Click here
Thursday, November 29, 2018
no image

Dynamically load SSls from a database dynamically in c#?

Hello everyone,

I'm a bit lost but I have a scenario where we have uploaded 199 SSL certificates to our azure server; and this is the max limit.

We have 100s more SSLs to upload and work with.

Has anyone experienced a situation like this? Is it possible to put the needed info into a database and load a certificate dynamically based on what website is accessing the server in an instance?

Please let me know if I need to provide more info.

Thanks,

Dynamically load SSls from a database dynamically in c#? Click here
no image

Using Paket with Github dependencies (C#)

Hello, I'm trying to accomplish the following:

I have project 'A' which is a console application that references a class library project, 'B', hosted on Github.

I have followed the instructions the Paket website for Github repositories, and I've just gotten confusion out of it, since it keeps throwing errors no matter what I try.

Also I believe that the documentation for Paket for Github is lacking information and just straight up confusing.

How will I go about this?

- Do I need to push the built nuget package of project 'B' to it's Github repository?

- I added `github mygithubusername/projectBname` to project 'A's `paket.dependencies`, I get the following error: "... Package 'B' was not found in group Main of the paket.lock file. "

Any help would be greatly appreciated, been stuck on this for weeks. I've tried reaching to their gitter channel, no response.

Using Paket with Github dependencies (C#) Click here
no image

Combining Windows Authentication with some sort of role base authorization system?

I wonder if somebody here could help point me in the right direction?

I'm new to Angular and SPAs in general. I am currently writing an app that should use a user's windows credentials (from Active Directory) to authenticate them automatically.

My Application was set up in Visual Studio 2017 as an ASP.NET Core Web Application and using the "Angular" template which scaffolds an Angular 5 Client App into that same project.

I have managed to get windows Authentication working by using the imported NuGet package Microsoft.AspNetCore.Authentication and adding the line below to the ConfigureServices section of my Startup.cs

services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme); 

My Get and Post controllers work just fine and I am able to see a user's network credentials by looking at User.Identity.Name within any of my controller methods.

Now I would like to implement some sort of role based authentication system but I've got no idea where to start. I would like to be able to add an Attribute to a controller function which specifies the allowed roles (example below):

[Authorize(Roles = "Admin")] [HttpGet("[action]/{id}")] public User GetUser([FromRoute] int id) { UserLogic ul = new UserLogic(); return ul.GetUser(id); } 

If I was doing this in an MVC project, I would just implement a RoleProvider and then specify in my web.config that I want it used as the default provider - but there is no web.config for ASP.NET Core Web Applications.

How do I go about specifying my own role provider so that tags like this [Authorize(Roles = "Admin")] can be routed through to them?

I'd prefer to keep my own database tables containing users and roles and I'd prefer to be able to perform role authorization using my own data access layer.

Can anyone point me in the right direction?

Combining Windows Authentication with some sort of role base authorization system? Click here
no image

Should I host my simple ASP.NET app on VPS or shared hosting?

Recently I asked about black Friday deals regarding hosting and people here gave a great answers, so thanks for that!

After black Friday and cyber Monday, I ended up with KVM VPS 2vCore CPU and 2GB RAM, 15GB SSD and shared linux hosting (was really a drunk impulse buy) which I don't really need. My app is currently at smarterasp.net, but I don't plan to extend it, since they don't offer any discount.

App is really simple CRUD app which has a small 8MB MSSQL database, so these are options I think of:

  • Host it with docker on my VPS alongside another asp.net core app. Only doubt I have regarding this is will 2 docker containers slow each other, since I'm not sure do I have enough resources?

  • Buy another shared hosting, but this time with hostmantis. This is the easiest solution, but I already spent too much on all black friday deals, so wouldn't spend more if not necessary.

  • Use Azure free solution, but if I understood correctly, I would still have to pay $5/month for SQL, so I could change it to SQLite or MySQL if that makes any difference (didn't use Azure, so I'm not sure does it work like this) and I can't use my own domain, but something.azurewebsites.net. Is this truth?

I don't need anything special and the purpose of the app is only to be alive, since I will put it on my resume.

Should I host my simple ASP.NET app on VPS or shared hosting? Click here
no image

running dot net publish with multiple threads (compiling dotnet core in multiple threads)

I want to change the script (Powershell) of the deployment from synchronous to asynchronous. One of the main operations of the deployment is the compilation of the dotnet core projects.

I wrote a short Powershell script to see if I can run `dotnet publish` on multiple threads (compiling multiple projects at once), and I wanted to see if something is different from compiling synchronously.

I saw a huge difference in the size of the files, so I can't compile with dotnet publish multiple projects at once? Or perhaps I did a mistake (pretty sure I didn't)?

How can I compile multiple dotnet core projects at once?

running dot net publish with multiple threads (compiling dotnet core in multiple threads) Click here
Wednesday, November 28, 2018
no image

Migrating to EF from homemade ORM.

I've got a fairly large .net webform project that uses a very old ORM designed by a programmer that no longer works here. It runs a query on the database to get the table information, reads in a text file as a template that holds generic data access properties for each table and its fields and stores them all in a single file in the project. When we create a new table, we run the project, click a button it runs the querys/reads the template and updates this one file. So after years of doing this that one file has gotten fairly large.

I was thinking about proposing a project to convert this to using entity framework. I'm thinking this would be a good direction to take our project, but as a fairly new dev how do I make that argument? What would be some of the benefits to EF over this method?

Migrating to EF from homemade ORM. Click here
no image

Offering my help migrating your projects to .NET Core / .NET Standard / new CSProjs for free!

Library authors and other open source .NET folks, need help migrating your projects to .NET Standard or .NET Core? Or simply want to use the new SDK-based CSProjs with the ol' Full Framework?

I've been writing build pipelines around MSBuild and .NET for 2 years now and since most of the heavy lifting at my shop is done i am therefore searching for projects who need help.

This includes:

  • Profile-based PCL migration
  • Multi-Targeted projects supporting wide varieties of target frameworks (to ease migration)
  • Help with SemVer
  • Custom MSBuild stuff
  • Cake, Powershell or MSBuild CICD pipelines
  • Cross-TargetFramework testing
  • SourceLink integration for teh nice Debug Symbol experience (Nuget packages with symbols built to retrieve the original files via git raw urls, that can be stepped through)
  • AppVeyor (or Azure Devops, Travis... most of them are pretty much the same)
  • Clean versioning implementation (AssemblyInfo, nupkg versions)
  • MSBuild Custom SDK (Auto-restored nuget package containers for MSBuild logic such as msbuild tasks, default items or advanced build outputs)

Why? I've been doing this manually for so long it's become a meditation practice for me. Also: To many nuget packages are stuck without proper dependencygroup definitions resulting in package consumers being forced to believe handwritten nuspecs without any validation - or sometimes simply just annoying limitations such as tiny awesome libraries forced under net45 or stuff like that).

So - don't be shy - if you maintain a OSS .NET project and don't know (or just don't have the time) to do aforementioned stuff: just reply with your project - i don't want any favors, i don't want you to give me special access to put backdoors in your code, nor do i want you to be in my debt; i like doing this stuff. I will simply throw you a PR with explanation to the best of my abilities and you decide if what i did is cool ;)

P.S.: If you're not OSS, i can help you, too - at least with some advice - just don't expect me to overcome this and that hurdle to help your company to get of yer bums :D P.P.S.: Also this has no commercial background whatsoever - i'm not currently looking for a job nor do i plan to commercialize this in any way.

Offering my help migrating your projects to .NET Core / .NET Standard / new CSProjs for free! Click here
no image

ASP.NET Core Web API + EF Core - Recommended way to check all unique constraints on a POST?

I've just started trying out EF Core and have ran into something that google doesn't immediately answer.

If you let VS auto create an API Controller with actions using Entity Framework, most of the methods check for things like if the record exists before deleting it. However, for POST requests, if you try to add a model with a duplicate for any existing unique column you get an internal server error.

What's the recommended way for checking all unique constraints and returning a 'nice' error?

ASP.NET Core Web API + EF Core - Recommended way to check all unique constraints on a POST? Click here
no image

Your favorite .NET/C#/Azure conference talks

I'm currently writing a blog post about good .NET/C#/Azure related talks (taped at conferences, user groups, etc.). I already have a list of my top 10 talks, but would appreciate your input. Anyone?

Your favorite .NET/C#/Azure conference talks Click here
Tuesday, November 27, 2018
no image

.NET Core WEB API on AWS resource

Hello, I'm new to .NET core and I've been writing writing .NET core web APIs locally using EF core migrations with a local SQL server and I'd like to deploy my API to AWS and I'm not finding any good resources. I think I need to use Amazon RDS to setup a SQL server and I also looked into Elastic beanstalk where I can connect to the database and apply the migrations through VS, is this the correct path?

.NET Core WEB API on AWS resource Click here
no image

What is the use of an async await method that only call one liners async await methods? How many threads do they span? How much CPU you can end up consuming?

Hi, lately I'm seeing a lot of methods using the async and await keywords. I still cannot wrap my head around the use of them and the underlying behavior as well as their advantage when applied like below. I ahve also obseved a problem with the CPU (going 100%) when they use it for everything and I'm seeing thread.run as the culprit for cpu utilization for some of this cases.

myController.cs

[HttpPost]

[ProducesResponseType(body)]

public async Task<IActionResult> Post([FromBody]Body body){

_MyClassService.sendMessage(body);

return Ok(body);

}

Myclass.cs

private async void sendMessage(){

await SendToProperChannel();

}

private async Task SendToProperChannel(){

await DoWorkInProperChannel();

}

private Task<int> DoWorkInProperChannel(){

await Thread.sleep(1000)

return 1+1;

}

According to my little knowledge.

  • We are making the controller request async in order to not block main threads, allowing to receive higher throughput at the controller level.
  • We are making also all the functions async to not block the upper threads that call those methods.
  • I also understand that since we have so many awaits, everyone returns a task but also a thread is handling that work waiting for the completion of this.
  • I'm still not clear on the thread number but I believe we are spawning more than 1 thread to fulfill a single request.

My questions.

  • What is the use of having one liners await if the upper method cannot continue without the response? The API can, in fact, receive more throughput, but down from there everything will be kind of sync, also spawning more threads just for jumping between methods in my class doesn't seem healthy.
  • If I only awaiting on one liners, in this specific code, the result would not be the same as removing the awaits?
  • All methods will also handle more throughput, since they don't block, but will also spawn more threads?
  • How is the syntax for starting an async method and waiting for the response way down inside the same method.

Example:

private async Task<int> myAsyncWorkerMethod(){

var myNeededValue=methodThatINeed();

var mySecondValue=methodWithSecondValue();

await myNeededValue;

await mySecondValue;

return myNeededValue+mySecondValue;

}

  • What is the benefit from async and await against having just a thread pool that handles all downstream calls, which you can easily control its size and can easily detect thread starvation and queue depth? (I might be using some java terms in here that might not apply)

Thoughts

  • In other lenguages I have seen the repercussions of thread context change, if your CPU is not powerful enough or you have thread starvation because of the thread pool size, does this .net uncontrolled thread pool would not have the same repercussions and just use the CPU as much as he wants?
  • You don't need to create an async invocation if you need them to return the response for the await statement. making asynchronous is only needed when you need to do some work on the above method?
  • Even if you are awaiting method results from another class unless you don't want to block the main thread you should also not wait for it.

Thanks in advance.

What is the use of an async await method that only call one liners async await methods? How many threads do they span? How much CPU you can end up consuming? Click here
no image

Background Service ruining Web API performance

I'm currently developing a Web API used by our mobile application. If an API-call is made that needs to send an email, the email is added to a queue in Azure Storage. For handling the queue (reading the queue mails and actually sending them) I thought the best solution would be creating a Hosted Service that will do this in the background.

For implementing this I followed the instructions from the following documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.1

I created a class that implements the abstract BackgroundService-class from .NET Core 2.1 for this. It looks like this:

namespace Api.BackgroundServices { /// <summary> /// Mail queue service. /// This handles the queued mails one by one. /// </summary> /// <seealso cref="Microsoft.Extensions.Hosting.BackgroundService" /> public class MailQueueService : BackgroundService { private readonly IServiceScopeFactory serviceScopeFactory; /// <summary> /// Initializes a new instance of the <see cref="MailQueueService"/> class. /// </summary> /// <param name="serviceScopeFactory">The service scope factory.</param> public MailQueueService(IServiceScopeFactory serviceScopeFactory) { this.serviceScopeFactory = serviceScopeFactory; } /// <summary> /// This method is called when the <see cref="T:Microsoft.Extensions.Hosting.IHostedService" /> starts. The implementation should return a task that represents /// the lifetime of the long running operation(s) being performed. /// </summary> /// <param name="stoppingToken">Triggered when <see cref="M:Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)" /> is called.</param> /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the long running operations.</returns> protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { await HandleMailQueueAsync(); //await Task.Delay(3000, stoppingToken); } } private async Task HandleMailQueueAsync() { using (IServiceScope serviceScope = serviceScopeFactory.CreateScope()) { TelemetryClient telemetryClient = serviceScope.ServiceProvider.GetService<TelemetryClient>(); try { IMailHandler mailHandler = serviceScope.ServiceProvider.GetService<IMailHandler>(); await mailHandler.HandleMailQueueAsync(); } catch (Exception exception) { telemetryClient.TrackException(exception); } } } } } 

After registering it by calling

services.AddHostedService<MailQueueService>(); 

in the Startup.cs, it will successfully handle the mail queue, but all other calls to the WebAPI take almost ten times as long. Only if I comment out the Task.Delay() part in my implementation of the BackgroundService, the performance goes back to an acceptable level.

However this seems more like a workaround than a real solution for my problem. Am I doing something else wrong that makes the performance tank like this?

Background Service ruining Web API performance Click here
no image

request for examples: fat controllers that do too much

Does anyone know where I could find one or two (or more) examples of .net controllers that have too much going on in them?

I'm trying to create a demonstration for a talk that involves starting with an unruly mess of spaghetti code and works out how to get it into something more manageable.

I'd prefer not to have to fabricate the spaghetti if possible. It would be nice to start with at least something _mostly_ realistic. I've been searching github but haven't had much success.

request for examples: fat controllers that do too much Click here
no image

Multiline String Concatenation with interpolation

Hi folks. I'm looking for some confirmation of my understanding of how the compiler deals with string concatenations.

I understand that if I break up a long literal string over a few lines for readability, the compiler will interpret that as a single string, and there will be no runtime overhead in doing this. So I can do:

var longString = "part 1 " +

"part 2"

Which is just as performant as:

var longString = "part 1 part 2" On a single line (imagine this is much longer, and hard to read on one line)

And not suffer from the performance impact of doing concatenations at runtime.

However, I'm not sure how this works with interpolated strings:

var interpolatedLongString = $"info: {xxx} " +

$"long text {yyy}"

Is the compiler smart enough to turn this into:

var interpolatedLongString = $"info: {xxx} long text {yyy}"

Thanks!

Andy

Multiline String Concatenation with interpolation Click here
no image

How do you structure you projects? Project Architecture 2018 [Discussion]

There's a lot of ways to structure projects these days. Wondering what people use/prefer nowadays.

I try to follow the Clean Architecture structure for new projects (depending on the size and scope) but work on a few legacy projects in other architectures e.g. Monolith, N-Layer.

Examples of Clean Architecture:

https://github.com/ardalis/CleanArchitecture

https://github.com/JasonGT/NorthwindTraders

Descriptions of common web application project architectures:

https://docs.microsoft.com/en-us/dotnet/standard/modern-web-apps-azure-architecture/common-web-application-architectures

It would be good to get a bunch of good examples in one place. I have a few youtube videos and blogs that are really useful for this sort of stuff and happy to share.

How do you structure you projects? Project Architecture 2018 [Discussion] Click here
no image

PdfPig 0.0.3 released. NET Standard 2.0 PDF library Apache 2.0 License.

Download: NuGet

Source: GitHub

I posted a while back when I first released PdfPig but I haven't been able to work on it for quite some time since then. Today I managed to get the next version out.

Features of this version:

  • Consumers can directly access the PDF file content through PdfDocument.Structure this exposes every object in the document with wrappers for each of the underlying PDF data types, stream, number, string, name, boolean, object, etc. This also provides direct access to the pages dictionary which is the root of the page structure for the PDF document.
  • Every letter now has a GlyphRectangle property. This is the smallest rectangle which would entirely contain the glyph calculated from the glyph definition in the font. This supports both Type 1 and Compact Font Format (CFF) fonts which were not previously supported.
  • Page now has a method to retrieve words using some simple heuristics to merge letters into words based on their size and position as well as an experimental feature to retrieve the PDF XObjects for the images on a page using page.ExperimentalAccess.GetRawImages();.
  • A load of bug fixes and performance tweaks for reading from documents.

Next up the plan is to add creation of simple PDF documents and expose the decoded font objects for TrueType, Type 1 and CFF fonts (which already exist internally) as well as bug fixes for documents which rely on reading TrueType fonts from System Files and Type 1 CID fonts.

Let me know which other features would make good candidates for the next version along with any bugs you might spot. I think most people are after creation and editing of documents which is why it's the target for the next version (0.0.5 because I don't like 4).

PdfPig 0.0.3 released. NET Standard 2.0 PDF library Apache 2.0 License. Click here
no image

DI containers with .net core

With dependency injection built in with .net core is there any need for using other DI containers, autofac/simple injector/ninject etc?

DI containers with .net core Click here
Monday, November 26, 2018
no image

ELI5 Dependency Injections and Constructors

I know this is a dumb question, but I've been using .NET for a year and a half now and still don't feel like I fully understand this. I want to learn it since I'm trying to learn .NET Core 2.1, but I'm just not getting it. I have two Udemy courses that I'm taking (right now I'm working on Complete ASP.NET Core 2.0 with Razor Pages by Bhrugen Patel, next is his ASP.NET Core 2.1 class) but he kind just breezes over what the use and reason of using DI is for.

Any help is greatly appreciated!

ELI5 Dependency Injections and Constructors Click here
no image

Drowning in Interfaces .. whats the solution?

Using ASP.net core 2.1, and of course using DI I have to generate 2 files. Despite using folders to separate operations I wonder what people with bigger projects do with their Interfaces?

Could you lump them all together in one Interface folder? Afterall you only need to access them to update them, and that can be done from the class, so there is no need for them to be in the main part of the structure.

Also, is there an "Update Interface based on Signature change" command that might automatically update the Interfaces when you change the contents of the class?

edit: I found the Update part, when you click on the changed method then the lightbulb has "Add to Interface"

Drowning in Interfaces .. whats the solution? Click here
The webdev Team