Wouldn’t it be nice if Visual Studio could autogenerate clients for external API? It is actually possible, if they expose an OpenAPI file. Let’s see how!
Source link
برچسب: generate
-
How to generate code from OpenAPI definition with Visual Studio 2019
-

C# Tip: use IHttpClientFactory to generate HttpClient instances
Just a second! 🫷
If you are here, it means that you are a software developer.
So, you know that storage, networking, and domain management have a cost .If you want to support this blog, please ensure that you have disabled the adblocker for this site.
I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.Thank you for your understanding.
– DavideThe problem with HttpClient
When you create lots of
HttpClientinstances, you may incur Socket Exhaustion.This happens because sockets are a finite resource, and they are not released exactly when you ‘Dispose’ them, but a bit later. So, when you create lots of clients, you may terminate the available sockets.
Even with
usingstatements you may end up with Socket Exhaustion.class ResourceChecker { public async Task<bool> ResourceExists(string url) { using (HttpClient client = new HttpClient()) { var response = await client.GetAsync(url); return response.IsSuccessStatusCode; } } }Actually, the real issue lies in the disposal of
HttpMessageHandlerinstances. With simpleHttpClientobjects, you have no control over them.Introducing HttpClientFactory
The
HttpClientFactoryclass createsHttpClientinstances for you.class ResourceChecker { private IHttpClientFactory _httpClientFactory; public ResourceChecker(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } public async Task<bool> ResourceExists(string url) { HttpClient client = _httpClientFactory.CreateClient(); var response = await client.GetAsync(url); return response.IsSuccessStatusCode; } }The purpose of
IHttpClientFactoryis to solve that issue withHttpMessageHandler.An interesting feature of
IHttpClientFactoryis that you can customize it with some general configurations that will be applied to all theHttpClientinstances generated in a certain way. For instance, you can define HTTP Headers, Base URL, and other properties in a single point, and have those properties applied everywhere.How to add it to .NET Core APIs or Websites
How can you use HttpClientFactory in your .NET projects?
If you have the Startup class, you can simply add an instruction to the
ConfigureServicesmethod:public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); }You can find that extension method under the
Microsoft.Extensions.DependencyInjectionnamespace.Wrapping up
In this article, we’ve seen why you should not instantiate HttpClients manually, but instead, you should use
IHttpClientFactory.Happy coding!
🐧
-

LINQ’s Enumerable.Range to generate a sequence of consecutive numbers | Code4IT
Just a second! 🫷
If you are here, it means that you are a software developer.
So, you know that storage, networking, and domain management have a cost .If you want to support this blog, please ensure that you have disabled the adblocker for this site.
I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.Thank you for your understanding.
– DavideWhen you need to generate a sequence of numbers in ascending order, you can just use a
whileloop with an enumerator, or you can useEnumerable.Range.This method, which you can find in the
System.Linqnamespace, allows you to generate a sequence of numbers by passing two parameters: the start number and the total numbers to add.Enumerable.Range(start:10, count:4) // [10, 11, 12, 13]⚠ Notice that the second parameter is not the last number of the sequence. Rather, it’s the length of the returned collection.
Clearly, it also works if the
startparameter is negative:Enumerable.Range(start:-6, count:3) // [-6, -5, -4]But it will not work if the
countparameter is negative: in fact, it will throw anArgumentOutOfRangeException:Enumerable.Range(start:1, count:-23) // Throws ArgumentOutOfRangeException // with message "Specified argument was out of the range of valid values"(Parameter 'count')⚠ Beware of overflows: it’s not a circular array, so if you pass the
int.MaxValuevalue while building the collection you will get anotherArgumentOutOfRangeException.Enumerable.Range(start:Int32.MaxValue, count:2) // Throws ArgumentOutOfRangeException💡 Smart tip: you can use
Enumerable.Rangeto generate collections of other types! Just use LINQ’sSelectmethod in conjunction withEnumerable.Range:Enumerable.Range(start:0, count:5) .Select(_ => "hey!"); // ["hey!", "hey!", "hey!", "hey!", "hey!"]Notice that this pattern is not very efficient: you first have to build a collection with N integers to then generate a collection of N strings. If you care about performance, go with a simple
whileloop – if you need a quick and dirty solution, this other approach works just fine.Further readings
There are lots of ways to achieve a similar result: another interesting one is by using the
yield returnstatement:🔗 C# Tip: use yield return to return one item at a time | Code4IT
This article first appeared on Code4IT 🐧
Wrapping up
In this C# tip, we learned how to generate collections of numbers using LINQ.
This is an incredibly useful LINQ method, but you have to remember that the second parameter does not indicate the last value of the collection, rather it’s the length of the collection itself.
I hope you enjoyed this article! Let’s keep in touch on Twitter or on LinkedIn, if you want! 🤜🤛
Happy coding!
🐧
-

how to generate qr code in angular.
How To Generate QR Code In Angular:
In the modern digital era, QR codes have become essential for quickly sharing information through a simple scan. QR codes provide a versatile solution for marketing purposes, linking to a website, or sharing contact details. In this blog post, we’ll explore how to generate QR codes in your Angular applications using the
angularx-qrcodelibrary.We’ll guide you through the installation process, show you how to integrate the library into your Angular project and provide a complete example to get you started. By the end of this tutorial, you’ll be able to create and customize QR codes effortlessly, adding an extra layer of interactivity and functionality to your applications. Perfect for developers of all levels, this step-by-step guide ensures you can implement QR code generation quickly and efficiently. Join us as we dive into the world of QR codes and enhance your Angular projects with this powerful feature!
Below are the steps to implement it.
Step 1: Set Up Your Angular Project.
If you don’t have an existing Angular project, create a new one using the Angular CLI:
ng new qr-code-app cd qr-code-app
Step 2: Install
angularx-qrcodeInstall the
angularx-qrcodelibrary using npm:npm install angularx-qrcodeStep 3: Create a Component and import the QRCodeModule.
import { Component } from '@angular/core'; import { MatFormFieldModule } from '@angular/material/form-field'; import { QrCodeModule } from 'ng-qrcode'; @Component({ selector: 'app-qrcode', standalone: true, imports: [MatFormFieldModule,QrCodeModule], templateUrl: './qrcode.component.html', styleUrl: './qrcode.component.css' }) export class QrcodeComponent { value: string = 'QRCODE Generator'; }4. Update the QR Code Component.
<div class="container"> <h1>Generate QR Codes Example</h1> <qr-code value="{{value}}" size="300" errorCorrectionLevel="M"></qr-code> </div>5. Run the Application.
ng serve
Navigate to
http://localhost:4200/in your web browser. You should see a QR code generated based on the data provided.Summary
- Set up your Angular project.
- Install the
angularx-qrcodelibrary. - Import
QRCodeModulein the imports section. - Create a new component for the QR code.
- Update the component to generate and display the QR code.
- Run your application.
This setup allows you to generate and display QR codes in your Angular application easily.
-
Automate Stock Analysis with Python and Yfinance: Generate Excel Reports
In this article, we will explore how to analyze stocks using Python and Excel. We will fetch historical data for three popular stocks—Realty Income (O), McDonald’s (MCD), and Johnson & Johnson (JNJ) — calculate returns, factor in dividends, and visualize… -

2 ways to generate realistic data using Bogus | Code4IT
Just a second! 🫷
If you are here, it means that you are a software developer.
So, you know that storage, networking, and domain management have a cost .If you want to support this blog, please ensure that you have disabled the adblocker for this site.
I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.Thank you for your understanding.
– DavideIn a previous article, we delved into the creation of realistic data using Bogus, an open-source library that allows you to generate data with plausible values.
Bogus contains several properties and methods that generate realistic data such as names, addresses, birthdays, and so on.
In this article, we will learn two ways to generate data with Bogus: both ways generate the same result; the main change is on the reusability and the modularity. But, in my opinion, it’s just a matter of preference: there is no approach absolutely better than the other. However, both methods can be preferred in specific cases.
For the sake of this article, we are going to use Bogus to generate instances of the
Bookclass, defined like this:public class Book { public Guid Id { get; set; } public string Title { get; set; } public int PagesCount { get; set; } public Genre[] Genres { get; set; } public DateOnly PublicationDate { get; set; } public string AuthorFirstName { get; set; } public string AuthorLastName { get; set; } } public enum Genre { Thriller, Fantasy, Romance, Biography }Expose a Faker inline or with a method
It is possible to create a specific object that, using a Builder approach, allows you to generate one or more items of a specified type.
It all starts with the
Faker<T>generic type, whereTis the type you want to generate.Once you create it, you can define the rules to be used when initializing the properties of a
Bookby using methods such asRuleForandRuleForType.public static class BogusBookGenerator { public static Faker<Book> CreateFaker() { Faker<Book> bookFaker = new Faker<Book>() .RuleFor(b => b.Id, f => f.Random.Guid()) .RuleFor(b => b.Title, f => f.Lorem.Text()) .RuleFor(b => b.Genres, f => f.Random.EnumValues<Genre>()) .RuleFor(b => b.AuthorFirstName, f => f.Person.FirstName) .RuleFor(b => b.AuthorLastName, f => f.Person.LastName) .RuleFor(nameof(Book.PagesCount), f => f.Random.Number(100, 800)) .RuleForType(typeof(DateOnly), f => f.Date.PastDateOnly()); return bookFaker; } }In this way, thanks to the static method, you can simply create a new instance of
Faker<Book>, ask it to generate one or more books, and enjoy the result:Faker<Book> generator = BogusBookGenerator.CreateFaker(); var books = generator.Generate(10);Clearly, it’s not necessary for the class to be marked as
static: it all depends on what you need to achieve!Expose a subtype of Faker, specific for the data type to be generated
If you don’t want to use a method (static or not static, it doesn’t matter), you can define a subtype of
Faker<Book>whose customization rules are all defined in the constructor.public class BookGenerator : Faker<Book> { public BookGenerator() { RuleFor(b => b.Id, f => f.Random.Guid()); RuleFor(b => b.Title, f => f.Lorem.Text()); RuleFor(b => b.Genres, f => f.Random.EnumValues<Genre>()); RuleFor(b => b.AuthorFirstName, f => f.Person.FirstName); RuleFor(b => b.AuthorLastName, f => f.Person.LastName); RuleFor(nameof(Book.PagesCount), f => f.Random.Number(100, 800)); RuleForType(typeof(DateOnly), f => f.Date.PastDateOnly()); } }Using this way, you can simply create a new instance of
BookGeneratorand, again, call theGeneratemethod to create new book instances.var generator = new BookGenerator(); var books = generator.Generate(10);Method vs Subclass: When should we use which?
As we saw, both methods bring the same result, and their usage is almost identical.
So, which way should I use?
Use the method approach (the first one) when you need:
- Simplicity: If you need to generate fake data quickly and your rules are straightforward, using a method is the easiest approach.
- Ad-hoc Data Generation: Ideal for one-off or simple scenarios where you don’t need to reuse the same rules across your application.
Or use the subclass (the second approach) when you need:
- Reusability: If you need to generate the same type of fake data in multiple places, defining a subclass allows you to encapsulate the rules and reuse them easily.
- Complex scenarios and extensibility: Better suited for more complex data generation scenarios where you might have many rules or need to extend the functionality.
- Maintainability: Easier to maintain and update the rules in one place.
Further readings
If you want to learn a bit more about Bogus and use it to populate data used by Entity Framework, I recently published an article about this topic:
🔗Seeding in-memory Entity Framework with realistic data with Bogus | Code4IT
This article first appeared on Code4IT 🐧
But, clearly, the best place to learn about Bogus is by reading the official documentation, that you can find on GitHub.
Wrapping up
This article sort of complements the previous article about Bogus.
I think Bogus is one of the best libraries in the .NET universe, as having realistic data can help you improve the intelligibility of the test cases you generate. Also, Bogus can be a great tool when you want to showcase demo values without accessing real data.
I hope you enjoyed this article! Let’s keep in touch on LinkedIn, Twitter or BlueSky! 🤜🤛
Happy coding!
🐧