Remove the background from an Image using C#

Instead of manually processing images, and cutting out the subject from the background, you can use an API to do this, as long as the image is publicly accessible via a URL – Even temporarily accessible, you could upload to S3, then delete it again afterwards.

Here’s the code – in C#

var url = “https://image-background-removal3.p.rapidapi.com/BackgroundRemoverLambda”;

var oReq = new { url = “https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ2nkYh11Mswy-IVb5tM3C4c_nlbYOvNyso9w&usqp=CAU” };

var strReq = JsonConvert.SerializeObject(oReq);

using var web = new WebClient();
web.Headers.Add(“x-rapidapi-key”, “xxxxxx”);
var response = web.UploadData(url, “POST”, Encoding.UTF8.GetBytes(strReq));
var b64Response = Convert.FromBase64String(Encoding.UTF8.GetString(response));
File.WriteAllBytes(“result3.png”, b64Response);

Where the API Key can be found here: https://rapidapi.com/appaio/api/image-background-removal3/

The Confusing Behaviour Of EF Core OnDelete Restrict

I was recently helping another developer understand the various “OnDelete” behaviors of Entity Framework Core. That is, when a parent entity in a parent/child relationship is deleted, what should happen to the child?

I thought this was actually all fairly straight forward. The way I understood things was :

DeleteBehavior.Cascade – Delete the child when the parent is deleted (e.g. Cascading deletes)
DeleteBehavior.SetNull – Set the FK on the child to just be null (So allow orphans)
DeleteBehavior.Restrict – Don’t allow the parent to be deleted at all

I’m pretty sure if I asked 100 .NET developers what these meant, there is a fairly high chance that all of them would answer the same way. But in reality, DeleteBehavior.Restrict is actually dependant on what you’ve done in that DBContext up until the delete… Let me explain.

Setting Up

Let’s imagine that I have two models in my database, they look like so :

class BlogPost
{
public int Id { get; set; }
public string PostName { get; set; }
public ICollection<BlogImage> BlogImages { get; set; }
}

class BlogImage
{
public int Id { get; set; }
public int? BlogPostId { get; set; }
public BlogPost? BlogPost { get; set; }
public string ImageUrl { get; set; }
}

Then imagine the relationship in EF Core is set up like so :

modelBuilder.Entity<BlogImage>()
.HasOne(x => x.BlogPost)
.WithMany(x => x.BlogImages)
.OnDelete(DeleteBehavior.Restrict);

Any developer looking at this at first glance would say, if I delete a blog post that has images pointing to it, it should stop me from deleting the blog post itself. But is that true?

Testing It Out

Let’s imagine I have a simple set of code that looks like do :

var context = new MyContext();
context.Database.Migrate();

var blogPost = new BlogPost
{
PostName = “Post 1”,
BlogImages = new List<BlogImage>
{
new BlogImage
{
ImageUrl = “/foo.png”
}
}
};

context.Add(blogPost);
context.SaveChanges();

Console.WriteLine(“Blog Post Added”);

var getBlogPost = context.Find<BlogPost>(blogPost.Id);
context.Remove(getBlogPost);
context.SaveChanges(); //Does this error here? We are deleting the blog post that has images

Console.WriteLine(“Blog Post Removed”);

Do I receive an exception? The answer is.. No. When this code is run, and I check the database I end up with a BlogImage that looks like so :

So instead of restricting the delete, EF Core has gone ahead and set the BlogPostId to be null, and essentially given me an orphaned record. But why?!

Diving headfirst into the documentation we can see that DeleteBehavior.Restrict has the following description :

For entities being tracked by the DbContext, the values of foreign key properties in dependent entities are set to null when the related principal is deleted. This helps keep the graph of entities in a consistent state while they are being tracked, such that a fully consistent graph can then be written to the database. If a property cannot be set to null because it is not a nullable type, then an exception will be thrown when SaveChanges() is called.

Emphasis mine.

This doesn’t really make that much sense IMO. But I wanted to test it out further. So I used the following test script, which is exactly the same as before, except half way through I recreate the DB Context. Given the documentation, the entity I pull back for deletion will not have the blog images themselves being tracked.

And sure enough given this code :

var context = new MyContext();
context.Database.Migrate();

var blogPost = new BlogPost
{
PostName = “Post 1”,
BlogImages = new List<BlogImage>
{
new BlogImage
{
ImageUrl = “/foo.png”
}
}
};

context.Add(blogPost);
context.SaveChanges();

Console.WriteLine(“Blog Post Added”);

context = new MyContext(); // <– Create a NEW DB context

var getBlogPost = context.Find<BlogPost>(blogPost.Id);
context.Remove(getBlogPost);
context.SaveChanges();

Console.WriteLine(“Blog Post Removed”);

I *do* get the exception I was expecting all along :

SqlException: The DELETE statement conflicted with the REFERENCE constraint “FK_BlogImages_BlogPosts_BlogPostId”.

Still writing this, I’m struggling to understand the logic here. If by some chance you’ve already loaded the child entity (By accident or not), your delete restriction suddenly behaves completely differently. That doesn’t make sense to me.

I’m sure some of you are ready to jump through your screens and tell me that this sort of ambiguity is because I am using a nullable FK on my BlogImage type. Which is true, and does mean that I expect that a BlogImage entity *can* be an orphan. If I set this to be a non-nullable key, then I will always get an exception because it cannot set the FK to null. However, the point I’m trying to make is that if I have a nullable key, but I set the delete behavior to restrict, I should still see some sort of consistent behavior.

What About DeleteBehavior.SetNull?

Another interesting thing to note is that the documentation for DeleteBehavior.SetNull is actually identical to that of Restrict :

For entities being tracked by the DbContext, the values of foreign key properties in dependent entities are set to null when the related principal is deleted. This helps keep the graph of entities in a consistent state while they are being tracked, such that a fully consistent graph can then be written to the database. If a property cannot be set to null because it is not a nullable type, then an exception will be thrown when SaveChanges() is called.

And yet, in my testing, using SetNull does not depend on which entities are being tracked by the DbContext, and works the same every time (Although, I did consider that possibly this is a SQL Server function using the default value rather than EF Core doing the leg work).

I actually spent a long time using Google-Fu to try and find anyone talking about the differences between SetNull and Restrict but, many just go along with what I described in the intro. SetNull sets null when it came, and restrict always stops you from deleting.

Conclusion

Maybe I’m in the minority here, or maybe there is a really good reason for the restrict behavior acting as it does, but I really do think that for the majority of developers, when they use DeleteBehavior.Restrict, they are expecting the parent to be blocked from being deleted in any and all circumstances. I don’t think anyone expects an accidental load of an entity into the DbContext to suddenly change the behavior. Am I alone in that?

The post The Confusing Behaviour Of EF Core OnDelete Restrict appeared first on .NET Core Tutorials.

Get to Know EF Core 6

The Entity Framework Core team has released the generally available version of EF Core 6.0 in parallel with .NET 6.
EF Core 6 is available as a set of NuGet Packages. At the end of this blog post you will find a packages section that lists all of the
available packages and describes what they are used for.

EF Core 6.0 is a modern, cloud-native-friendly data access API that supports multiple backends. Get up and running with a document-based Azure Cosmos DB container using only a few lines of code, or use your LINQ query skills to extract the data you need from relational databases like SQL Server, MySQL, and PostgreSQL. EF Core is a cross-platform solution that runs on mobile devices, works with data-binding in client WinForms and WPF apps “out of the box”, and can even run inside your browser!

Did you know it is possible to embed a SQLite database in a web app and use Blazor WebAssembly to access it using EF Core? Check out Steven Sanderson’s excellent video to see how this is possible. Combined with the power of .NET 6, EF Core 6.0 delivers major performance improvements and even scored 92% better on the industry standard Tech Empower Fortunes benchmark compared to EF Core 5.0 running on .NET 5. The EF Core team and global OSS community have built and published many resources to help you get started.

This blog post lists a few ways to learn about new features and get up and running with Entity Framework Core as quickly as possible.

The first step in your journey should always be the comprehensive documentation available online at https://docs.microsoft.com/ef. There you will find
everything from a step-by-step guide to build your first EF Core app to a comprehensive list of what’s new in EF Core 6. If you find anything missing, let us know via GitHub issues and/or
submit a pull request.

Note: various samples ready to build and run are available on GitHub at: What’s New in EF Core 6 Samples.

Check out our EF Core Community Standup EF Core 6.0 retrospective to hear from the team and several community members about the release. We also presented What’s New with EF Core 6.0 at .NET Conf 2021. Be sure to check out community member Julie Lerman’s comprehensive article EF Core 6: Fulfilling the Bucket List.

For excellent advice regarding updating your existing apps, read Updating your ASP.NET Core and/or EF Core Application to .NET 6.

Get to Know EF Core 6.0

The following major areas were added or improved in EF Core 6.0, and each has several resources to help you get started.

Azure Cosmos DB

The EF Core team invested heavily to ensure that working with Azure Cosmos DB is a first class experience. From simplifying configuration to supporting raw SQL and delivering diagnostics, we believe this is a full featured option for working with the popular NoSQL database.

Resource Type
Title

Video
.NET Conf: EF Core 6 and Azure Cosmos DB

Video
Azure Cosmos DB and EF Core

Video
Cosmos Live TV: What’s New with EF Core 6 for Cosmos DB

Video
On .NET: Working with EF Core and Azure Cosmos DB

Official Docs
Cosmos Provider Enhancements

Compiled Models

EF Core parses configuration information to build a working model of how the domain maps to the underlying database. The time it takes to compile the memory increases as the number of entities, properties, and relationships grows. Customers with apps in distributed environments or using platforms like Azure Functions require fast startup times. Compiled models addresses this by building the model at development time, significantly improve the time to first query result.

Resource Type
Title

Video
Introducing EF Core Compiled Models

Blog Post
Compiled Models

Official Docs
Compiled Models

Configure Conventions

Imagine you want to impose a string column length limit of 200 characters on every table in your database. If you have hundreds of entities, this would require either applying data annotations or performing fluent configuration for every table. Pre-configuration conventions allow you to specify a rule as a convention that becomes the default unless you opt-out. This can potentially save hundreds of lines of code and allows you to make changes in a single place.

Resource Type
Title

Blog Post
Configure Conventions

Official Docs
Pre-convention Model Configuration

Migration Bundles

A popular feature of EF Core is the ability to track schema changes by version for your database. This capability is called migrations. Traditionally, migrations are embedded in your target application. They would require you to deploy the app along with the .NET SDKs and runtime to execute. To simplify this step as a part of continuous deployment, the EF Core team built migration bundles. These are self-contained, standalone executables that apply the migrations as part of your CI/CD pipeline.

Resource Type
Title

Blog Post
Introducing DevOps-friendly EF Core Migration Bundles

Official Docs
Migration Bundles

Performance

The team’s aggressive focus on performance resulted in a 92% improvement for the full stack of EF Core 6 on .NET 6 over EF Core 5 on .NET 5 according to the industry standard TechEmpower benchmark.

Resource Type
Title

Video
Visualizing Database Query Plans

Video
Performance Tuning an EF Core Application

Blog Post
EF Core Performance

Official Docs
Improved Performance on TechEmpower Fortunes

Temporal Tables

SQL Server supports temporal tables. This is an audit mechanism that tracks every change to a database table and exposes it in a queryable format. EF Core recently added first class support to create, query, and even restore entries from temporal tables.

Resource Type
Title

Video
SQL Server Temporal Tables and EF Core 6

Blog Post
Prime your flux capacitor: SQL Server temporal tables in EF Core 6

Official Docs
SQL Server Temporal Tables

GraphQL

The team focused on the GraphQL experience and although there aren’t specific changes in EF Core 6.0 related to GraphQL, here are some resources that show how well the two technologies work together.

Resource Type
Title

Video
Modern Data APIs with EF Core and GraphQL

Video
GraphQL with EF Core 6 and HotChocolate 12

Packages

The EF Core packages for EF Core 6 include:

Microsoft.EntityFrameworkCore – The main EF Core package

Microsoft.EntityFrameworkCore.SqlServer – Database provider for Microsoft SQL Server and SQL Azure

Microsoft.EntityFrameworkCore.Sqlite – Database provider for SQLite

Microsoft.EntityFrameworkCore.Cosmos – Database provider for Azure Cosmos DB

Microsoft.EntityFrameworkCore.InMemory – The in-memory database provider

Microsoft.EntityFrameworkCore.Tools – EF Core PowerShell commands for the Visual Studio Package Manager Console

Microsoft.EntityFrameworkCore.Design – Shared design-time components for EF Core tools

Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite – SQL Server support for spatial types

Microsoft.EntityFrameworkCore.Sqlite.NetTopologySuite – SQLite support for spatial types

Microsoft.EntityFrameworkCore.Proxies – Lazy-loading and change-tracking proxies

Microsoft.EntityFrameworkCore.Abstractions – Decoupled EF Core abstractions

Microsoft.EntityFrameworkCore.Relational – Shared EF Core components for relational database providers

Microsoft.EntityFrameworkCore.Analyzers – C# analyzers for EF Core

Microsoft.EntityFrameworkCore.Sqlite.Core – Database provider for SQLite without a packaged native binary

We have also published the 6.0.0 release of the Microsoft.Data.Sqlite.Core ADO.NET provider.

Installing dotnet ef

To execute EF Core migration or scaffolding commands, you’ll have to install the EF Tools package as either a global or local tool.

If you already installed a previous version of the tool, update it with

dotnet tool update –global dotnet-ef

If this is your first time installing the tool, use:

dotnet tool install –global dotnet-ef

It’s possible to use this new version of dotnet ef with projects that use older versions of the EF Core runtime. For more information on the tool, read: Get the Entity Framwork Core Tools.

Conclusion

Speed. Performance. Improved capabilities across the board. This version of EF Core 6.0 is optimized to work on your platform of choice and connect to your database of choice. Accelerate your development and speed up your performance and make the move to EF Core 6.0!

The post Get to Know EF Core 6 appeared first on .NET Blog.

Top 9 Vuetify Templates for Web Developer

Introduction
Things to Know About Vuetify: Vuetify Pros and Cons
Top 9 Examples of Vuetify Templates
Conclusions

Introduction

It is safe to say that in 2021 user experience is crucial. And, subsequently, user interface and overall project design are just as crucial. User experience and intuitive design help your end-user to not only get the overall gist of your project but also build a connection to your brand, which, ideally, evolves into brand loyalty in the future.

The reasoning behind these simple, at face value, truths is actually quite fascinating if we were to get to the bottom of this. It all has to do with the natural evolution of the paradigm of the relationship between the seller and the buyer in the wider sphere of business and, more importantly, in the narrower sphere of marketing. At the moment, the customer’s position is much more convenient when compared to the seller’s one, due to the market’s oversaturation with demand. In layman’s terms, it is always possible for a customer to look elsewhere for similar, even if worth, goods and services. That is why it is most important for a company to work over its image and overall presentation, especially when it comes to such constantly changing spheres as the web. And, coming full circle to the very beginning of our discussion, means paying close attention to your project’s web presentation and user experience and interface.

Luckily, nowadays there are ways to simplify this whole ordeal with the help of such tools as the main “characters” of today’s article – Vuetify and its templates.

Things to Know About Vuetify: Vuetify Pros and Cons

What is Vuetify and what does it have to do with everything that we have talked about already? Vuetify is a complete UI framework that can be built on top of Vue. Thus, the beautiful pun in the name. But, although we always appreciate good wordplay, we digress. The main goal of Vuetify is to provide developers with the ability to create richer and more engaging user experiences in a more effortless manner. And that is not its only advantage. One of the best things about Vuetify is its mobile-first approach to design, meaning that any app builds on this framework works on any device, be it phones, computers or tablets, right out of the box.

But that’s not where Vuetify’s pros end. Let’s take a look at them with the following rundown:

• Vuetify is open-source, giving you, as a developer, to inspect and study from other developers and vice versa.

• Vuetify’s components are reusable. Being based on Vue, Vuetify consists of components, rendering every part of your or anybody’s projects reusable. This fact, in turn, significantly simplifies unit-testing, readability and overall usage of your code.

• Vuetify possesses a large variety of components. And, being a Material Design component framework, we cannot see it as anything, but an advantage.

• Vuetify browser compatibility is vast. As Vuetify is a progressive framework, projects built with it are compatible with a wide variety of different browsers, such as:

Chrome;
Edge Insider;
Edge;
Firefox;
Safari 10+;
Internet Explorer and Safari 9. Although, this pairing is only supported with polyfill.

• Vuetify has a large community. And that’s a great fact, taking into consideration the above-mentioned fact that all of the Vuetify components are reusable, as it means that your chances of not only getting competent help from fellow developers on any emerging issues but also finding worthwhile components that you will be able to use on your projects.

• Vuetify documentation is outstanding. This advantage is pretty self-explanatory. The documentation Vuetify boasts is just as good as its paternal Vue. This allows new developers to get into working with it easier and quicker.

But every coin has two sides, meaning that Vutify is not perfect by any stretch of imagination. Let’s take a peek at Vuetify’s cons:

• Vuetify is a Material Design Framework. This is not, necessarily, a disadvantage by any means, but if you, as a developer, is not a fan of it this can be perceived as such.

• Vuetify’s customization can be somewhat challenging. But, once again, this is not a full-fledged disadvantage, as it mainly concerns developers, who are new to Vuetify and haven’t yet got a firm grip on all of its inner machinations.

So, as you can see, Vuetify not only possesses much more advantages than disadvantages, which, in their own right can be dismissed pretty easily but also is a useful and worthwhile tool for your project UI creation and improvement. Now, let’s pay our undivided attention to the other main character of today’s article – Vuetify Templates.

Top 9 Examples of Vuetify Templates

As we’ve already mentioned, Vuetify components are highly reusable. The reusability of Vuetify components, as well as the open-source nature of this framework, are such great features that they alone make Vuetify Templates so significant. In short, as a developer, you can easily create tons of beautiful Material design apps and projects just by taking good parts of different Vuetify templates of your liking, thus creating something of a highly functional Frankenstein’s Monster. And that’s not even taking into account the vast library of UI components, which we, in fact, consider one of the best on today’s market. But once again, we digress.

That is why we consider that it is quite the time to list a number of such beautifully crafted templates in order to show them to you and ignite your imagination to repurpose their components for your apps and projects. Or, maybe, you would simply find a template deserving of being used on your project. So, here we go!

1. Vue Material Template Full by Flatlogic

We are not going to make a secret of it: the very first Vuetify Template was made by us and we are more than proud of it. Even more: Vue Material Template Full is not just a template, but, actually, a fully-fledged admin dashboard, so it is safe to say that you will be able to find quite a lot of interesting components to use in your own project. And even though you are able to do it, consider using it on your projects in its entirety, because it is not just an admin dashboard, but an exceptional one at that.

This powerful and eye-pleasing admin dashboard will be a great fit for your project, especially if it is of the eCommerce variety. It is fully optimized, frequently updated, fully in-tune with and adaptable to any modern devices. Vue Material Template also contains within itself three color skins, dark mode, forms, charts, maps and tons of other great widgets that will assure a speedy start to your project’s great dashboard creation.

More details

2. ArchitectUI Dashboard Vue PRO

ArchitectUI Dashboard Vue PRO has a plethora of different components (more than two hundred, to be more accurate) that will help you save your time and effort on developing your own projects. Powered by the latest technologies, nine different color schemes and handy documentation, this template Vuetify Template is very much deserving of your attention.

More details

3. Veluxi template

Compared to the two previous Vuetify templates on this list, Veluxi definitely stands out, because its main goal is not to manage the admin side of things, but rather to be a collection of versatile landing pages, aimed at serving a number of different businesses. Agencies, educational, medical, fashion companies, mobile apps, etc. – you name it – Veluxi is ready to be of service in this sphere.

The customization process is easy and comfortable with Veluxi, even if you are a beginner level web developer, as it offers eleven variations that you can tailor to your needs and preferences. This Vuetify Template also packs a punch when it comes to the specialties department, having such cool features as animations, parallax effect, a dark mode and around one hundred components and many-many more.

More details

4. Vue Material Laravel Template by Flatlogic

Once again, we present you with our pride and glory called Vue Material Admin. Built with Laravel PHP framework (hence the name) as a backend, this Vuetify Template is more than deserving of your attention, as it is going to be a great basis for any web app imaginable and we, actually, built this template, partnered with the creators of Vuetify library. So, you can rest assured that Vue Material Laravel is following all the official guidelines to a T.

Moreover, Vue Material Laravel Template is packed to the brim with different cool features, like being deployable via Composer, JWT based authorization, three color themes, dark modes and customizable layouts. And that’s not mentioning tons and tons of reusable components.

More details

5. MaterialPro

If you are a great fan of Lightning McQueen from Pixar’s “Cars” and you are all about speed, then MaterialPro Vuetify Template deserves your undivided attention, as it has all the must-haves and some more for you to experience a speedy admin realization. 

Another great thing about MaterialPro is its proneness to tinkering and creative adjustments from your side, while all of its materials still work in perfect unison. And, after all, it is just a versatile Vuetify Template, as it has six dashboards, three hundred user interface components, predefined widgets, lots and lots of charts and tables, range sliders and forms and many-many more different things for you to explore and experiment with.

More details

6. Vuse

Simply put, Vuse Vuetify Template is just cool. But, to elaborate, it is not only slick and beautiful to look at. It is also quite versatile, as it includes such features as lazy loading, code splitting, navigation, 27 custom pages, two workable applications and 35 other exceptionally useful widgets. Moreover, Vuse’s documentation is precise and helpful, which is never a bad thing. Summarizing, this Vuetify Template can be best compared to this cool kid on the block from your childhood that does everything perfectly and effortlessly.

Source

7. Bamburgh

If you need to set up your admin panel as quickly as possible – pay your attention to Bamburgh – a full-blown Vuetify template with UI kit. This great entry allows you to forget about the tedious coding and designing process, because all the components in Bamburgh are packed and ready to be deployed at any given moment.

And we, of course, can not talk about such a Vuetify Template, as Bamburgh, without mentioning the great widget it possesses: 

• Six ready-made apps, like chat, contacts, email, event calendars and more;

• A number of page layouts;

• A number of UI elements (badges, avatars, navigation, cards, modals, tooltips and many more at your disposal).

So, as you can see, Bamburgh is not just a fun thing to say out loud, but also a versatile and capable Vuetify Template to fasten the process of admin panel establishment.

More details

8. Zero

If what you look for to improve your business’ web presentation are the slickness and careful craftsmanship – then look no further than Zero, as this multi-purpose, responsive and gorgeous to look at Vuetify Template.

What is also great about Zero, given how slick it actually looks, is the effortlessness with which you can tinker around it, add and remove features you need or don’t want. All of that’s not mentioning more than forty components, ten sample pages, six months’ worth of free updates and pixel-perfect design that are already in the bundle. But wait, there is more, as, despite such a plethora of specialities, Zero will still show the highest numbers when it comes to fast loading speed and searching.

More details

9. Alpha

Talk about irony, as the last Vuetify Template on this list is named after the first letter of the Greek alphabet. But, naturally, being last on our list does not mean that it is the worst one. On the contrary, Alpha is exceptional if what you look for is a beautiful front-end template. We mean, just look at the picture!

But visual pleasantness is not all Alpha can offer. It also has an abundance of useful features, such as sticky headers, filterable portfolio, pricing plans, social media buttons and anything you can imagine your business-oriented project can need. Alpha is an exemplary Vuetify Template that excels at practicing all the latest trends of the modern web market.

More details

Conclusions

And that concludes our dive into the astounding world of Vuetify and Vuetify Templates. What is left to say here is the fact that Vuetify is the tool to use if you want your project to not only succeed in this oversaturated and rough web market of today but also look good while doing it. And Vuetify Templates are there to help you ease this process.

That’s it for today! Have a great day and feel free to read up on more of our articles!

Suggested Articles

Ways to Make an Ecommerce Store on Node.js in 2021 |Guide for Beginners
Top 10 Vue Templates to Choose in 2021 | FrontEnd Matters!
New React Templates in the Family of Flatlogic Dashboards

The post Top 9 Vuetify Templates for Web Developer appeared first on Flatlogic Blog.

GraphQL Mutations in ASP.NET Core

This post is about GraphQL in ASP.NET Core with EF Core. In this post we will explore how to implement mutations using ASP.NET Core. Mutations help you to update the data in the database. Here is the Mutation class. In this class, we are adding the link object to database using Entity Framework Core.

public class Mutation
{
[UseDbContext(typeof(BookmarkDbContext))]
public async Task<LinkOutput> AddLink(LinkInput linkInput,
[ScopedService] BookmarkDbContext bookmarkDbContext)
{
if (string.IsNullOrEmpty(linkInput.Url))
{
throw new ArgumentNullException(nameof(linkInput.Url));
}

var link = new Link
{
Url = linkInput.Url,
Title = linkInput.Title,
Description = linkInput.Description,
ImageUrl = linkInput.ImageUrl,
CreatedOn = DateTime.UtcNow
};
bookmarkDbContext.Links.Add(link);
await bookmarkDbContext.SaveChangesAsync();
return new LinkOutput(true, link.Id, link.Url,
link.Title, link.Description, link.ImageUrl, link.CreatedOn);
}
}

Next, we need to configure the Mutation class to the GraphQL pipeline like this.

builder.Services.AddGraphQLServer()
.AddQueryType<Query>()
.AddProjections()
.AddFiltering()
.AddSorting()
.AddMutationType<Mutation>();

You can use the following code to implement update operation as well.

[UseDbContext(typeof(BookmarkDbContext))]
public async Task<LinkOutput> UpdateLink(int id, LinkInput linkInput,
[ScopedService] BookmarkDbContext bookmarkDbContext)
{
var link = bookmarkDbContext.Links.Find(id);
if (link != null)
{
if (link.Title != linkInput.Title)
{
link.Title = linkInput.Title;
}
if (link.Description != linkInput.Description)
{
link.Description = linkInput.Description;
}
if (link.ImageUrl != linkInput.ImageUrl)
{
link.ImageUrl = linkInput.ImageUrl;
}
if (link.Url != linkInput.Url)
{
link.Url = linkInput.Url;
}

await bookmarkDbContext.SaveChangesAsync();
return new LinkOutput(true, link.Id, link.Url, link.Title,
link.Description, link.ImageUrl, link.CreatedOn);
}

return new LinkOutput(false, null, null, null, null, null, null);
}

And you can get the schema and know about the Mutation operations in GraphQL from Schema Reference.

You can execute the mutation operation like this.

mutation {
addLink(
linkInput: {
url: https://microsoft.com
title: Microsoft – Cloud, Computers, Apps & Gaming
description: Explore Microsoft products and services for your home or business.
}
) {
url
title
description
}
}

Once it execute the operation and then it return the Url, title and description, like this.

If you’re not specifying the return object, GraphQL will show an error like this.

Mutation will help you to alters data, like inserting data into a database or altering data already in a database.

You can find the source code in GitHub

Happy Programming 🙂

Azure Functions – Could not load file or assembly System.Text.Encoding.CodePages

This post is about how to fix the exception Could not load file or assembly System.Text.Encoding.CodePages when you’re using any HTML parser in Azure Functions. Recently while working on Azure Static Web App, I faced an issue like this. I created an Azure Function in Dotnet, which helps to parse HTML from URLs. I was using a nuget package – OpenGraph-Net. And after I deployed the function, it is started throwing this error – Exception while executing function: &lt;Function Name&gt; Could not load file or assembly ‘System.Text.Encoding.CodePages, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’. The system cannot find the file specified. It is working properly on my machine.

Since the Azure Static Web App doesn’t offer console or any other utility to access the Functions directly, all I can do was trying some changes in the source code. After looking into multiple Github issues, I found 3 solutions. I did it one by one and fixed the issue. You may not need all these 3 solutions, but after applying these 3 solutions only it started working for me properly.

First I tried installing the System.Text.Encoding.CodePages package manually using the dotnet add package System.Text.Encoding.CodePages –version 6.0.0 command and I deployed it. But it didn’t worked. Next I tried modifying the project file and added this line – <FunctionsPreservedDependencies Include=”System.Text.Encoding.CodePages.dll” />, again deployed it. Here the modified project file looks like.

<!– omitted for brevity –>
<ItemGroup>
<FunctionsPreservedDependencies Include=“System.Text.Encoding.CodePages.dll” />
</ItemGroup>
<!– omitted for brevity –>

But still it is throwing the same error. And finally I tried one more project file change, I added some element like this – _FunctionsSkipCleanOutput and project file looks like this.

<!– omitted for brevity –>
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
</PropertyGroup>
<!– omitted for brevity –>

Now it started working properly. As I mentioned earlier I am not sure whether we need to do all these configuration changes or the last one is only one required, I didn’t tried removing the others.

Happy Programming 🙂

Turning Off Visual Studio 2022 Intellicode Complete Line Intellisense

A big reason people who develop in .NET languages rave about Visual Studio being the number one IDE, is auto complete and intellisense features. Being able to see what methods/properties are available on a class or scrolling through overloads of a particular method are invaluable. While more lightweight IDE’s like VS Code are blazingly fast.. I usually end up spending a couple of hours setting up extensions to have it function more like Visual Studio anyway!

That being said. When I made the switch to Visual Studio 2022, there was something off but I couldn’t quite put my finger on it. I actually switched a couple of times back to Visual Studio 2019, because I felt more “productive”. I couldn’t quite place it until today.

What I saw was this :

Notice that intellisense has been extended to also predict entire lines, not just the complete of the method/type/class I am currently on. At first this felt amazing but then I started realizing why this was frustrating to use.

The constant flashing of the entire line subconsciously makes me stop and read what it’s suggesting to see if I’ll use it. Maybe this is just something I would get used to but I noticed myself repeatedly losing my flow or train of thought to read the suggestions. Now that may not be that bad until you realize…
The suggestions are often completely non-sensical when working on business software. Take the above suggestion, there is no type called “Category”. So it’s actually suggesting something that should I accept, will actually break anyway.
Even if you don’t accept the suggestions, my brain subconsciously starts typing what they suggest, and therefore end up with broken code regardless.
And all of the above is made even worse because the suggestions completely flip non-stop. In a single line, and even at times following it’s lead, I get suggested no less than 4 different types.

Here’s a gif of what I’m talking about with all 4 of the issues present.

 

Now maybe I’ll get used to the feature but until then, I’m going to turn it all off. So if you are like me and want the same level of intellisense that Visual Studio 2019 had, you need to go :

Tools -> Options -> Intellicode (Not intellisense!)

Then disable the following :

Show completions for whole lines of code
Show completions on new lines

After disabling these, restart Visual Studio and you should be good to go!

Again, this only affects the auto-complete suggestions for complete lines. It doesn’t affect completing the type/method, or showing you a method summary etc.

The post Turning Off Visual Studio 2022 Intellicode Complete Line Intellisense appeared first on .NET Core Tutorials.

Extract a License Plate from an Image #ALPR

ALPR – Or Automatic License Plate Recognition is the process of extracting the textual elements of a License Plate from an image. For example, reading the text FL802FJ from the image shown above.

Here is an API on Rapid API that offers a simple API that reads the license plate from an image of a car when provided via a URL: https://rapidapi.com/appaio/api/license-plate-from-image/

You make a HTTP POST request to the following endpoint:

https://license-plate-from-image.p.rapidapi.com/PlateRecognizerLambda

With the JSON Body;

{“url”:”https://i.ytimg.com/vi/WPXs6vNiSb4/maxresdefault.jpg”}

And the x-rapidapi-key set in the HTTP Headers.

Which results in the following:

{
“processing_time”: 147.311,
“results”: [
{
“box”: {
“xmin”: 896,
“ymin”: 307,
“xmax”: 1067,
“ymax”: 411
},
“plate”: “fl802fj“,
“region”: {
“code”: “fr”,
“score”: 0.621
},
“score”: 0.898,
“candidates”: [
{
“score”: 0.898,
“plate”: “fl802fj”
},
{
“score”: 0.897,
“plate”: “fl8o2fj”
},
{
“score”: 0.777,
“plate”: “flb02fj”
},
{
“score”: 0.775,
“plate”: “flbo2fj”
}
],
“dscore”: 0.729,
“vehicle”: {
“score”: 0.759,
“type”: “Sedan”,
“box”: {
“xmin”: 130,
“ymin”: 3,
“xmax”: 1148,
“ymax”: 690
}
}
}
],
“filename”: “1214_OkT6R_93b5bdbc-09af-47c4-b1a7-14109ed988ae.jpg”,
“version”: 1,
“camera_id”: null,
“timestamp”: “2021-11-25T12:14:00.429055Z”
}

Sending Alerts to Slack

Seq can monitor the event stream and trigger alerts when configured conditions occur. For example, a system produce an alert when an item runs out of stock.

Alerts are useful because they can generate notifications. If I receive a notification that a product is out of stock I can take action, such as ordering more stock. There are many ways to receive alert notifications. One popular notification option is to configure Seq to write a message to a Slack channel when an alert is triggered.

Getting Started

The Seq sample data includes an event type representing when a product runs out of stock in a fictional coffee retailer.

Out of stock event

Before creating an alert it is necessary to have a way to send a notification when the alert triggers.

Configure Slack to receive notifications

For Slack to receive notifications from Seq we firstly create a new Slack app, with the ‘Incoming Webhooks’ feature. Then add a new Webhook, and give the new Slack app permission to post to one of your Slack channels. I configured a Webhook to write to a ‘#stock-alerts’ Slack channel. When your Webhook is configured take a copy of the ‘Webhook URL’ for later.

Configure Slack to receive notifications

Setting up Slack integration in Seq

To integrate Seq and Slack you need to install the ‘Slack Notifier’ Seq app (developed and maintained by David Pfeffer and the Seq community). Go to Settings > Apps > Install from NuGet and install the ‘Seq.App.Slack’ app. Add an instance of the app (mine is called ‘Alert notifications’), setting the ‘Webhook URL’ to the value you copied from the Slack app. Now Seq has a way to write to a Slack channel.

Creating the Alert

Seq alerts are triggered by a query that produces a result. This query will produce a result for each minute in which there is at least one ‘out of stock’ event.

Counting out of stock events, grouped by minute

The chart at the bottom of the window shows that ‘out of stock’ events occur regularly. The inventory controller needs to know!

To make this query into an alert I click the bell button. I’ve named the new alert ‘Out of stock’ and selected the Slack Notifier Seq app instance as the ‘Output app instance’. When the alert triggers it will send the notification to the ‘#stock-alerts’ channel.

Creating an alert that sends events to Slack

Within a few minutes an ‘out of stock’ event has triggered and an ‘out of stock’ alert and a message has been sent to the ‘#stock-alerts’ Seq channel.

Seq alert has arrived in Slack

When a notification appears in Slack I can follow the links back to the alert that generated the notification or to the query the alert is based on. For these links to work you will need to have set the api.canonicalUri Seq server setting.

There is a lot more that can be done with alerts and the Slack Notifier Seq app. Refer to the Seq documentation for more detail.

There are also notification apps for email and Microsoft Teams.

Solving Github Password Authentication 403 Errors

Sorry for an absolute mouthful of a post title. I couldn’t find any better way to describe it! In August 2021, Github removed the support for password authentication with GIT repositories. What that essentially means is that if you were previously using your actual Github username/password combination when using GIT (Both private and public repositories), you’re probably going to see the following error :

remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead. remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information. fatal: unable to access “…” : The requested URL returned error: 403

The above error message links to a post that goes into some detail about why this change has been made. But in short, using access tokens instead of your actual Github password benefits you because :

The token is unique and is not re-used across websites
The token can be generated per device/per use
The token can be revoked at any point in time if leaked, and will only affect those using that specific token instead of the entire Github account
The scope of the token can be limited to only allow certain actions (e.g. Only allow code commit but not edit the user account)
The token itself is random and isn’t subject to things like dictionary attacks

All sounds pretty good right! Now while the error message is surprisingly helpful, it doesn’t actually go into details on how to switch to using personal access tokens. So hopefully this should go some way to helping!

Generating A Personal Access Token On Github

This is the easy part. Simply go to the following URL : https://github.com/settings/tokens, and hit Generate New Token. You’ll be asked which permissions you want to give your new token. The main permissions are going to be around repository actions like so :

The expiration is up to you however a short duration means that you’ll have to run through this process again when the token runs out.

Hitting generate at the bottom of the page will generate your token and show it to you once. You cannot view this token again so be ready to use it! And that’s it, you have your new personal access token! But.. Where to stick it?

Removing Old GIT Passwords

This is the part that took me forever. While I had the new access token, my GIT client of choice (SourceTree) never prompted me to enter it. This is where things go slightly haywire. I’m going to give some hints where to go, and what I did for Sourcetree on Windows, but you’ll need to vary your instructions depending on which client and OS you are using.

The first place to check on Windows is the Credential Manager. Simply type Credential Manager into your start bar, open the Credential Manager, then switch to “Windows Credentials” like so :

You’ll be shown a set of credentials in this list that have been saved. Your GIT credentials may be in this list. If they are, simply delete them, then continue on. If not then we need to delve into how our specific GIT client actually stored passwords.

For Sourcetree that means going to the following folder on Windows : C:Users<username>AppDataLocalAtlassianSourceTree, and finding a file simply titled “passwd”. Open this, find your GIT credentials and delete them.

Again, your mileage is always going to vary on this step. The main point is that you need to find your credential cache for your GIT client, and delete your old credentials. That’s it!

Entering Your Access Token

In your GIT client, simply pull/push your code and you should be prompted to enter your new credentials because, with the last step, we just deleted the stored credentials we had previously.

Simple enter your Github Username with your Personal Access Token in place of your password. That’s it! Your access token essentially functions like your password in terms of what your GIT client thinks it’s doing, so it’s nice and easy!

The post Solving Github Password Authentication 403 Errors appeared first on .NET Core Tutorials.