Lynn Demarest's Blog, page 2

March 17, 2020

Protected: Team Foundation Server

This content is password protected. To view it please enter your password below:


Password:

 •  0 comments  •  flag
Share on Twitter
Published on March 17, 2020 19:49

January 30, 2020

Warning! In C#, X + 1 does Not Necessarily Equal X + 1

In C#, when you add 1 to the largest value an Int32 can hold, you don’t get an error, you get a wrong answer.

Below, we set max to the largest Int32 value possible. You can see that’s 2,147,483,647, or about 2 billion. But when we add 1 to max we get – 2,147,483,648 — the MinValue for an int! This is what’s known as overflowing. (If we’d added 2, we’d wind up at the MinValue + 1.)





MaxValue + 1 = MinValue!



Fortunately, you can configure your Visual Studio project to catch overflow errors. Right click on your project name and type alt-Enter to bring up the project properties pages. Select the Build tab and scroll down to the bottom right and click the Advanced button. This dialog should open:









Check the “Check for arithmetic overflow/underflow” box. When you run the program again, the overflow exception is caught, and you don’t get a big negative number when you expected a big positive one.









If you want to be more explicit in your code, you can use the checked and unchecked keywords, which will take precedence over whatever’s in the Build settings.





checked
{
var max = int.MaxValue;
max++; // An exception will be thrown because of the "checked" block
}
unchecked
{
var max = int.MaxValue;
max++; // No exception will be thrown because of the "checked" block
}



You may want to use a checked wrapper only in cases where you fear an overflow and let the rest of the application remain unchecked. After all, checking is expensive, which is why the setting in Build is off by default.

 •  0 comments  •  flag
Share on Twitter
Published on January 30, 2020 18:25

January 26, 2020

Using .Net Core User Secrets to Hold Confidential Data

When programming most applications, there are some configuration items you’d rather not share with the world, for example when you push the repository to github. For example, a secret APIKey needed to access an API, or a database connection string containing a username and password.





.Net Core gleans configuration settings from a variety of sources. There’s the appsettings.json file, the environment, the command line, and something called User Secrets.

Visual Studio creates User Secrets automatically when you right-click on the project and select Manage User Secrets. This will open a secrets.json file you can edit just like appsettings.json.





One cool thing about using User Secrets is that you can add setting in appsettings.json to let the github user know what settings are required, and your User Secrets settings will override them. So you might have this in appsettings.json:





// These two settings should be overridden by settings in User Secrets.
"APIKey": "[YOUR API KEY HERE]",
"ConnectionStrings": {
"ProjectsDBConnectionString": "Server=[YOUR SQL SERVER NAME];Database=[YOUR DB NAME];Trusted_Connection=true;"
}



Here’s a good video on the IConfiguration class.

 •  0 comments  •  flag
Share on Twitter
Published on January 26, 2020 17:23

Generic Class makes .NET Core HttpClient Calls (New!)

Note: This is an enhancement of the static HTTPClientHelper class introduced here.





Here’s a new and improved class that abstracts HttpClient calls. You add the class to your dependency injection container and then just inject it normally in classes that need it. The class is generic, so any type can be used.





Adding IHttpClientHelper to the DI container is a little tricky because the constructor not only expects IHttpClientFactory to be pulled from the DI container, but also the name of the factory connection, ProjectsAPI, in the example below.





// HttpClientFactory
services.AddHttpClient("ProjectsAPI", client =>
{
client.BaseAddress = new Uri(Configuration["ProjectsAPIServer"]);
client.DefaultRequestHeaders.Add("APIKey", Configuration["APIKey"]);
client.DefaultRequestHeaders.Add("X-Version", Configuration["X-VERSION"]);
});

// HttpClientFactory will take care of connection caching, ProjectsAPI is the name
// of the factory, just above.
services.AddSingleton(s =>
new HTTPClientHelper(s.GetService(), "ProjectsAPI")
);



Note: APIKey is just a simple secret string used to authenticate users of the API. X-Version is the API version being requested.

To use the class, inject it into your class normally.





public class ProjectRepository : IProjectRepository
{
private readonly IHTTPClientHelper httpClientHelper;
public ProjectRepository(IHTTPClientHelper httpClientHelper)
{
this.httpClientHelper = httpClientHelper;
}
...



Then just use it. Note that Project below can be any type you expect returned. It might be IEnumerable if you expect a list of projects returned. This is possible because the class is generic.





public async Task GetProjectAsync(int id)
{
Project project = null;
string url = $"api/projects/" + id.ToString();
project = await httpClientHelper.GetAsync(url);
return project;
}



Here’s the entire HTTPClientHelper class. If you want to use the IHTTPClientHelper interface to abstract the injection, just use Visual Studio to extract it.





using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace ITProjects.Models
{
// HTTPClientHelper class
//
// Extract the interface and inject it into startup.cs:
//
// services.AddSingleton();
//
// Because this class is dependent on HttpClientFactory, you also have to include
// it in the DI container:
//
// services.AddHttpClient("ProjectsAPI", client =>
// {
// client.BaseAddress = new Uri(Configuration["ProjectsAPIServer"]);
// client.DefaultRequestHeaders.Add("APIKey", Configuration["APIKey"]);
// client.DefaultRequestHeaders.Add("X-Version", Configuration["X-VERSION"]);
// });
//
// APIKey is a secret key we send to authenticate ourselves, perhaps a GUID.
// X-Version contains the version of the API we want to access, i.e., 1.0
// BaseAddress is the URL of the server, i.e., https://localhost:5001
//
public class HTTPClientHelper : IHTTPClientHelper
{
IHttpClientFactory httpClientFactory;
HttpClient client;
String ClientName;

public HTTPClientHelper(IHttpClientFactory httpClientFactory, string ClientName)
{
this.httpClientFactory = httpClientFactory;
this.ClientName = ClientName;
}

#region Generic, Async, static HTTP functions for GET, POST, PUT, and DELETE

public async Task GetAsync(string url)
{
T data;
client = httpClientFactory.CreateClient(ClientName);
try
{
using (HttpResponseMessage response = await client.GetAsync(url))
using (HttpContent content = response.Content)
{
string d = await content.ReadAsStringAsync();
if (d != null)
{
data = JsonConvert.DeserializeObject(d);
return (T)data;
}
}
}
catch (Exception ex)
{
throw;
}
Object o = new Object();
return (T)o;
}

public async Task PostAsync(string url, HttpContent contentPost)
{
T data;
client = httpClientFactory.CreateClient(ClientName);
using (HttpResponseMessage response = await client.PostAsync(url, contentPost))
using (HttpContent content = response.Content)
{
string d = await content.ReadAsStringAsync();
if (d != null)
{
data = JsonConvert.DeserializeObject(d);
return (T)data;
}
}
Object o = new Object();
return (T)o;
}

public async Task PutAsync(string url, HttpContent contentPut)
{
T data;
client = httpClientFactory.CreateClient(ClientName);

using (HttpResponseMessage response = await client.PutAsync(url, contentPut))
using (HttpContent content = response.Content)
{
string d = await content.ReadAsStringAsync();
if (d != null)
{
data = JsonConvert.DeserializeObject(d);
return (T)data;
}
}
Object o = new Object();
return (T)o;
}

public async Task DeleteAsync(string url)
{
T newT;
client = httpClientFactory.CreateClient(ClientName);

using (HttpResponseMessage response = await client.DeleteAsync(url))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
newT = JsonConvert.DeserializeObject(data);
return newT;
}
}
Object o = new Object();
return (T)o;
}
#endregion
}
}
 •  0 comments  •  flag
Share on Twitter
Published on January 26, 2020 11:11

January 19, 2020

Using Swagger to Document your API in .Net Core 3.1

Swagger, a service you can inject into the middleware pipeline, automatically creates web pages that document your API and allow you to exercise its public elements.





To add it to your API, do the following:





1. Download and Install the Swagger Library



To do this, open the Package Manager Console in Visual Studio (with your API project loaded) and execute :





Install-Package Swashbuckle.AspNetCore -Version 5.0.0



2. Add the SwaggerDoc Service to the DI Container



Add the following code to your DI container in Startup.cs’s ConfigureServices.





services.AddSwaggerGen(x =>
{
x.SwaggerDoc("v1", new OpenApiInfo { Title = "IT Projects API", Version = "v1" });
});



OpenApiInfo is in Microsoft.OpenApi.Models so add a using expression to the top of Start.cs.





using Microsoft.OpenApi.Models;



3. Add Swagger to the Middleware Pipeline



app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});



Note that “My API V1” will appear in the SwaggerUI web page.









4. Run Your API and Test the Swagger.json File



Swagger works by creating a JSON file that SwaggerUI uses to display information about your API. SwaggerUI creates this JSON file, swagger.json, by invoking





http://localhost:/swagger/v1/swagger....



This should return a screenful of JSON data that describes your API. Of course replace with the port your API is using.





5. Display the Swagger UI



Finally, to display the Swagger web interface, invoke:





http://localhost:/swagger



Here’s a recent post that explains the above process in more detail: https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio

 •  0 comments  •  flag
Share on Twitter
Published on January 19, 2020 19:32

Securing a REST API with a Secret and an Action Filter

A simple way to secure a private REST API is to insist that all incoming requests include a secret key in the HTTP header. This is surprisingly easy to do using a .Net Core Action Filter.





Action filters are classes that override one or more virtual methods found in the variety of abstract classes from which they may inherit. For example, if the APIKeyAuthAttribute filter, below, is associated with a controller action (typically by using an attribute), the overridden method OnActionExecutionAsync is inserted into the execution pipeline just before the controller action is invoked.





Much like services placed into the main middleware pipeline, OnActionExecutionAsync does some work and then awaits the next delegate, given by parameter ActionExecutionDelegate next. The next delegate, which is the controller method itself, releases control back to OnActionExecutionAsync after it’s done. The method may then do some processing on the outgoing execution pipeline, if needed.





As previously stated, the APIKeyAuthAttribute filter class (below) creates a ServiceFilter filter that rejects any request that does not contain a secret key in the HTTP header. The HTTP header is contained in the ActionExecutingContext parameter. (See: HttpContext.Request.Headers)





To apply the filter to an action method, you simply decorate the method with an attribute referencing the filter. Decorating a controller class with the attribute is merely shorthand for decorating each of the actions separately.





The filter gets the expected value of the secret key by reading it from the configuration, so we need access to the IConfiguration service.





Notice that the dependency injection of the configuration service used to be done “manually.” Line 31, now commented out, uses context.HttpContext.RequestServices to gain access to the dependency injection container, from which it requests the IConfiguration object registered there.





A better alternative, and the one included in the example, is to use a ServiceFilter. Using ServiceFilter allows you to inject dependencies directly into the filter’s constructor, which is the standard way to do it.





When creating a ServiceFilter attribute, you give the type of the desired attribute filter, like this:





[ServiceFilter(typeof(APIKeyAuthAttribute))]



Then you can use regular .Net Core dependency injection in the filter’s constructor:





public IConfiguration configuration { get; }

public APIKeyAuthAttribute(IConfiguration _config)
{
configuration = _config ?? throw new ArgumentNullException(nameof(_config));
}



Note that when you use a ServiceFilter you have to include your filter class in the dependency injection container in Startup.cs, like this:





services.AddScoped();



By the way, if you try to inject IConfiguration into the constructor of APIKeyAuthAttribute without changing the attribute syntax to ServiceFilter and adding the filter class to the DI container, you get an error because the old [APIKeyAuth] attribute, sufficient if you don’t need dependency injection, doesn’t include the filter class type like the ServiceFilter one does.





Note: Line 10 below contains an attribute that indicates the APIKeyAuth attribute can be placed on classes or methods.





using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace ProjectsAPI.Filters
{

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class APIKeyAuthAttribute : ActionFilterAttribute
{
private const string APIKeyName = "APIKey"; // the name of the Http header field
public IConfiguration configuration { get; }
public APIKeyAuthAttribute(IConfiguration _config)
{
configuration = _config ?? throw new ArgumentNullException(nameof(_config));
}

public override async Task OnActionExecutionAsync(ActionExecutingContext context,
ActionExecutionDelegate next)
{
if (!context.HttpContext.Request.Headers.TryGetValue(APIKeyName,
out var potentialKey))
{
context.Result = new UnauthorizedResult();
return;
}

// The old way: RequestServices gives access to the dependency injection container.
// var configuration = context.HttpContext.RequestServices.GetRequiredService();

// The new way: ServiceFilter allows us to inject the configuration
// into this class's constructor
var apikey = configuration.GetValue(APIKeyName);
if (!apikey.Equals(potentialKey))
{
context.Result = new UnauthorizedResult();
return;
}

await next();

// Executed on the way back out of the pipeline.
// We don't need to do anything here.
}
}
}




Here’s more on filters in .Net Core





https://www.devtrends.co.uk/blog/dependency-injection-in-action-filters-in-asp.net-core

 •  0 comments  •  flag
Share on Twitter
Published on January 19, 2020 17:58

January 17, 2020

Generic Class makes .NET Core HttpClient Calls

Note: This class has been updated.





Here’s a generic class that abstracts async HttpClient calls in .NET Core. It can be used, for example, to make calls from a desktop application or web site back end to a data API.





POST, PUT, DELETE and GET are implemented. Because it’s generic, any data type can be involved. Also, the class is static, so there’s no need to instantiate it. For example, to read a single Application object from a data API endpoint url:





Application application = await HTTPClientHelper.GetAsync(url, MySecretKey);



The url, of course, is the data API endpoint. MySecretKey is placed in an HTTP Header field named APIKey. This is required by my particular API for security. All users of the API must send this key.





This is simpler than JSON Web Tokens (JWT). It uses only a single secret key that every client must know. Users log in to a web application using vanilla Identity. The web application knows the secret key, so it can access data from the API.





using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace ITProjects.Models
{
public static class HTTPClientHelper
{
#region Abstract, Async, static HTTP functions for GET, POST, PUT, DELETE
public static async Task GetAsync(string url, string APIKey)
{
T data;

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("APIKey", APIKey);
using (HttpResponseMessage response = await client.GetAsync(url))
using (HttpContent content = response.Content)
{
string d = await content.ReadAsStringAsync();
if (d != null)
{
data = JsonConvert.DeserializeObject(d);
return (T)data;
}
}
}

Object o = new Object();
return (T)o;
}

public static async Task PostAsync(string url,
HttpContent contentPost,
string APIKey)
{
T data;

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("APIKey", APIKey);
using (HttpResponseMessage response = await client.PostAsync(url,
contentPost))
using (HttpContent content = response.Content)
{
string d = await content.ReadAsStringAsync();
if (d != null)
{
data = JsonConvert.DeserializeObject(d);
return (T)data;
}
}
}
Object o = new Object();
return (T)o;
}

public static async Task PutAsync(string url,
HttpContent contentPut,
string APIKey)
{
T data;

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("APIKey", APIKey);
using (HttpResponseMessage response = await client.PutAsync(url,
contentPut))
using (HttpContent content = response.Content)
{
string d = await content.ReadAsStringAsync();
if (d != null)
{
data = JsonConvert.DeserializeObject(d);
return (T)data;
}
}
}
Object o = new Object();
return (T)o;
}

public static async Task DeleteAsync(string url, string APIKey)
{
T newT;

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("APIKey", APIKey);

using (HttpResponseMessage response = await client.DeleteAsync(url))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
newT = JsonConvert.DeserializeObject(data);
return newT;
}
}
}
Object o = new Object();
return (T)o;
}

#endregion

}
}
 •  0 comments  •  flag
Share on Twitter
Published on January 17, 2020 19:49

Abstract Class to make .NET Core HttpClient Calls

Here’s a class that abstracts async HttpClient calls in .NET Core. It can be used, for example, to make calls from a desktop application or web site back end to a data API.





POST, PUT, DELETE and GET are implemented. Because it’s abstract, any data type can be involved. Also, the class is static, so there’s no need to instantiate it. For example, to read a single Application object from a data API endpoint url:





Application application = await HTTPClientHelper.GetAsync(url, MySecretKey);



The url, of course, is the data API endpoint. MySecretKey is placed in an HTTP Header field named APIKey. This is required by my particular API for security. All users of the API must send this key.





This is simpler than JSON Web Tokens (JWT). It uses only a single secret key that every client must know. Users log in to a web application using vanilla Identity. The web application knows the secret key, so it can access data from the API.





using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace ITProjects.Models
{
public static class HTTPClientHelper
{
#region Abstract, Async, static HTTP functions for GET, POST, PUT, DELETE
public static async Task GetAsync(string url, string APIKey)
{
T data;

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("APIKey", APIKey);
using (HttpResponseMessage response = await client.GetAsync(url))
using (HttpContent content = response.Content)
{
string d = await content.ReadAsStringAsync();
if (d != null)
{
data = JsonConvert.DeserializeObject(d);
return (T)data;
}
}
}

Object o = new Object();
return (T)o;
}

public static async Task PostAsync(string url,
HttpContent contentPost,
string APIKey)
{
T data;

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("APIKey", APIKey);
using (HttpResponseMessage response = await client.PostAsync(url,
contentPost))
using (HttpContent content = response.Content)
{
string d = await content.ReadAsStringAsync();
if (d != null)
{
data = JsonConvert.DeserializeObject(d);
return (T)data;
}
}
}
Object o = new Object();
return (T)o;
}

public static async Task PutAsync(string url,
HttpContent contentPut,
string APIKey)
{
T data;

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("APIKey", APIKey);
using (HttpResponseMessage response = await client.PutAsync(url,
contentPut))
using (HttpContent content = response.Content)
{
string d = await content.ReadAsStringAsync();
if (d != null)
{
data = JsonConvert.DeserializeObject(d);
return (T)data;
}
}
}
Object o = new Object();
return (T)o;
}

public static async Task DeleteAsync(string url, string APIKey)
{
T newT;

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("APIKey", APIKey);

using (HttpResponseMessage response = await client.DeleteAsync(url))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
newT = JsonConvert.DeserializeObject(data);
return newT;
}
}
}
Object o = new Object();
return (T)o;
}

#endregion

}
}
 •  0 comments  •  flag
Share on Twitter
Published on January 17, 2020 19:49

How to Reference Class Properties with Strings Using ASP.NET Reflection

I often want to get (and less frequently set) the value of a class property using a string containing the property name rather than a standard dot reference. 





So instead of this: 





// the normal way
string Name = customer.Name




I want to be able to do this: 





// makes the class property look like a dictionary item
string Name = customer["Name"];




Or 





string ColumnName = "Name";
string Name = customer[ColumnName];




(Javascript aficionados will recognize this dual personality immediately, as it’s a natural behavior for javascript objects.)





You can add this dictionary-like capability to any class by adding the following indexer property. No changes are needed.





If you prefer, you can create a small class containing only the indexer property and then have other classes inherit it. That’s what I do in the example at https://dotnetfiddle.net/2klk3x. (See the IndexerProperty class.)





public object this[string propertyName]
{
get { return this.GetType().GetProperty(propertyName).GetValue(this); }
set { this.GetType().GetProperty(propertyName).SetValue(this, value); }
}




The dictionary syntax is especially helpful when using LINQ. Below is a small function that takes a list of customers and sorts it by SortColumn, a string holding the name of the column.





private List SortCustomers( customers, string SortColumn)
{
return customers.OrderBy(cust =>cust[SortColumn]).ToList();
}




WARNING: As usual when using reflection, don’t do it when speed is important. 





-30-

 •  0 comments  •  flag
Share on Twitter
Published on January 17, 2020 15:25

How to Reference Class Properties with ASP.NET Reflection

I often want to get (and less frequently set) the value of a class property using a string containing the property name rather than a standard dot reference. 





So instead of this: 






// the normal way
string Name = customer.Name




I want to be able to do this: 






// makes the class property look like a dictionary item
string Name = customer["Name"];




Or 






string ColumnName = "Name";
string Name = customer[ColumnName];




You can add this dictionary-like capability to any class by adding the following indexer property. No changes are needed.





If you prefer, you can create a small class containing only the indexer property and then have other classes inherit it. That’s what I do in the example at https://dotnetfiddle.net/2klk3x. (See the IndexerProperty class.)






public object this[string propertyName]
{
get { return this.GetType().GetProperty(propertyName).GetValue(this); }
set { this.GetType().GetProperty(propertyName).SetValue(this, value); }
}




The dictionary syntax is especially helpful when using LINQ. Below is a small function that takes a list of customers and sorts it by SortColumn, a string holding the name of the column.






private List SortCustomers( customers, string SortColumn)
{
return customers.OrderBy(cust =>cust[SortColumn]).ToList();
}




WARNING: As usual when using reflection, don’t do it when speed is important. 





-30-

 •  0 comments  •  flag
Share on Twitter
Published on January 17, 2020 15:25