Home DEVELOPER .NET 10.0 preview 3 types of extension brings

.NET 10.0 preview 3 types of extension brings

0


.NET 10.0 preview is for download from tomorrow .NET is ready on download page Ready. As a development environment, you need Visual Studio 17.14 Preview 2.0 as before. There was no update yesterday, which means new language features. C# According to language facility status It will only be known by preview 3.0. When translating by editing and command line order in visual studio code dotnet build However, new features are already working.




Dr. Holgar Schwichtenberg is the main technology specialist in the Maximago software development. Along with the team of experts on www.it-visions.de, he also provides advice and training in the fields of Microsoft, Java and web techniques. He lectures at expert conferences and is the author of several expert books.


Establishment Program.

The installation program .NET 10.0 preview shows components of 3 SDK (Image 1).

(Image: Screenshot (Holgar Shavichenburg))

Later expansion of classes, even though they are already compiled elsewhere (for example in classes distributed in .NET class libraries by Microsoft), C#language version 3.0 since there are additional methods under the name “Extension Methods”. It appeared together in 2007 with .NET Framework 3.5. However, one can only add examples methods. So someone had to express such constructions that were appropriate by name, as well as see IsEmptyClassic() 1 in the list 1:

public static class StringExtensionClassic
{
   public static string TruncateClassic(this string s, int count)
   {
      if (s == null) return "";
      if (s.Length <= count) return s;
      return s.Substring(0, count) + "...";
   }

   public static bool IsEmptyClassic(this string s)
               => String.IsNullOrEmpty(s);
}

Listing 1: Classic Extension methods

C# 14.0 is now with new block keywords extension A common possibility of expansion of existing .NET classes. key term extension At the top level, one should be part of a static, non-pemenic class (ie no nested class). Keyword extension If you announce the type of expansion in listing 2 System.String (Alternatively formed -brief by these types stringAll methods and properties within the extension block then expand the types described here. Currently the following constructions can be used in these extension blocks (see Listing 2):

  • Examples
  • Static methods
  • Example properties with gayer
  • Stable properties

Unfortunately, when an attempt is made to give a setting to a property, the compiler unfortunately catches with the wrong message “Extension announcements may only include or qualities”.

OrderedDictionary websites = new OrderedDictionary();
websites.Add("Heise", "www.Heise.de");
websites.Add("Microsoft", "www.Microsoft.com");
websites.Add("IT-Visions", "www.IT-Visions.de");

var propertyName = "IT-Visions";
var value = "www.IT-Visions.de";

// bisher
if (!websites.TryAdd(propertyName, value))
{
  int index1 = websites.IndexOf(propertyName); // Second lookup operation
  CUI.Warning("Element " + value + " ist bereits vorhanden!");
}

// neu
if (!websites.TryAdd(propertyName, value, out int index))
{
  CUI.Warning("Element " + value + 
              " ist bereits vorhanden an der Position " + 
              index + """!""");
}

// neu
if (websites.TryGetValue(propertyName, out string? value2, out int index2))
{
  CUI.Success($"Element {value2} wurde gefunden an der Position {index2}.");
}

Listing 2: Extension with System.String C# 14.0

Listing 3 reflects the call of old and new extensions. Developers now have the option to use old or new syntax for extension methods. Visual Studio will offer refacting methods for conversion between two syntax forms. In addition, Microsoft is planning to allow further constructions in extension blocks in upcoming preview versions, such as constructors. Syntax for extensions that Microsoft had progress for C# 13.0 (public implicit extension Name for Typ) It was rejected.

public class StringExtensionDemo
{
   public void Run()
   {
      string s1old = "Hello World";
      string s1oldtruncated = s1old.TruncateClassic(5);
      Console.WriteLine(s1oldtruncated); // Hello...
      string s2old = null;
      Console.WriteLine(s2old.IsEmptyClassic()); // true

      string s1 = "Hello World";
      string s1truncated = s1.Truncate(5);
      Console.WriteLine(s1truncated); // Hello...

      string s2 = null;
      Console.WriteLine(s2.IsEmpty); // true

      string s3 = string.Create(5, '#');
      Console.WriteLine(s3); // "#####"
   }
}

Listing 3: Calling Extension in Listing 1 and 2

Another very useful new voice in C# 14.0 refers to Microsoft Null conditional assignment. This enables developers to create an assignment for a property whether the object is checked null Is. instead of

Website aktuelleDOTNETWebsite = Website.Load(123);
if (aktuelleDOTNETWebsite!= null)
{
 // Aktualisieren der URL
 aktuelleDOTNETWebsite.Url = "https://www.dotnet10.de";
}

Can you now write small with the question mark:

aktuelleDOTNETWebsite?.Url = "https://www.dotnet10.de";

This does not make the mistake of the word. However, if nothing happens in the variable aktuelleDOTNETWebsite Value null Is the owner.

In the project template “asp.net core web API (native aot)”, the metadata generation with Openapi specification (OAS) is now active in standard. With command

dotnet new webapiaot --name ITVisionsWebAPI

A project that refers to NUGET package microsoft.aspnetcore.openapi and Openapi with Program.cs with support

builder.Services.AddOpenApi();

And

app.MapOpenApi();

Active.

So far, Openapi support was only active in the project template “Webapi”, which does not allow compilation with NativeAot compiler. In project tempiaot “Webapiaot”, developers can also deactivate Openapi features with parameters --no-openapi,

dotnet new webapiaot --name ITVisionsWebAPI --no-openapi

In .NET 9.0 (16) new: New quantity class orderhadiktiry

Problems available in preview 2 that the webapi projects have always made 404 error, the preview has been fixed in 3. XML comments

, And This can be transferred to the openAPI document as preview 2 is seen there summary And description,

Asp.net core minimum webapis is now dominating parameter verification with data annotations. He can do Till now only controller-based webpis,

For minimal webapis, developers only have to activate the verification facility in the project file


    
$(InterceptorsNamespaces);Microsoft.AspNetCore.Http.Validation.Generated
  

Like in start file:

builder.Services.AddValidation();

Then you can use well known verification anotation (MinLength), (MaxLength), (Range), (Url), (EmailAddress), (Phone), (CreditCard), (RegularExpression) And many more (see list Learn Microsoft) For example, also work in minimum webpis:

app.MapGet("/checkwebsite", ((MinLength(5)) string name, (Url) string url)
       => WebsiteChecker.CheckWebsite(name, url));

Here is http call

http://localhost:5245/checkwebsite?name=ITVisions&url=www.IT-Visions.de

On the runtime to return the JSON document with two verification errors (see Figure 2).



This asp.net core was not corresponding to both parameters verification rules (Fig. 2) when calling the minimum webapi.

(Image: Holgar Shavichenburg)

Microsoft’s Webframework Asp.net Core and Blazor Server and Blazor Webassembly have already been handed over data between the pierrender and the main terandor through JSON-ANGENT in HTML documents. Till now, this constant component is quite complex for state developers, as you had to get an object through the first dependence injection.

@inject PersistentComponentState ApplicationState

And then placed the condition as an object

private PersistingComponentStateSubscription? persistingSubscription;

persistingSubscription = ApplicationState.RegisterOnPersisting(() =>
        {
            ApplicationState.PersistAsJson("name", daten);
            return Task.CompletedTask;
        });

And clearly get out again

if (ApplicationState.TryTakeFromJson("name", out var daten))
        {
            Daten = daten;
        }

In Microsoft .NET 10.0 preview 3 was fundamentally simplified, in which the manifestative continuous component with the state. Developers should now have an assets with only anotation (SupplyParameterFromPersistentComponentState) Provided and don’t worry about anything else:

(SupplyParameterFromPersistentComponentState)
public Daten? daten { get; set; }

The fingerprinting introduced in Blazor 9.0 now works for the so -called “Standalone Blazore Websambies” projects for the JavaScript file built in Blazor, which is not operated in the ASP.NET core, but can be hosted on a stable web server. To do this, use in project settings

true

And in html head area


Script day is then


This improvement has not yet been implemented in the project template, what you see when you create a new project:

dotnet new blazorwasm -n ITVisionsDemo

For blazor webasssembly you should have surrounding definition (development, staging, production) First done through HTTP headerNow Microsoft automatically considers the following environment when compiling Blazor Webass Ensembly:

  • But dotnet build: "Development"
  • But dotnet publish: "Production"

Developers can also clearly determine the type of atmosphere using a project setting, for example to staging:

Staging

Blazor is in Webassembly orbit HttpClient In standard, performance streaming is now active to increase performance and reduce the need for memory. However, only asynchronous operation is possible. This .NET is one of the braking changes in 10.0, Those who are documented in learning microsoftResponse in httpclient can be inactive with streaming:

requestMessage.SetBrowserResponseStreamingEnabled(false);

There was already an improvement for certificate exports In release notes .NET 10.0 for preview 2, but did not work there. Now in preview 3 you can actually export certificates through AES Encryption and Hashing via SHA-2-256, with a new method ExportPkcs12() Complementary to the current method Export(),

byte() pfxData = cert.ExportPkcs12(Pkcs12ExportPbeParameters.Pbes2Aes256Sha256, password);

Older procedures (3des Cly and Sha1-Hashing) Export() But it is also possible using the new method:

byte() pfxData = cert.ExportPkcs12(Pkcs12ExportPbeParameters.Pkcs12TripleDesSha1, password);

In addition, .NET 10.0 preview 3 verification reference, provides some minor improvements for telemetry and ML.NET, Which you can find in release notes,

In November 2025, up to publication, four and preview versions and two release candidates of .NET 10.0 can be expected.


(May)

Old city, silhouette and bright colors: pictures of week 14

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exit mobile version