The new C# Record type

Software Development, Web programming
Introduced with C#9 (.Net 5) in November 2020, the new record type adds yet another way of declaring types in C#. By default record acts as reference type, like classes, but since C#10 you can also create a record struct (value type). You can also declare them using record class, but as that’s the default, you can omit the class type when doing so and declare them as just record. Record types are compiler-generated classes/structs with some predefined methods, they can be declared very lightly on coding but will then gain their features when compiled. They all follow the IEquatable interface. IEquatable : this interface ensures that they have value-based equality. This means that when comparing two of them, C# automatically compares their properties and the values inside them to…
Read More

Request local endpoint from one .Net project to another skipping certificates

Software Development, Web programming
Just add this bit of code to the httpClientHandler: // Return `true` to allow certificates that are untrusted/invalid httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; Full code example: var myPostObj = new {prop1 = 1, porp2 = 2}; using (var httpClientHandler = new HttpClientHandler()) { // Return `true` to allow certificates that are untrusted/invalid httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using (var client = new HttpClient(httpClientHandler)) { var reqAsJson = JsonConvert.SerializeObject(myPostObj); var content = new StringContent(reqAsJson, Encoding.UTF8, "application/json"); var response = await client.PostAsync(url, content); return response; } }
Read More

Connecting to localhost using HttpClient in C#

Software Development, Web programming
When getting error message: The SSL connection could not be established, see inner exception. Inner exception: The remote certificate is invalid according to the validation procedure. We need to add a client handler that will simply accept all certificates no matter what. [csharp highlight="6,7"] private static async Task<HttpResponseMessage> Request(object request, string url, string headerKey, string secret) { using (var httpClientHandler = new HttpClientHandler()) { // Return `true` to allow certificates that are untrusted/invalid httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using (var client = new HttpClient(httpClientHandler)) { client.DefaultRequestHeaders.Add(headerKey, secret); var reqJson = JsonConvert.SerializeObject(request); var content = new StringContent(reqJson, Encoding.UTF8, "application/json"); var response = await client.PostAsync(url, content); return response; } } } [/csharp]
Read More

Angular2 sanitation

Web programming
Angular 2 handles sanitation using the DomSanitiser at platform-browser library, though this seems to have changed through versions this is the latest one: [js]import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';[/js] Can be used like this in code: [js] constructor(private sanitizer: DomSanitizer) { this.sanitizer.bypassSecurityTrustResourceUrl("www.example.com"); } [/js] Another way to achieve the same thing, using SecurityContext at angular/core: [js] import { Component, SecurityContext } from '@angular/core'; this.sanitizer.sanitize(SecurityContext.URL, "https://www.example.com"); [/js] Basically you can use sanitize adding the type of value you want to sanitise, or you can use the appropiate method for each type: [js] // Types SecurityContext.URL; SecurityContext.RESOURCE_URL SecurityContext.HTML SecurityContext.SCRIPT SecurityContext.STYLE // Methods this.sanitizer.bypassSecurityTrustUrl("url") this.sanitizer.bypassSecurityTrustResourceUrl("url") this.sanitizer.bypassSecurityTrustHtml("url") this.sanitizer.bypassSecurityTrustScript("url") this.sanitizer.bypassSecurityTrustStyle("url") this.sanitizer.sanitize(SecurityContext.URL, "url"); [/js] Adding URL to iframe There's two ways to bind the url into it: [html] <iframe class="video-iframe" [src]="getVideoUrl()"></iframe> <iframe class="video-iframe" src="{{getVideoUrl()}}"></iframe> [/html]…
Read More

How to theme styles with Angular and SASS

Web design, Web programming
With so many components and pieces of code in an angular application, CSS, cascade styling, may not be so straightforward as styles may be loaded in different orders or affect other components when you less expect it. Though after 15+ years styling websites, I was more than used to organise my styles in a proper way to have everything working nicely. Or maybe I never had such a big website on my hands for this to be an issue. But now that styles are encapsulated in the component when you give it some, while very useful to specify local styling (which still inherits the global) it can become painful to then maintain some sense of cascading, like how to reference a style in the parent to determine your child's one.…
Read More

Google ReCaptcha v2 and Angular

Web programming
Note: This was done for Angular 1, but Angular 2 is the same except the bit at the end of the post. Google ReCaptcha In order to include Google ReCaptcha in your website you need a Google account and get into the "Google ReCaptcha" web page. Once in there create a site and add your domain/s in there, recaptcha generates a key that's only valid for the included domains, and that affects localhost too, so in order to test in localhost you must include that domain in the list. As it would be a bad approach to use production keys to test in localhost domain (anyone could make use of your keys) the best approach is to not include localhost into your production site and create a different one with…
Read More

Some notes on Blazor

Web programming
What is Blazor? It's a new .Net technology that allows to implement web's client side codes using C# and compiling to Web Assembly, a new web standard that all modern browsers implement (it's meant to be faster as it's compiled). It also makes use of the old Razor technology used at MVC views, that's why they've got similar names (Browser+Razor = Blazor). It allows you to create SPAs (Single Page Applications) using .Net technologies only, no javascript. Some notes Blazor is similar to Angular in which it allows you to create your own pieces of code, add them as HTML tags and include two-way data binding between the codes and the view. It seems very similar to Angular1 in how it achieves it and it doesn't seem very flexible on…
Read More

Salesforce Pardot forms

Web programming, Web statistics
What is a Pardot form? Salesforce Pardot forms are a combo between a user tracking script that registers users navigation throughout your website and Form registration like the form-to-lead approach which does the same but without tracking data. What do I need? First of, you need to set the tracking code into your website, which you should be able to find at Salesforce. Then, you also need to set a form in your website to allow the users to register. This can be done in two ways: creating a form and its fields at Salesforce and attaching an iframe to your website with such form or with what's called form-handler: create your own form and "POST" it to Salesforce, which obviously is the way we devs do it ;) How…
Read More

Creating AWS Lambdas with Visual Studio

Web programming
Fair warning AWS Services are in constant change and evolution. Check the date of this post as in the last 18 months there's been new stuff added to those services and I expect more to come in the next 18, so if the post is a bit out of date be careful it may not be accurate. Installing and using the AWS plugin Need to install "AWS Toolkit for Visual Studio 2017 and 2019" plugin into Visual Studio. Then, you should have an "AWS Explorer" tab on the sidebar next to the Solution Explorer and the rest where you can set up your credentials and log into Amazon. That panel will also show you all the lambdas and rest of stuff you already have in Amazon. You can also add…
Read More

Adding an SVG with HTML5

Web programming
Few ways to use an svg in your page: Using the <object> tag Just embed an svg into the page by requesting it as a resource from the server and embedding it into the page as a document. Example <object type="image/svg+xml" data="images/logo.svg" id="logo"></object> Known issueOn being a different document (like using an iframe) your styles won't reach it. That may not be an issue to you but if you are planning to adapt its size or filling colors contextually or reactively then it can be. To sort it out you have different solutions, from accessing the element on runtime with javascript and override its styles directly to attach a link inside the SVG file that loads the required stylesheet file along the doc. Still, contextual styling can be a problem.…
Read More

Parallel threads with C#

Web programming
Example of some code where I decided to take the data from the DB in batches instead than all in one go, which was timing out. This could have been done one after the other, just waiting for the previous one to finish before requesting next batch, but I decided to give it a go and try to get them all at the same time by making separate calls and waiting for them all to finish to build the result in order. Important bits in commented lines. [csharp] using System.Text; using System.Threading.Tasks; public abstract class BaseExporterRepository : BaseDataRepository<DbContext> { private readonly IDbContextFactory _contextFactory; protected readonly int batchSize = 5000; protected virtual string GetHeader() => ""; protected virtual Task<StringBuilder> BuildBatchAsync(DbContext ctx, int skip) => null; protected virtual Task<int> CountAllAsync() => null;…
Read More

Performing Queries with Kibana

Web programming
Queries To get anything in the index: [csharp] GET /_search {"query": {"match_all": {}}} [/csharp] To get a document type inside the index (dragon-dev is the index name): [csharp] GET dragon-dev/organisation/_search {"query": {"match_all": {}}} GET dragon-dev/article/_search {"query": {"match_all": {}}} GET dragon-dev/person/_search {"query": {"match_all": {}}} [/csharp] Search by Guid (two different ways): [csharp] GET dragon-dev/person/_search { "query": { "match": { "id": "8dd0f391-ce67-41e6-bf68-374716a90bfe" } } } GET dragon-dev/associate/_search { "query": { "match": {"associatedWithId": "dbc8814d-9123-47d3-8dac-e31a7de5107e" } } } [/csharp] Sorting [csharp] // Sorting by a numeric or Date field is straight forward GET dragon-dev/organisation/_search { "sort": [{"websiteId": {"order" : "asc"}}], "query": {"match_all": {}} } // But a text field requires to make it a keyword type and search by keyword: GET dragon-dev/organisation/_search { "sort": [{"name.keyword": {"order" : "asc"}}], "query": {"match_all": {}} } [/csharp] Deleting…
Read More

Setting up Neo4j to work with a C#.Net project

Web programming
Just a quick guideline to refresh my mind: Installing Neo4j Server First, go to their website and download and install the latest version. If you are planning to use this installation for dev purposes only, you don't need the enterprise version, the individual works just fine. Installing it should take no time and be quite simple, but once it's done, run the program and click on Start to start the server, then click on the link to browse to it. Unless you edit the config file to set off the authentication it will ask you to login, the default user/pass was something like neo4j/neo4j or neo4j/admin, I can't remember right now. Once that's done it asks to change the default password to a new one, you can set your own…
Read More

Performing queries in .Net with NEST

Web programming
First of all, I created a document model in C# named EsOrganisation with some basic fields: [csharp] [ElasticsearchType(Name = "organisation")] public class EsOrganisation { public Guid Id { get; set; } public DateTimeOffset CreatedDate { get; set; } public DateTimeOffset? UpdatedDate { get; set; } public int OrganisationTypeId { get; set; } public string OrganisationName { get; set; } public List<string> OrganisationAliases { get; set; } public List<string> OrganisationKeywords { get; set; } public List<int> Products { get; set; } } [/csharp] Then I also created a factory to retrieve the Nest.ElasticClient, to simplify just have in mind that when I call to client.SearchAsync() I have already instantiated and prepared it. Structured vs Unstructured Search Structured or Unstructured Search refers as to how are the filters applied, Structured search refers…
Read More

Some tips on C# Generics

Web programming
Defining interfaces You can define that a generic must implement an interface, which in essence allows you to know beforehand that a generic type will have a certain method (making it less generic) [csharp] public interface ISearchable { void Search(); } public class SomeClass<T> where T : ISearchable { public void DoSomething(T entity) { entity.Search(); // Can do this on a generic type because it's implementing ISearchable } } [/csharp] You can also use generics on the interfaces, in this case: [csharp] public interface ISearchable<TEntity> { TEntity Search(); } public class SomeClass<T> where T : ISearchable<T> { public T FindMe(T entity) { return entity.Search(); } } [/csharp] Now when referencing the interface we must set the generic type too. Warning!: If you set a constraint on a generic type any…
Read More