• .Net,  c#

    Visual Studio and that Annoying Code Style

    Here were are long ago from my last post and what do I do?  Yes, complain about Visual Studio 2022 and MS removing yet again the only real coding style I… use?

    Yes, that thing one does when one creates a Constructor for a Class to set a private read only variable that is not “this.whatever” but using the camel case “_whatever”.
    Now I get it… it’s a style… not everyone like the _whatever variables when one does something like Dependency Injection… Ok I have no problem with that…

    The complaint here… is everything almost when MS releases yet another update to VS 2022- they reset my code style! Really!

    Anyway… a good post to explain how to put it back:

    Put the Style Back

     

  • .Net,  Microsoft

    Dotnet 6 API with a HttpDelete and that 405 Method not allowed error

    As we can tell from the title of the Post, we are going to talk about figuring out why in a client app one gets a Http Status code of 405 (Method Not Allowed).

    When does this happen? Usually when a http request does a  http PUT or DELETE. Yet, when one uses Swagger (openAPI) or Postman to directly call the same API Delete or Put, it works!  This is starting to feel like a CORS issue, right? Read On ==>

    So 405! Indeed looking at the surface of what is going on, one thinks Ah! CORS is at it again! Absolutely, this is what it feels like. After all, a Swagger/Postman GET/DELETE call under the same http domain works. But the moment one moves to a Client App coming in from a different domain (i.e. a different port on localhost, because different ports are also considered a different domain in terms of CORS), the Http PUT/DELETE stops working and throws a 405.

    We are using VS2022 with Dotnet 6.0.100-rc.2.21505.57 (so the latest VS2022 and Dotnet RC 6 as of the writing of this post)

    Wow… let’s step into how to rein in CORS…. We start in the API project in the Startup class.

    In Configure Services =>

    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder
            .AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            .WithMethods("GET","PUT","DELETE","POST","PATCH") //not really necessary when AllowAnyMethods is used.
            );
    });
    

    We build a CORS policy  (yes one can remove the .WithMethods clause)

    And of course we add in the Configure method =>

    app.UseRouting();
    app.UseCors("CorsPolicy");

    And everything is right with the world… Let’s do a Delete in a client app. Meaning we are doing HttpClient Delete to a rest url that contains the id:

    Yeap a hard 405… What the what What?
    After digging through lots of readings on the topic of CORS 405 PUT/DELETE, DotNet 6 issues (with not much luck), I stepped upon the answer with a bit of thinking about the problem….

    In my Controller we have this as the delete method header =>

    [HttpDelete("id")]
    public async Task<IActionResult> Delete(int id)
    { ...

    Seems simple enough, it works in the Swagger interface for testing the API. I validated that the client is using and passing the correct url and id. WHAT!?

    Look closely at the [HttpDelete… tag. Notice anything? If one said, “Duh, ScottGeek- you need to wrap the “id” within {}” then YEAP!
    That would be the issue. The real question is why does this seem work in the Swagger UI for the api but not in a app using HttpClient?

    I have absolutely no idea why (yes I could get Fiddler out and start digging deep, nope) In this case what seems like a CORS acting up issue (405 on a cross domain request), yeah it’s not, or is it? This seems to be a bug somewhere, I suspect, in the OpenAPI (swagger) bits. Why in the OpenAPI? because it should reflect the same 405 when the API Method tag is not 100% correct.

    But let’s not just pick on OpenAPI. The fact that DotNet 6 allows both [HttpDelete(“id”)] and [HttpDelete(“{id}”)] without issuing some kind of build blowup or at least a green squiggle on the one that is in error… well I give it to ya… feels like a bug.

    Put the {} around the id and….

    Also, don’t forget to check one’s HttpPut as well…

    ~SG

  • .Net,  Microsoft

    The world of Dotnet Templates

    I have long been using templates for dotnet new and of course Visual Studio. So I’ve started down the road of creating my own templates… or a least trying to understand how to create these,

    Now creating templates for dotnet new and especially for Visual Studio has never been a simple task. But let us try.

    The first matter is understanding where templates live. For the most part these are based on your user for your PC. This found by using a PS command:

    join-path -Path $env:USERPROFILE -ChildPath .templateengine

    This will return C:\Users\<your user name>\.templateengine   And as you guess it, there is a .templateengine directory in your users directory. What does that mean, well simply put, when one does a .dotnet new –install, application templates get installed for your user. These actually live in that directory space. Simple enough.

    When you start developing your own templates, you need to be careful, because the list of templates can get very long. That may or may not be a problem.
    A handy PS script to clear out installed templates and put it back to the original set of templates:

    function Reset-Templates{
        [cmdletbinding()]
        param(
            [string]$templateEngineUserDir = (join-path -Path $env:USERPROFILE -ChildPath .templateengine)
        )
        process{
            'resetting dotnet new templates. folder: "{0}"' -f $templateEngineUserDir | Write-host
            get-childitem -path $templateEngineUserDir -directory | Select-Object -ExpandProperty FullName | remove-item -recurse
            &dotnet new --debug:reinit
        }
    }

    Keep in mind, this clears out all templates you have installed under your user. Use with care. If you have a set of favorite templates… yeap, they will get cleared off too!

    Now, where to start? I would go to Sayed’s GitHub repo @

    [visual-link-preview encoded=”eyJ0eXBlIjoiZXh0ZXJuYWwiLCJwb3N0IjowLCJwb3N0X2xhYmVsIjoiIiwidXJsIjoiaHR0cHM6Ly9naXRodWIuY29tL3NheWVkaWhhc2hpbWkvdGVtcGxhdGUtc2FtcGxlIiwiaW1hZ2VfaWQiOi0xLCJpbWFnZV91cmwiOiJodHRwczovL2F2YXRhcnMuZ2l0aHVidXNlcmNvbnRlbnQuY29tL3UvMTI4MzE1ND9zPTQwMCZ2PTQiLCJ0aXRsZSI6IlRlbXBsYXRlIFNhbXBsZSBieSBTYXllZCIsInN1bW1hcnkiOiJUaGlzIHJlcG8gY29udGFpbnMgYSBjb3VwbGUgc2FtcGxlcyBzaG93aW5nIGhvdyB5b3UgY2FuIGNyZWF0ZSBhIC5uZXQgY29yZSB0ZW1wbGF0ZSB0aGF0IGNhbiBiZSB1c2VkIGVpdGhlciBieSB0aGUgZG90bmV0IGNvbW1hbmQgbGluZSAoZG90bmV0IG5ldykgb3IgVmlzdWFsIFN0dWRpbyAmIFZpc3VhbCBTdHVkaW8gZm9yIE1hYy4iLCJ0ZW1wbGF0ZSI6InVzZV9kZWZhdWx0X2Zyb21fc2V0dGluZ3MifQ==”]

    It’s a long read, but one can also go over to Channel9 and look for the video series that steps one through the process.

    Another handy resource to search for templates is a web site:

     

    [visual-link-preview encoded=”eyJ0eXBlIjoiZXh0ZXJuYWwiLCJwb3N0IjowLCJwb3N0X2xhYmVsIjoiIiwidXJsIjoiaHR0cHM6Ly9kb3RuZXRuZXcuYXp1cmV3ZWJzaXRlcy5uZXQvIiwiaW1hZ2VfaWQiOi0xLCJpbWFnZV91cmwiOiJodHRwczovL2F2YXRhcnMyLmdpdGh1YnVzZXJjb250ZW50LmNvbS91LzI2Nzg4NTgiLCJ0aXRsZSI6ImRvdG5ldCB0ZW1wbGF0ZXMiLCJzdW1tYXJ5IjoiU2l0ZSBmb3IgZmluZGluZyBkb3RuZXQgdGVtcGxhdGVzLiIsInRlbXBsYXRlIjoidXNlX2RlZmF1bHRfZnJvbV9zZXR0aW5ncyJ9″]

    Enjoy
    ~ScottGeek

  • .Net

    The Confusing world of Text.Json and .Net 5

    So one of the base libraries over the years that has been our friend is Newtonsoft.Json – the stuff of legend maybe? Well, if not, certainly anyone whose done .Net and used any kind of Json formatted data certainly knows of Newtonsoft.Json… The “go to Json Serializer”! That is until Microsoft set out to prove to the world they could do it better. Better?

    Like many things in the world of .Net over the years, Microsoft watches these open source libraries… and notices when they become the defacto standard (meaning… Micro either left it out of their core offerings…. or more typical someone did better). Hence Microsoft’s System.Text.Json vs. NewtonSoft.Json.  Oh let the confusion begin!

    Now to Microsoft’s credit they have been working to finally bring System.Text.Json up to speed… but of course they continue to state the their intent is not to bring their Json library up to par with Newtonsoft. And there it is… the two world Json library view… now mostly the complaint I have deals with migrating old code up to using Microsoft’s. It’s a bit of a “rub me the wrong way” kind of careful reading as to which direction to take. Why? Well you get into dependency  issues where Newtonsoft and Microsoft’s library don’t always play well together- that can be a problem when it comes to wanting to use old code (NewtonSoft) in a new app while wanting to take advantage of faster MS .Net 5 serializations….. Yeah, why would one ever want to do that?

    Anyway, I take some time to read a great article @

    [visual-link-preview encoded=”eyJ0eXBlIjoiZXh0ZXJuYWwiLCJwb3N0IjowLCJwb3N0X2xhYmVsIjoiIiwidXJsIjoiaHR0cHM6Ly9kZXZibG9ncy5taWNyb3NvZnQuY29tL2RvdG5ldC93aGF0cy1uZXh0LWZvci1zeXN0ZW0tdGV4dC1qc29uLyIsImltYWdlX2lkIjotMSwiaW1hZ2VfdXJsIjoiaHR0cHM6Ly9kZXZibG9ncy5taWNyb3NvZnQuY29tL2RvdG5ldC93cC1jb250ZW50L3VwbG9hZHMvc2l0ZXMvMTAvMjAyMC8xMC9kb3RuZXQtYm90LnBuZyIsInRpdGxlIjoiV2hhdOKAmXMgbmV4dCBmb3IgU3lzdGVtLlRleHQuSnNvbj8gfCAuTkVUIEJsb2ciLCJzdW1tYXJ5IjoiTGVhcm4gYWJvdXQgdGhlIG5ldyBwZXJmb3JtYW5jZSwgcmVsaWFpbGl0eSBhbmQgZWFzeSBhZG9wdGlvbiB0aGF0IGhhcyBiZWVuIG1hZGUgd2l0aCBTeXN0ZW0uVGV4dC5Kc29uLCBhbmQgd2hhdOKAmXMgZ29pbmcgdG8gY29tZSBuZXh0LiIsInRlbXBsYXRlIjoidXNlX2RlZmF1bHRfZnJvbV9zZXR0aW5ncyJ9″]

    Layomi has a great write up of things to consider… especially in the section “Choosing between…” the two different libraries…. It’s a good read.

    ~SG

  • .Net,  .Net Core,  ASP.NET Core,  Microsoft,  Visual Studio 2019

    Dot Net 5 is Here… Check it out.

    Wow… some most excellent videos on what is what in .Net 5! Check it out on

    [visual-link-preview encoded=”eyJ0eXBlIjoiZXh0ZXJuYWwiLCJwb3N0IjowLCJwb3N0X2xhYmVsIjoiIiwidXJsIjoiaHR0cHM6Ly93d3cuZG90bmV0Y29uZi5uZXQvIiwiaW1hZ2VfaWQiOjAsImltYWdlX3VybCI6IiIsInRpdGxlIjoiLk5FVCBDb25mIDIwMjAiLCJzdW1tYXJ5IjoiSm9pbiB0aGUgLk5FVCBDb25mIDIwMjAgZnJlZSB2aXJ0dWFsIGV2ZW50IE5vdmVtYmVyIDEwLTEyIHRvIGxlYXJuIGFib3V0IHRoZSBuZXdlc3QgZGV2ZWxvcG1lbnRzIGFjcm9zcyB0aGUgLk5FVCBwbGF0Zm9ybSwgb3BlbiBzb3VyY2UsIGFuZCBkZXYgdG9vbHMuIE1hcmsgeW91ciBjYWxlbmRhciEiLCJ0ZW1wbGF0ZSI6InVzZV9kZWZhdWx0X2Zyb21fc2V0dGluZ3MifQ==”]

    You can also find these on You Tube… search on .Net 5. The Conf 2020 Days 1-3 will be there…

    ~ScottGeek.

  • .Net,  .Net Core,  Microsoft,  Visual Studio 2019

    Dot Net Hell by any other name?

    Just when I think Dot Net Hell days are coming behind us… I run across the reality of the fact that those that created this in the first place are… well… still doing it?

     

    Take this little gem:

    public static async IAsyncEnumerable<string> GetContent(string[] urls)
    {
    
    }

    Yes, we now have IAsyncEnumerable… or do we.   In my little experiment, I have a .Net 4.8 console app with C#8.0 language stuff turned on. So, I wanted to mess about with the Async Enumerable…. But in my console app that IAsyncEnumerble goes all red line of crap on me.

    So what’s the deal?  Well it’s simple once you do the digging.   .Net 4.8 does not implement .Net Standard 2.1… Yeah, you guessed it… where the Async Enumerable lives!

    So yeah, I could use .Net Core 3.0 which works with C# 8.0 and .Net Standard 2.1. Or here’s a thought why not just do a .Net Standard 2.1 console app? Well, the latest version of VS 2019 does not have a .Net Standard 2.1 template listed… Ummm, I’m sensing something missing there.

    Welcome to the “New” Hell! 

    ~ScottGeek….

  • .Net,  Microsoft,  Visual Studio 2019

    Program Challenge using CSV and NetMQ Part 1.

    I did a recent program challenge. The requirements were not too complicated.

    Basically I was given a simple csv formatted file (csv, of course, being a comma delimited text file). The challenge was to take this csv and parse it into a POCO- POCO being Plain Old Class Object. I’m not sure why we need a acronym for that. POCO is just a data structure in the form of a Class Object. But I digress.

    Once the csv is parsed into a Class Object, I was then to make it available in a Request/Response using NetMQ. Now on the surface this might seem a lot to do. But not really. The key, as always, is to break down the problem into the workable bits.

    We start with what we know some tasks:

    A) Input is a csv and it must be read into a Class Object.
    B) Using Request/Response pattern the csv must output using NetMQ (this part relies on getting A done correctly).
    C) The Request and Response should be in two separate applications. Task A will need to expose the Class Object as the Response, this is Application 1. Application 2 will be the Request that will output the Class Object. 

    So let’s look at  the first part of task A.

    Now as much as I like writing yet another file parser- not really- I opted in this case to use one that is already available. It’s call CsvHelper bu Josh Close. It’s available on NuGet of course. The nice thing about this one is it’s simple and it works with POCO’s.  You wire it up based on your class object.

    Let’s start with my POCO (this was given by looking at the csv that just happens to have the first row with column names):

    public class People
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    }

    Now wiring this into the csv parser is a simple matter of having a text reader and creating a new csvreader with the helper:

    static List<People> giveMeData(TextReader textReader)
    {
        var csvReader = new CsvReader(textReader);
        var theData = csvReader.GetRecords<People>();
        return (theData.ToList());
    }

    Here I’ve method that parses the csv and makes a list of People.

    And that’s it for the first part of task A. The second part of task A has to do with exposing this List of People through NetMQ. 

    We will do this in next part of this blog.

     

  • .Net,  Build2019,  Microsoft

    Build 2019 Session: .Net Goodness

    Yes, I know I’m a little behind on picking out my favorite Build 2019 Session… So here the first one…

    Microsoft Build 2019 Developer Conference May 6-8 Seattle, WA

    Microsoft Build 2019 Developer Conference May 6-8 Seattle, WA

    .NET Platform Overview and Roadmap

    Join developers and industry experts at Microsoft Build to explore the latest developer tools and technologies. #MSBuild

    Source: .NET Platform Overview and Roadmap

  • .Net,  Microsoft

    From the Dot Net Config some Good Web Sites to check out.

    So in the travels about with the .Net Conf this week check out some site:

     

    Awesome .NET open source & community resources

     And…

    BuiltWithDot.Net is a community showcase of projects built with .net framework, .net core, xamarin, mono, mono game, unity, or godot. Anyone can submit.
     

    And…