Hannes DuPreez, Author at CodeGuru https://www.codeguru.com/author/hannes-dupreez/ Thu, 09 Feb 2023 05:15:55 +0000 en-US hourly 1 https://wordpress.org/?v=6.3.2 GitHub AI Pair Programmer Feature Highlight https://www.codeguru.com/tools/github-ai-pair-programmer/ Wed, 08 Feb 2023 15:48:59 +0000 https://www.codeguru.com/?p=19668 GitHub recently added a new feature, known as the AI pair programmer, in a bid to take advantage of recent advances in artificial intelligence. AI is getting a lot of attention right now thanks to the popularity of AI tools like ChatGPT and Google’s Bard, as the Internet finds new ways to leverage the offerings […]

The post GitHub AI Pair Programmer Feature Highlight appeared first on CodeGuru.

]]>
GitHub recently added a new feature, known as the AI pair programmer, in a bid to take advantage of recent advances in artificial intelligence. AI is getting a lot of attention right now thanks to the popularity of AI tools like ChatGPT and Google’s Bard, as the Internet finds new ways to leverage the offerings of machine learning. In this developer tool highlight, we take a look at GitHub Copilot’s newest feature and learn how it can benefit programmers.

What is GitHub Copilot AI Pair Programmer?

GitHub Copilot

GitHub Copilot is an AI-powered integrated development environment (IDE) that uses machine learning and artificial intelligence to assist developers and software engineers write better, faster, and more intuitive code. Having the ability to “read” and understand the code and comments programmers type, GitHub Copilot determines the context of the code you enter and offers code suggestions as you type.

The code suggestions can be something as simple as a line of code or an entire function. GitHub Code is powered by the OpenAI Codex, which is a generative language model developed by OpenAI.

The code suggestions occur as the developer is typing – simply start entering a new line, adding a comment, or writing a natural language comment that describes what the code should do and GitHub Copilot will analyze the information and present suggestions right inside the editor. Suggestions are available for many of the top programming languages, including powerhouses like Python, JavaScript, C#, and C++ – to name but a few.

GitHub Copilot also integrates with other developer tools, IDEs, and code editors, including Visual Studio, VS Code, JetBrains IDEs, and Neovim.

With GitHub Copilot programmers can:

  • Use the IDE platform that they are most comfortable with such as Neovim, Visual Studio, Visual Studio Code, and JetBrains.
  • Get code suggestions through AI. These suggestions can match a project’s context and style conventions.
  • Code in unfamiliar languages.

Read: Top Plugins for Visual Studio

Benefits of GitHub Copilot

GitHub Copilot has the additional added features:

    • Reduced Distractions: Instead of searching for hours for a possible solution to a problem on the Internet, GitHub Copilot reduces the need for it by using its AI while developers are coding.
    • Handle repetitive tasks: Sometimes a day in a developer’s life can be dull and mind numbing. GitHub Copilot handles repetitive tasks beautifully by completing most of these tasks while you work.
    • Help developers document their code: The better code is documented, the better GitHub Copilot can help give suggestions and input.

You can learn more in our GitHub Copilot Overview.

GitHub Copilot Voice Commands

One of the newest experimental features of GitHub Copilot and its AI pair programming tool is the addition of “Voice Commands”. Developers can utter the phrase “Hey, GitHub!” to access voice-based interaction with GitHub Copilot.

You can use these voice commands to control the IDE in a number of ways. For instance, you can say “Go to line 27” to have the editor go to the 27th line of your code or “Run the program” to execute a program’s code.

To get quick access to the experimental features of GitHub Copilot, the technical preview, and its voice command features apply here.

The post GitHub AI Pair Programmer Feature Highlight appeared first on CodeGuru.

]]>
What is Microsoft Orleans? https://www.codeguru.com/tools/microsoft-orleans/ Wed, 08 Feb 2023 05:03:17 +0000 https://www.codeguru.com/?p=19671 Microsoft Orleans is a cross-platform framework .NET developers can use to build scalable (from a single on-premise server, silos, or highly available cloud applications) and robust, distributed applications (applications spanning more than single processes). In this developer tool tutorial, we discuss what Microsoft Orleans is, how it works, and its benefits to C# and .NET […]

The post What is Microsoft Orleans? appeared first on CodeGuru.

]]>
Microsoft Orleans is a cross-platform framework .NET developers can use to build scalable (from a single on-premise server, silos, or highly available cloud applications) and robust, distributed applications (applications spanning more than single processes).

In this developer tool tutorial, we discuss what Microsoft Orleans is, how it works, and its benefits to C# and .NET developers.

Read: Best Build Tools for C#

Overview of Microsoft Orleans

Microsoft Orleans

Microsoft Orleans provides a set of patterns and APIs that make the complexities of developing distributed applications a lot easier. With Microsoft Orleans (commonly known as Distributed.NET), programmers can switch to building scalable, cloud-native services. It can run on any .NET environment, including Windows, Linux, and macOS.

Microsoft Orleans is based on an actor model, where each actor in the model is a lightweight, concurrent, immutable object enveloping a state and its behavior. These actors communicate with each other via the use of asynchronous messages. Actors are simply logical objects called grains (more on this later) that exist virtually, thus making them always addressable, even on failures of executing servers. More information on actors can be found here.

Microsoft Orleans

Grains are objects that consist of user-defined identities (keys making grains available to be invoked by other grains), states, and behaviors, and are the building block of actors. Some interfaces that gets implemented by grains include:

  • IGrainWithGuidKey: Grains with guid keys
  • IGrainWithIntegerKey: Grains with Int64 keys
  • IGrainWithStringkey: Grains with string keys

Read: Project Management Software for .NET Developers

What is Microsoft Orleans Used For?

Below are some of the use cases and situations Microsoft Orleans is used for:

  • Persistence
  • Timers
  • Reminders
  • Grain placement
  • Grain versioning
  • Call filters
  • Request context
  • Distributed ACID transaction
  • Streams

Persistence

Persistence ensures that the state is available before processing a request and ensures consistency. Grains can contain multiple data objects. During the running state of a grain, its state is held in memory for serving requests, thus preventing access to storage.

Timers

Timers are non-durable and are used for high-frequency events that do not require any reliability.

Reminders

Reminders are simply durable scheduling mechanisms for grains. Reminders are used to ensure the actions are completed even if the grain is not activated.

Grain Placement

Grain placement is completely configurable, where developers can decide between random, prefer-local, and load-based types. Because of this, grain placement is flexible in regards to deciding where grains are created.

Call Filters

Microsoft Orleans supports filters which include authorizations, telemetry, and error handling for both outgoing and incoming calls.

Request Context

By using the request context, metadata can be passed to grains. The request context is mainly used to hold distributed tracing information, as well as, any user-defined values.

Distributed ACID Transactions

Grains can make use of ACID (Atomic, Consistent, Isolated, Durable) transactions. These transactions are distributed, decentralized, and have serializable isolation.

The post What is Microsoft Orleans? appeared first on CodeGuru.

]]>
Developer News Is Coming Back to Visual Studio https://www.codeguru.com/tools/visual-studio-developer-news/ Tue, 24 Jan 2023 21:39:51 +0000 https://www.codeguru.com/?p=19642 If you are not familiar with previous Visual Studio versions prior to the 2019 version, you may not know have of the feature known as Developer News, which existed in versions of 2017 and prior. If you have later versions of Visual Studio, you may have noticed the Developer News feed solely in the Visual […]

The post Developer News Is Coming Back to Visual Studio appeared first on CodeGuru.

]]>
Visual Studio
If you are not familiar with previous Visual Studio versions prior to the 2019 version, you may not know have of the feature known as Developer News, which existed in versions of 2017 and prior. If you have later versions of Visual Studio, you may have noticed the Developer News feed solely in the Visual Studio installer application.

In early version of Visual Studio, the Developer News feed was updated frequently as it was displayed on the Startup page of Visual Studio, assuming, of course, that the developer chose to start with the Startup page when they booted up VS.

Not only did this helpful feed provide the latest news in VS or other .NET developments, sometimes it directed the developer to some nice examples on new features . As stated, this was a feed that was updated regularly, so there was not any developer input to display it. On a personal level I found it irritating at first, then got used to it, then missed it when the feed disappeared.

When the Developer News feed disappeared, developers were not happy at all and expressed their opinions and concerns on the Developer Community feedback and feature request site. Many independent developers started to try and fill the gap by creating various “developer news” extensions for the Visual Studio marketplace, where other developers could download it.

Microsoft had to put some decent thought into bringing this feature back because of the following reasons:

  • The news update and refresh cycles
  • Customization and filtering of news items
  • What if a developer does not make use of a start page but still wanted to get the news feed?
  • How to make the feed more accessible when solutions are open in Visual Studio

With the above thoughts in mind, Microsoft updated the refresh cycles of the news feed and allowed for filtering of news items (such as news applicable to a different language). Developers also have the choice now of opening the news articles inside the default browser, or inside Visual Studio’s built-in browser.

More features, such as including news directly from Visual Studio Magazine, local event news, and developer community integration are also slated to be included.

The bottom two were tricky, as Microsoft developers had to come up with a solution that can cater for both conditions. Thus, they made a News window which is dock-able and gave it the ability to hide and show on demand – the same as all other windows inside Visual Studio. The news tool will be docked in the same location as the Solution Explorer window for ease of access.

Read: Visual Studio Code Extensions for Higher Productivity

The post Developer News Is Coming Back to Visual Studio appeared first on CodeGuru.

]]>
Intro to Intel oneDAL and ML.NET https://www.codeguru.com/dotnet/intel-onedal-ml-net/ Mon, 16 Jan 2023 22:03:18 +0000 https://www.codeguru.com/?p=19643 Microsoft and Intel are teaming up for the latest upcoming release of ML.NET 3.0. We will briefly discuss what ML.NET is and its role in machine learning and software development. Read: Microsoft Teams Review What is Machine Learning? Machine learning (ML) is the scientific study of algorithms and models that computers use to perform tasks […]

The post Intro to Intel oneDAL and ML.NET appeared first on CodeGuru.

]]>
ML.NET tutorials

Microsoft and Intel are teaming up for the latest upcoming release of ML.NET 3.0. We will briefly discuss what ML.NET is and its role in machine learning and software development.

Read: Microsoft Teams Review

What is Machine Learning?

Machine learning (ML) is the scientific study of algorithms and models that computers use to perform tasks without using explicit instructions, relying solely instead on patterns and inference. Machine learning algorithms build models based on training data, to make decisions without being explicitly programmed to do so.

Common machine learning methods include:

  • Supervised machine learning algorithms: Apply what has been learned to new data by using labels to predict future events.
  • Unsupervised machine learning algorithms: Used when the training information provided is not classified or labeled.
  • Semi-supervised machine learning algorithms: Uses both labeled and unlabeled data for training.
  • Reinforcement machine learning algorithms: Interacts with its environment by producing actions.

What is ML.NET?

ML.NET is a free software machine learning library for C#, VB.NET, and F#. ML.NET includes transforms for feature engineering, such as n-gram creation. ML.NET also includes transforms for learners to handle binary classification, multi-class classification, and regression tasks. ML.NET also includes anomaly detection, recommendation systems, and deep learning (DL).

What is Intel oneAPI Data Analytics Library (oneDAL)

Intel oneAPI Data Analytics Library is a library that speeds up data analysis. This is done by providing optimized algorithmic building blocks for all stages of both the data analytics and the machine learning process.

oneDAL makes use of the EXPLAIN SIMD extensions in 64-bit architectures featured in Intel and AMD CPUs.

oneDAL Components in ML.NET

By integrating with ML.NET, oneDAL accelerates existing trainers during training, using the following trainer extensions:

  • Ordinary Least Squares (OLS): Used for regression
  • L-BFGS (Limited-Memory Broyden-Fletcher-Goldfarb-Shanno Algorithm): Used for classification
  • FastTree: Used for regression and classification
  • FastForest: Used for regression and classification

In order to get started, programmer will need to install the latest Microsoft.ML 3.0 preview version. Note: you may also need to install the Microsoft.ML.Mkl.Components package for OLS: Microsoft.ML.Mkl.Components.

In addition, you may need to install the Microsoft.ML.FastTree package if you are planning to use FastTree: Microsoft.ML.FastTree.

After that, developers will want to install the Microsoft.ML.OneDAL NuGet package: Microsoft.ML.OneDAL.

Finally, you will need to set the system’s MLNET_BACKEND environment variable to ONEDAL. You can use the quick code snippet below to do so:

Environment.SetEnvironmentVariable("MLNET_BACKEND", "ONEDAL");

ML.NET and oneDAL Example

Below is a quick example of how to make use of ML.NET and oneDAL by setting its trainers:

var trainer = ML.BinaryClassification.Trainers.FastForest(options);
var model = trainer.Fit(preprocessedTrainingData);
var trainingPredictions = model.Transform(preprocessedTrainingData);
var trainingMetrics = ML.BinaryClassification.EvaluateNonCalibrated(trainingPredictions, labelColumnName: "target");
var testingPredictions = model.Transform(preprocessedTestingData);
var testingMetrics = ML.BinaryClassification.EvaluateNonCalibrated(testingPredictions, labelColumnName: "target");

GitHub has a more detailed example of how to get started with oneDAL and ML.NET to help you get started.

Read more C# programming tutorials and software development tips.

The post Intro to Intel oneDAL and ML.NET appeared first on CodeGuru.

]]>
System.Text.Json improvements in .NET 7 https://www.codeguru.com/news/system-text-json-dot-net/ Fri, 21 Oct 2022 00:03:09 +0000 https://www.codeguru.com/?p=19503 Microsoft has added high impact reliability, library extensibility, consistency, and performance-orientated features to improve the System.Text.Json library. Some of the improvements to the .NET library include: Contract customization Type hierarchies Required members JsonSerializerOptions.Default System.Text.Json Updates Let’s tackle each of the updates to System.Text.Json one-by-one. Read: Best Online Courses to Learn C# Contract Customization in .NET […]

The post System.Text.Json improvements in .NET 7 appeared first on CodeGuru.

]]>
.Net Tutorials

Microsoft has added high impact reliability, library extensibility, consistency, and performance-orientated features to improve the System.Text.Json library. Some of the improvements to the .NET library include:

  • Contract customization
  • Type hierarchies
  • Required members
  • JsonSerializerOptions.Default

System.Text.Json Updates

Let’s tackle each of the updates to System.Text.Json one-by-one.

Read: Best Online Courses to Learn C#

Contract Customization in .NET

Contract customization gives developers more control on type serialization and deserialization, user-defined type hierarchies, and support for required members. The System.Text.Json library figures out how a .NET type should be serialized and deserialized by establishing a JSON contract which is derived from the .NET type’s shape. This shape includes the properties and fields, the constructor, and checks the implementation of IEnumerable or IDictionary.

The metadata has always been JsonTypeInfo , but now, in .NET 7, all of its metadata has been exposed to be modifiable, thus allowing programmers to write their own resolution logic for the JSON contracts.

Here is a small code example showing how to define a custom contract resolver in .NET:

var JSONserOptions = new JsonSerializerOptions
{
    TypeInfoResolver = new propertyContractResolver()
};

JsonSerializer.Serialize(new { value = 44 }, JSONserOptions); 

public class propertyContractResolver : DefaultJsonTypeInfoResolver
{
    public override JsonTypeInfo  GetTypeInfo(Type t, JsonSerializerOptions o)
    {
        JsonTypeInfo type = base.GetTypeInfo(t, o);

        if (type.Kind == JsonTypeInfoKind.Object)
        {
            foreach (JsonPropertyInfo prop in type.Properties)
            {
                prop.Name = prop.Name.ToUpperInvariant();
            }
        }

        return type;
    }
}

Type Hierarchies in .NET

Polymorphic serialization and deserialization of user-defined type hierarchies is now supported by System.Text.Json. This can be done with the JsonDerivedTypeAttribute library. A code example follows demonstrating polymorphic serialization and deserialization in .NET:

[JsonDerivedType(typeof(DerivedClass))]
public class Temp
{
    public int i { get; set; }
}

public class DerivedClass : Temp
{
    public int j { get; set; }
}

The above code example enables polymorphic serialization for the Base class:

Base val = new DerivedClass();
JsonSerializer.Serialize(value); 

The run-time type above is DerivedClass.

Required Members in .NET

With C# 11, support has been added for required members. This lets class authors specify properties and fields and the reflection serialization that must be populated when being instantiated. A quick C# code example follows:

using System.Text.Json;
JsonSerializer.Deserialize("""{"StudentCourse": 7}"""); 

public class Student
{
    public required string StudentName { get; set; }
    public int NumberOfSubjects { get; set; }
}

With this, a JSON exception will be thrown because the required parameter (StudentName) was not supplied.

JsonSerializerOptions.Default

A read-only instance of JsonSerializerOptions can now be passed and accessed by developers through the use of the JsonSerializerOptions.Default static property. Here is some example code demonstrating this:

public class Convert : JsonConverter
{
    private readonly static JsonConverter s_default = 
        (JsonConverter)JsonSerializerOptions.Default.GetConverter(typeof(int));

    public override void Write(Utf8JsonWriter w, int val, JsonSerializerOptions o)
    {
        return w.WriteStringValue(val.ToString());
    }

    public override int Read(ref Utf8JsonReader r, Type type, JsonSerializerOptions o)
    {
        return s_default.Read(ref r, t, o);
    }
}

Read more .NET programming tutorials and software development tips.

The post System.Text.Json improvements in .NET 7 appeared first on CodeGuru.

]]>
.NET 7 Release Candidate 2 https://www.codeguru.com/news/dot-net-seven-release-candidate/ Thu, 20 Oct 2022 18:58:10 +0000 https://www.codeguru.com/?p=19502 Microsoft’s Release Candidate 2 (the final release candidate) for .NET 7 was released on October 11, 2022. In this programming tutorial, we look at some of the features and updates developers can expect. Read: Best Online Courses for .NET Developers C# 11 Updates in .NET 7 New features and updates in C# 11 include the […]

The post .NET 7 Release Candidate 2 appeared first on CodeGuru.

]]>
C# Programming Guide

Microsoft’s Release Candidate 2 (the final release candidate) for .NET 7 was released on October 11, 2022. In this programming tutorial, we look at some of the features and updates developers can expect.

Read: Best Online Courses for .NET Developers

C# 11 Updates in .NET 7

New features and updates in C# 11 include the following.

Generic Attributes in C#

C# 11 introduces a new generic class, which encapsulates operations that are specific to a particular data type. A small example (from Microsoft) follows:

class BaseNode { }
class BaseNodeGeneric { }
// concrete type
class NodeConcrete : BaseNode { }
//closed constructed type
class NodeClosed : BaseNodeGeneric { }
//open constructed type
class NodeOpen : BaseNodeGeneric { }

An example of a generic class with the base class of System.Attribute in .NET follows:

public class GenericAttribute : Attribute { }

Required Members in C#

A Class and Struct type can make use of the required keyword to ensure that properties and fields must be properly initialized. Required members have a few rules:

  • The required modifier can be applied to fields and properties in Struct and Class types
  • Required members cannot be applied to members of an interface
  • Required members must be initialized
  • Required members must be visible as their containing type
  • Derived classes cannot hide required members that are declared in the base class

Here is a code example showing how to use required members in C#:

public class Course
{
    public required string CourseName { get; init; }
    public required int CourseDuration {get; init; }

    [SetsRequiredMembers]
    public Course(string courseName, int courseDuration)
    {
        this.CourseName = coursetName;
        this.CourseDuration = courseDuration;
    }
    public Course() {}
}

For a more detailed look at some of the new and updated features of C#, please refer to the following link.

Looking to learn C# programming in an online course environment? We have a list of the Best Online Courses for Developers.

.NET Library Updates

.NET libraries keep on improving, and there are always new features being added. In the most recent release, these include:

  • Generic Math
  • Regular Expression improvements

Generic Math Library in .NET

Generic Math gives .NET developers the ability to use operators on generic types. An example from Microsoft follows:

public static TResult Sum<T, TResult>(IEnumerable values)
    where T : INumber
    where TResult : INumber
{
    TResult result = TResult.Zero;

    foreach (var value in values)
    {
        result += TResult.Create(value);
    }

    return result;
}

public static TResult Average<T, TResult>(IEnumerable values)
    where T : INumber
    where TResult : INumber
{
    TResult sum = Sum<T, TResult>(values);
    return TResult.Create(sum) / TResult.Create(values.Count());
}

public static TResult StandardDeviation<T, TResult>(IEnumerable values)
    where T : INumber
    where TResult : IFloatingPoint
{
    TResult standardDeviation = TResult.Zero;

    if (values.Any())
    {
        TResult average = Average<T, TResult>(values);
        TResult sum = Sum<TResult, TResult>(values.Select((value) => {
            var deviation = TResult.Create(value) - average;
            return deviation * deviation;
        }));
        standardDeviation = TResult.Sqrt(sum / TResult.Create(values.Count() - 1));
    }

    return standardDeviation;
}

More information on Generic Math can be found here and Regular Expression improvements from the latest release can be seen here.

For a complete list of improvements and changes in .NET 7 Candidate Release 2, have a look here.

Read more C# programming tutorials and software development tips.

The post .NET 7 Release Candidate 2 appeared first on CodeGuru.

]]>
The Top 20 Programming Languages in 2022 https://www.codeguru.com/news/top-programming-languages/ Mon, 17 Oct 2022 14:36:41 +0000 https://www.codeguru.com/?p=19504 2022 has reached its final quarter and, as usual, this means that the Institute of Electrical and Electronics Engineers (IEEE) published its annual list of the top programming languages for the year. Their list includes the following metrics: Spectrum Programming Jobs Trending Let’s break each one of them down. These categories include the following languages […]

The post The Top 20 Programming Languages in 2022 appeared first on CodeGuru.

]]>
2022 has reached its final quarter and, as usual, this means that the Institute of Electrical and Electronics Engineers (IEEE) published its annual list of the top programming languages for the year. Their list includes the following metrics:

  • Spectrum
  • Programming Jobs
  • Trending

Let’s break each one of them down.

These categories include the following languages from the highest ranking to the lowest:

Popular Programming Languages

Read: Top Online Courses to Learn C# Programming

Top Programming Languages

How are these rankings are judged? Each language’s popularity was measured by 8 metrics. These include:

  • Google searches
  • Twitter
  • Stack Overflow
  • Reddit
  • IEEE Xplore Digital Library
  • IEEE Jobs sites
  • CareerBuilder
  • GitHub

Let’s explore each of these metrics more closely.

Google Searches

The IEEE makes use of a template known as “X programming” to get the number (which indicates the volume of online resources about each of the respective programming languages) of hits for each programming language.

Twitter

By using the Twitter Search API, the template (X Programming) was used for the months January through August to gather the amount of chatter on social media for each language. This is usually the sharing of news articles, hackathons, and books.

Just a quick note on the Twitter API: The Twitter Development Platform is used to tap into Twitter’s platform from your applications.

There are three different products being counted for:

  • Twitter API
  • Twitter Ads
  • Twitter for Websites

More information about the Twitter API can be found here.

Stack Overflow

Stack Overflow is a programming forum, such as CodeGuru and VB Forums. IEEE measured the number of questions asked that mentioned each programming language. With the help of the Stack Exchange API, the IEEE was able to tabulate the desired measurements.

More information on the Stack Exchange API can be found here.

Reddit

A similar method, like the methods above, was applied to measure the number of posts that mentioned each programming language on Reddit, using the Reddit API.

More information about the Reddit API can be found here.

IEEE Xplore Digital Library

The IEEE Xplore API searched through 3.6 million articles that mention a programming language. More information on the IEEE Xplore API for developers can be found here.

IEEE Jobs sites

The IEEE measured the demand for programming languages in job postings on its IEEE Jobs Site. This contains a huge amount of non-U.S. listings. You can learn more about the IEEE Jobs Site here.

CareerBuilder

The IEEE measured the demand for programming languages in job postings on the CareerBuilder job website to help determine popularity of programming languages based on how many jobs were available for each.

GitHub

The IEEE made use of GitHub 2.0 to measure the top 50 programming languages used in GitHub repositories. The below table lists the top 50 programming languages being used on GitHub:

itHub Programming Languages Report

You can view the GitHub programming language usage stats here.

The post The Top 20 Programming Languages in 2022 appeared first on CodeGuru.

]]>
New Feature in .NET 7: Rate Limiting https://www.codeguru.com/dotnet/dot-net-rate-limiting/ Wed, 24 Aug 2022 04:59:16 +0000 https://www.codeguru.com/?p=19398 As its name implies, rate limiting limits how much of a particular resource can be accessed. An example could be that your application can send through hundreds of requests in a minute, but you are not sure if the application or database is capable of overseeing that many requests. In such a case, programmers can […]

The post New Feature in .NET 7: Rate Limiting appeared first on CodeGuru.

]]>
.Net Tutorials
As its name implies, rate limiting limits how much of a particular resource can be accessed. An example could be that your application can send through hundreds of requests in a minute, but you are not sure if the application or database is capable of overseeing that many requests. In such a case, programmers can put a rate limiter in the application to oversee the number of requests they would like to handle in a given amount of time (such as a minute) and then reject any requests beyond that point before accessing the database.

In this manner, rate limiting allows your application to oversee a safe number of requests without (potentially) experiencing failures from a connected database.

Looking to learn .NET software development in a class or online course? We have a tutorial listing the Top Courses to Learn .NET to help you get started.

How to Use RateLimiter in .NET

The RateLimiter abstract base class is illustrated in the .NET code example below:

public abstract class RateLimiter : IAsyncDisposable, IDisposable
{
    public abstract int GetAvailablePermits();
    public abstract TimeSpan? IdleDuration { get; }

    public RateLimitLease Acquire(int permitCount = 1);
    public ValueTask WaitAsync(int permitCount = 1, CancellationToken = default);

    public void Dispose();
    public ValueTask DisposeAsync();
}

RateLimiter can be found inside the System.Threading.RateLimiting NuGet package.

Using the Acquire Method in .NET

In the following example, we acquire a permit via the Acquire method. If the permit has been acquired, we can perform a given action, or else we can make use of error handling:

RateLimiter rlMyLimiter = GetLimiter();
using RateLimitLease rlMyRateLimitLease = rlMyLimiter.Acquire(permitCount: 1);
if (rlMyRateLimitLease.IsAcquired)
{
    // Anything in here is protected by the limiter
}
else
{
    // Here, error logic could be added
}

Concurrent Rate Limiters in .NET

The next .NET code example shows a concurrent rate limiter making use of queueing permits, which checks if a permit is available or not:

RateLimiter rlMyLimiter  = new ConcurrencyLimiter(
    new ConcurrencyLimiterOptions(permitLimit: 2, queueProcessingOrder: QueueProcessingOrder.OldestFirst, queueLimit: 2));

// First thread
using RateLimitLease rlMyRateLimitLease = rlMyLimiter.Acquire(permitCount: 2);
if (rlMyRateLimitLease.IsAcquired) 
{
	//Anything in here is protected by the limiter
}
else
{
    // Here, error logic could be added for Second Thread
}

// Second Thread
using RateLimitLease rlMyRateLimitLease = await rlMyLimiter.WaitAsync(permitCount: 2);
if (rlMyRateLimitLease.IsAcquired) 
{
	//Anything in here is protected by the limiter
}
else
{
    // Here, error logic could be added for Second Thread
}

Token Bucket Rate Limiter in .NET

The next code example shows the use of a token bucket rate limiter, which developers can use to set the tokens that can get added per period, and how often this should occur:

RateLimiter rlMyLimiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions(tokenLimit: 5, queueProcessingOrder: QueueProcessingOrder.OldestFirst,
    queueLimit: 1, replenishmentPeriod: TimeSpan.FromSeconds(5), tokensPerPeriod: 1, autoReplenishment: true));
using RateLimitLease rlMyRateLimitLease1 = await rlMyLimiter.WaitAsync(5);

using RateLimitLease rlMyRateLimitLease2 = await rlMyLimiter.WaitAsync();

You can learn more about the RateLimiter API in .NET from its official documentation.

Read more .NET programming tutorials and news.


The post New Feature in .NET 7: Rate Limiting appeared first on CodeGuru.

]]>
The .NET Community Toolkit 8.0 https://www.codeguru.com/tools/dot-net-community-toolkit/ Tue, 23 Aug 2022 00:09:51 +0000 https://www.codeguru.com/?p=19396 In this programming tutorial, we take a look at the .NET Community Toolkit version 8, its new features, and updates to the developer tool. Read: Productivity Tools for .NET Developers What is the .NET Community Toolkit? The .NET Community Toolkit (which was originally part of the Windows Community Toolkit) is simply a collection of APIs […]

The post The .NET Community Toolkit 8.0 appeared first on CodeGuru.

]]>
In this programming tutorial, we take a look at the .NET Community Toolkit version 8, its new features, and updates to the developer tool.

Read: Productivity Tools for .NET Developers

What is the .NET Community Toolkit?

.NET Community Toolkit 8

The .NET Community Toolkit (which was originally part of the Windows Community Toolkit) is simply a collection of APIs and other helpers. The Toolkit forms part of the .NET foundation and is system and platform agnostic. These libraries multi-target from .NET Standard 2.0 to .NET 6.

The .NET Community Toolkit is available on GitHub and includes every library in the Toolkit. These libraries include:

  • CommunityToolkit.HighPerformance
  • CommunityToolkit.Common
  • CommunityToolkit.Diagnostics
  • CommunityToolkit.Mvvm

CommunityToolkit.HighPerformance

CommunityToolkit.HighPerformance contains helpers that allow developers to work more efficiently with high-performance code. It also includes the following APIs:

  • Pooled buffer helpers: These represent a pool of memory blocks.
  • String pool type: The StringPool type implements a configurable pool for string instances to minimize memory allocation when multiple char or byte string instances are created.
  • 2D variant of Memory<T> – Memory2D<T>: Memory2D<T> contains the same functionality as the Memory type, and can be used to represent 2D memory locations.
  • 2D variant of <Span<T> – Span2D<T>: Span2D<T> contains the same functionality as the <Span<T> type, but it supports 2D memory regions.

CommunityToolkit.Common

CommunityToolkit.Common contains helper APIs that are shared with other libraries in the Community Toolkit. These include the following:

CommunityToolkit.Diagnostics

CommunityToolkit.Diagnostics contains helper APIs that deal with more efficient argument validation and error checking. Some APIs include:

Guard

Guard validates method arguments smoothly, thus, making it faster, less verbose, less error-prone, and more expressive, saving developers from writing checks and throwing exceptions manually.

The Guard APIs are based on the following three principles:

  • Speed: The methods in Guard APIs are generated by making use of T4 templates. As per my book on Visual Studio 2019: “A T4 text template or pre-processed template is a combination of text blocks and control logic that can generate a text file. The logic is written as fragments of program code.”

    There are two types of pre-processed text templates: Design Time (Design-time T4 text templates generate program code in a Visual Studio project) and Runtime (we can generate text strings in our applications during runtime using runtime T4 text templates.)

  • Being intuitive: All Guard APIs have simple self-explanatory names that make them easy to identify and deduce their purposes.
  • Helpfulness: Guard APIs supply detailed exception messages. For more information on Guard APIs have a look at their official documentation.
  • ThrowHelper: As its name implies, the ThrowHelper class helps to efficiently throw exceptions. This class is best used in conjunction with the Guard APIs, especially if programmers want detailed control of the exceptions being thrown.

CommunityToolkit.Mvvm

The MVVM is built around the following principles, according to Microsoft:

  • Platform and Runtime Independent: .NET Standard 2.0 and .NET 5 (UI Framework Agnostic)
  • Simple to pick up and use: No strict requirements on Application structure or coding-paradigms (outside of ‘MVVM’ness); i.e., flexible usage.
  • À la carte: Freedom to choose which components to use.
  • Reference Implementation: Lean and performant, providing implementations for interfaces that are included in the Base Class Library, but lack concrete types to use them directly.

For more information on Microsoft.Toolkit.Mvvm, read its official documentation.

Read more .NET developer tool tutorials, news, and reviews.

The post The .NET Community Toolkit 8.0 appeared first on CodeGuru.

]]>
GitHub Copilot Overview https://www.codeguru.com/tools/github-copilot/ Sat, 06 Aug 2022 22:02:26 +0000 https://www.codeguru.com/?p=19371 According to GitHub, GitHub Copilot is an “AI pair programmer that offers autocomplete-style suggestions as you code. You can receive suggestions from GitHub Copilot either by starting to write the code you want to use, or by writing a natural language comment describing what you want the code to do. GitHub Copilot analyzes the context […]

The post GitHub Copilot Overview appeared first on CodeGuru.

]]>
According to GitHub, GitHub Copilot is an “AI pair programmer that offers autocomplete-style suggestions as you code. You can receive suggestions from GitHub Copilot either by starting to write the code you want to use, or by writing a natural language comment describing what you want the code to do. GitHub Copilot analyzes the context in the file you are editing, as well as related files, and offers suggestions from within your text editor.

The GitHub Copilot further states that the developer tool is “is optimized to help you write Python, JavaScript, TypeScript, Ruby, Go, C#, or C++. You can also use GitHub Copilot to generate suggestions in other languages and a wide variety of frameworks. GitHub Copilot is powered by OpenAI Codex, a new AI system created by OpenAI.

To sum all of that up, with GitHub Copilot, developers and programmers can:

  • Use the integrated development environment (IDE) platform that they are most comfortable with such as Neovim, Visual Studio, Visual Studio Code, and JetBrains.
  • Get code suggestions through AI. These suggestions can match a project’s context and style conventions.
  • Code in unfamiliar languages.

Read: C# Tools for Code Quality

What are the Benefits of GitHub Copilot?

GitHub Copilot offers the following benefits to developers:

  • Reduced distractions: Instead of searching for hours for a possible solution to a problem on the Internet, GitHub Copilot reduces the need for further research by using its AI to provide suggestions while you are coding.
  • Handles repetitive tasks:: Sometimes a day in a developer’s life can be dull and mind-numbing. GitHub Copilot handles repetitive tasks beautifully by completing common tasks while you work.
  • Helps developers document their code: The better code is documented, the better GitHub Copilot can help give suggestions and input. GitHub Copilot not only makes documenting code easier with a set of documentation tools, it also makes documenting more rewarding, as the more a coder documents, the better Copilot’s AI can understand what the code is meant to do.

Getting Started with GitHub Copilot in Visual Studio

To start using GitHub Copilot with Visual Studio, simple follow these steps:

  • Create a new project or open an existing project in Visual Studio.
  • Click Extensions, the Manage Extensions.
  • Select Visual Studio Marketplace.
  • Search for Copilot.

Upon completing these steps, your screen will look like the image below:

Visual Studio GitHub Copilot extension

Figure 1 – Copilot Extension

Next, continue following these steps:

  • Click Download and close the Extensions window.
  • Close Visual Studio.

The Installer screen will appear. Continue following the steps below after this screen appears:

Install GitHub Copilot

Figure 2 – Install Copilot

    • Click Modify.
    • Once the installation has finished, launch Visual Studio again.
    • A popup window appears after you have opened Visual Studio again:

GitHub Copilot Visual Studio Extension

Figure 3 – Activation Code

      • Click OK.
      • Your default web browser will open, asking for a code that was sent to you via email.
      • After entering the code, select Authorize GitHub Copilot Plugin to start using GitHub Copilot in your coding environment.

You should now be all set. To learn how to configure GitHub Copilot in your IDE, check out GitHub Copilot’s official documentation.

Read more developer tool reviews, guides, and how-to’s.

The post GitHub Copilot Overview appeared first on CodeGuru.

]]>