Category: .NET Core

Exchange rates–start project – part 1

(This is the result of 1 hour per day auto-challenge as a full cycle developer)

Long time ago I have made a site about exchange currency rates for National Bank of Romania( and l, later, also Central Europeean Bank ) . It was started on ~ 2004  – found image at https://web.archive.org/web/20041215090302/http://www.infovalutar.ro/

Then was passed via MVC1 – and it looks like in https://web.archive.org/web/20180227023708/http://www.infovalutar.ro/bnr

Now it is the moment to pass to .NET Core and Azure.

Here are some requirements:

  1. Must parse at specified times the exchange currencies from multiple banks
  2. Must show the exchange rates
  3. Must have a Web application, a Console one , a Mobile one
  4. Must be easy accessible to programmers – if they want to have the exchange rates ( rss, custom links)
  5. Must have a download link for all values
  6. Must have charts
  7. Must be easy to use – whatever that means

 

I will work at the applications 1 hour per day – and see what it is happening over the time.

Infovalutar

And one hour passes...
(This is the result of 1 hour per day auto-challenge as a full cycle developer for an exchange rates application)
( You can see the sources at https://github.com/ignatandrei/InfoValutar/ )
NrPost 
1Start
2Reading NBR from internet
3Source control and build
4Badge and test
5CI and action
6Artifacts and dotnet try
7Docker with .NET Try
8ECB
9Intermezzo - Various implementations for programmers
10Intermezzo - similar code - options
11Plugin implementation
12GUI for console
13WebAPI
14Plugin in .NET Core 3
15Build and Versioning
16Add swagger
17Docker - first part
18Docker - second part
19Docker - build Azure
20Pipeline send to Docker Hub
21Play with Docker - online
22Run VSCode and Docker
23Deploy Azure
24VSCode see tests and powershell
25Code Coverage
26Database in Azure
27Sql In Memory or Azure
28Azure ConString, RSS
29Middleware for backward compatibility
30Identical Tables in EFCore
31Multiple Data in EFCore
32Dot net try again
33Start Azure Function
34Azure function - deploy
35Solving my problems
36IAsyncEnumerable transformed to IEnumerable and making Azure Functions works
37Azure functions - final
38Review of 37 hours
39Last Commit in AzureDevOps
40Create Angular WebSite
41Add static Angular to WebAPI .NET Core
42Docker for Angular
43Angular and CORS
44SSL , VSCode, Docker
45Routing in Angular
46RxJS for Routing
47RxJs Unsubscribe

Presentation .NET Core3 Wha’s New

From the presentation:

C# 8.0 What’s new

Reference:

https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8 https://github.com/dotnet/csharplang/blob/master/meetings/2017/LDM-2017-03-08.md

Demos:

  1. Default Interface Inheritance

  2. Multiple Interface Inheritance
  3. Switch
  4. Deconstruct

Other demos:

  1. UsingUsage

  2. StaticLocalFunctions();
  3. Nullable();
  4. Version();
  5. Indexes();
  6. NullCoalescing();

.NET Core What’s new

Reference:

https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0

https://devblogs.microsoft.com/dotnet/announcing-net-core-3-0/

Demos:

  1. AsyncEnumerable

  2. WPF
  3. COM
  4. Build ( trim, single file)
  5. Diamond hell with plugins

See NetCore3WhatsNew.sln and AssemblyLoadingUnloadingDiamond.sln

ASP.NET Core What’s new

Reference:

https://docs.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-3.0?view=aspnetcore-3.0

  1. Blazor + Blazor Server

  2. gRPC – https://docs.microsoft.com/en-us/aspnet/core/grpc/index?view=aspnetcore-3.0
  3. SignalR – reconnection, authorization

  4. NewtonSoft => System.Text.JSON
  5. Windows Authentication has been extended onto Linux and macOS.
  6. GenericHost – see https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#hostbuilder-replaces-webhostbuilder
  7. As of ASP.NET Core 3.0, .NET Framework is no longer a supported target framework

EF Core What’s new

Reference: https://devblogs.microsoft.com/dotnet/announcing-ef-core-3-0-and-ef-6-3-general-availability/

  1. Refactoring + Single SQL statement per LINQ query

  2. Restricted client evaluation – i.e. Explicit AsEnumerable
  3. C# 8.0 support – AsAsyncEnumerable
  4. IDbCommandInterceptor

See NetCore3WhatsNew.sln , AsyncEnumerable

See https://github.com/ignatandrei/EFRecordAndPlay/tree/master/EF_Core3/EFCoreRecordAndPlay/EFRec

The video whole presentation ( in Romanian) you can find  at https://www.youtube.com/watch?v=GjJGMwkSnao&feature=youtu.be&fbclid=IwAR1i33TSycffNQ8O-iDjf2l_yU9IL1g2ylRPqiG7OkOZo5RRdy0CxklnbTk 

The demo is at https://github.com/ignatandrei/Presentations/tree/master/2019/shorts/NetCore3.0WhatsNew

What’s new in .NET Core 3

If you want to see what is new in .NET Core 3, please join tomorrow at https://www.meetup.com/Bucharest-A-D-C-E-S-Meetup/events/264063550/ .

We will have talk about

C# 8.0 What’s new

Reference:

https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8

Demos:

  1. Default Interface Inheritance

  2. Multiple Interface Inheritance
  3. Switch
  4. Deconstruct

Other demos:

  1. UsingUsage

  2. StaticLocalFunctions();
  3. Nullable();
  4. Version();
  5. Indexes();
  6. NullCoalescing();

See NetCore3WhatsNew.sln

.NET Core What’s new

Reference:

https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0

https://devblogs.microsoft.com/dotnet/announcing-net-core-3-0/

Demos:

  1. AsyncEnumerable

  2. WPF
  3. COM
  4. Build ( trim, single file)
  5. Diamond hell with plugins

See NetCore3WhatsNew.sln and AssemblyLoadingUnloadingDiamond.sln

ASP.NET Core What’s new

Reference:

https://docs.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-3.0?view=aspnetcore-3.0

  1. Blazor + Blazor Server

  2. gRPC – https://docs.microsoft.com/en-us/aspnet/core/grpc/index?view=aspnetcore-3.0
  3. SignalR – reconnection, authorization

  4. NewtonSoft => System.Text.JSON
  5. Windows Authentication has been extended onto Linux and macOS.
  6. GenericHost – see https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#hostbuilder-replaces-webhostbuilder
  7. As of ASP.NET Core 3.0, .NET Framework is no longer a supported target framework

EF Core What’s new

Reference: https://devblogs.microsoft.com/dotnet/announcing-ef-core-3-0-and-ef-6-3-general-availability/

  1. Refactoring + Single SQL statement per LINQ query

  2. Restricted client evaluation – i.e. Explicit AsEnumerable
  3. C# 8.0 support – AsAsyncEnumerable
  4. IDbCommandInterceptor

See NetCore3WhatsNew.sln , AsyncEnumerable

So I wait tomorrow at https://www.meetup.com/Bucharest-A-D-C-E-S-Meetup/events/264063550/ .

.NET Core 3 – what impressed me

This are the things that have impressed me:

  • Async Streams ( think in conjunction with about EFCore / SignalR / gRPC / Observables)
  •  .NET Default Interface members ( not appliable to classes  – so multiple inheritance is a problem just for interfaces…)
  • Deconstruct – see a class from his properties
  • Switch  – they improved Switch to work practically in any case scenario
  • For Windows Application –  COM support, MSIX
  • For any application – Default Files Executable ( about time!), assembly linking( tree-shaking in Javascript idiom) , single files executables ( like a jar file, but executable)
  • For plugins: Assembly loading improvements and Assembly Unloadability
  • gRPC in ASP.NET Core
  • SignalR improvements
  • Windows Authentication has been extended onto Linux and macOS
  • As of ASP.NET Core 3.0, .NET Framework is no longer a supported target framework.
  • EFCore : Restricted client evaluation – Explicit loading data from database
  • EFCore: Async in loading data
  • EFCore : IDBCommandInterceptor for

But there are more improvements( nullable for classes , using syntax, static local functions…)

Be sure that you read the links:

String interpolation for EFCore and Like

I have had a problem with EF Core and String Interpolation – until I realized that was a problem with sp_executesql

But let’s see the whole problem. ta

EFCore supports string interpolation –  that means , if you give this code

<context>.<table>.FromSql($”select blabla from table where id={id}”)

it will transform into

exec sp_executesql N’select blabla from table where id= @p0 ”
‘,N’@p0 int’,@p0=N’200′

And it is very good , because it avoids sql injection . ( Just a note, do not put

$”select blabla from table where id={id}”

into a variable  – you WILL have SqlInjection )

Ok. Now I want to do a like –  plain simple, right ?

<context>.<table>.FromSql($”select blabla from table where CountryName like ‘%{name}%’ ”)

And I try  –  and NO RESULT comes. I will into the generated Sql ( by using SqlProfiler from SSMS ) and it gives

exec sp_executesql N’select blabla from table where CountryName like ”%p0%”’,N’@p0 nvarchar(4000)’,@p0=N’france’

Pretty harmless , right ?

And seems ok – until I have executed directly and see that no results come.

So StackOverflow to the rescue : https://stackoverflow.com/questions/3556506/using-like-in-sp-executesql

And so my query in C# have been modified to

<context>.<table>.FromSql($”select blabla from table where where CountryName like ‘%’ + {name} + ‘%'” )

And now it works!

Moral of the  story : always investigate the sql generated .

Dotnet Try

I have wrote a blog post about DotNet CLI Tools
I did not mention one that is super important: DotNet Try : https://github.com/dotnet/try

You can see at https://github.com/dotnet/try how to install it .

Or ,to use in Docker, check my files to install in Docker https://github.com/ignatandrei/Presentations/tree/master/2019/shorts/NetCoreGlobalTools/dotnetTry   . To edit files in Docker, use Visual Studio Code with Docker and Remote Development and Docker extension.

To see in action on the web, check out Noda Time  or

( for the moment is in preview, but it will work with GitHub and blogs…)

[PostEvent] Talks by Softbinator

The organizers from Talk from Softbinator were kind enough to select me for a presentation. Again , my presentation about .NET Core and Angular Everywhere. Source Code at https://github.com/ignatandrei/angNetCoreDemo/ 

The presentation was supposed to take 1/2 hour – and it took 1 hour with all the explanations.

Video at https://www.facebook.com/softbinator/videos/459024768242391

Correct abstraction–.NET Core IFileProvider

Create the right abstraction and they will implement it. I was delighted by finding that the .NET Core has an IFileProvider : https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.ifileprovider?view=aspnetcore-2.2  .

An obvious implementation is PhysicalFileProvider : https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.physicalfileprovider?view=aspnetcore-2.2

A not so obvious implementation, but normal from a programmers mind, is NullFileProvider: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.nullfileprovider?view=aspnetcore-2.2

And, because we have already 2 providers, makes sense a CompositeFileProvider: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.compositefileprovider?view=aspnetcore-2.2

And because we create assemblies, it is normal to have EmbeddedFileProvider: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.embeddedfileprovider?view=aspnetcore-2.2

And , to complicate things, a ManifestEmbeddedFileProvider: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.manifestembeddedfileprovider?view=aspnetcore-2.2

( You can read more details here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-2.2#physicalfileprovider)

But this is just what Microsoft provides in .NET Framework.

Other creates more, such as :

LongFileProvider: https://github.com/v-kabanov/hdrepository/blob/master/trunk/Common/bfs.Repository.IO.WinNtfs/WinLongFileFrovider.cs

S3FileProvider: https://github.com/evorine/S3FileProvider/blob/master/src/S3FileProvider.cs, https://github.com/lamondlu/AWSS3FileProvider

AzureBlogFileProvider: https://github.com/filipw/Strathweb.AspNetCore.AzureBlobFileProvider

More Cloud Providers : https://github.com/jiabiao/NCloudFiles

ZipFileProviders: https://github.com/tagcode/Lexical.FileProvider , https://github.com/cloudscribe/cloudscribe/blob/master/src/cloudscribe.Web.Common/StaticFiles/GzipMappingFileProvider.cs

DatabaseFileProviders: https://github.com/mikebrind/RazorEngineViewOptionsFileProviders

And InMemory: https://github.com/dazinator/Dazinator.AspNet.Extensions.FileProviders

It is interesting how you can find various implementation of an so common thing, like a file / folder. But it is also rewarding to see that you have created the right abstractions – and other will implement !

[PostEvent] CodeCamp Timisoara

I have been a presenter and participant at CodeCamp Timisoara. There are a lot of tracks with good information!

As a participant , I can mention:

Things you did not know about C# and .NET – with Marius Bancila
CALMS in DevOps – with Adrian Suteu
Making E2E tests great again using Cypress – with Omri Ben Ari

My presentation was about Angular and .NET Core Everywhere and you can find the source code at https://github.com/ignatandrei/AngNetCoreDemo

Simple serialize of encoding

My problem was the serialize of the Encoding . Let’s suppose that we have a class that have a property Encoding( maybe to read a file ).


internal class MyTest
{
    public MyTest()
    {
        enc = ASCIIEncoding.ASCII;
    }
    public Encoding enc { get; set; }
}


We want to serialize this class in order to let the administrator/people to decide what will be the encoding.

When we serialize( obvious, with NewtonSoftJson) , we obtain this kind of data:

{
“enc”: {
“IsSingleByte”: true,
“BodyName”: “us-ascii”,
“EncodingName”: “US-ASCII”,
“HeaderName”: “us-ascii”,
WebName“: “us-ascii”,
“WindowsCodePage”: 1252,
“IsBrowserDisplay”: false,
“IsBrowserSave”: false,
“IsMailNewsDisplay”: true,
“IsMailNewsSave”: true,
“EncoderFallback”: {
“DefaultString”: “?”,
“MaxCharCount”: 1
},
“DecoderFallback”: {
“DefaultString”: “?”,
“MaxCharCount”: 1
},
“IsReadOnly”: true,
“CodePage”: 20127
}
}

This is too much for someone to edit . We want a simple string that can be edited easy – and the WebName ,  that is , in fact , a string from https://www.iana.org/assignments/character-sets/character-sets.xhtml seems the obvious choice.

So –  I have done a JSONConverter class just for this property. It is very simple:

public class JsonEncodingConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (typeof(Encoding).IsAssignableFrom(objectType));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string webName = "";
        if (reader.TokenType == JsonToken.String)
        {

            webName = reader.Value?.ToString();
        }
        existingValue = Encoding.GetEncoding(webName);

        return existingValue;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        string webName = (value as Encoding).WebName;
        serializer.Serialize(writer, webName);
    }
}

And can be used very easy:

MyTest m = new MyTest();
JsonEncodingConverter[] conv = new[] { new JsonEncodingConverter() };
string original = JsonConvert.SerializeObject(m, Formatting.Indented);
string data = JsonConvert.SerializeObject(m, Formatting.Indented, conv);
//https://www.iana.org/assignments/character-sets/character-sets.xhtml
Console.WriteLine(data);
Console.WriteLine("and now the original");
Console.WriteLine(original);
MyTest s = JsonConvert.DeserializeObject<MyTest>(data, conv);
Console.WriteLine(s.enc.WebName);

The result of serializing it is now

{
“enc”: “us-ascii”
}

And because it has this code

public override bool CanConvert(Type objectType)
{
    return (typeof(Encoding).IsAssignableFrom(objectType));
}

it means it will serialize just the encoding, not other tools.

And it is more easy to be edited by someone.

Moral: Aim for simple string that can be edited can be achieved when serializing. Do not stay with defaults!

 

( you can easy achieve backwards compatibility for already serialized Encoding by asking

if (reader.TokenType == JsonToken.StartObject)
{
    webName = reader.Value?.ToString();
    //handling old data format for encoding
    while (reader.TokenType != JsonToken.EndObject)
    {
        if (!reader.Read())
            break;
        if (reader.TokenType != JsonToken.PropertyName)
            continue;
        var val = reader.Value?.ToString();
        if (string.Compare("webname", val, StringComparison.InvariantCultureIgnoreCase) == 0)
        {
            webName = reader.ReadAsString();
            //do not break - advance reading to the end
            //break;
        }
    }

}

)

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.