Posts

Showing posts from May, 2021

Dependency injection in ASP.NET

Image
Out of the box, you get dependency injection in ASP.NET, and can inject items into a controller constructor, or a view, with a very simple configuration step. IConfiguration comes free, as does logging. And the framework provides others, like IHttpContextAccessor , which lets you easily access HTTP stuff outside of a controller or view. You get scoped, transient, and singleton items, and automatic disposal for scoped items once a request is completed. Learn more about dependency injection in the docs . View code on GitHub

.NET Configuration

Image
Configuration in .NET Core and later is mostly unstructured, letting you build your configuration JSON file the way you want it. The standard approach tends to be an appsettings.json file. From there, you can define your configuration any way you want - simple key-value pairs, complex objects, arrays, whatever you need. View code on GitHub

C# Events

Image
Events in C# are common in UI applications like WebForms and WinForms. They can also be useful anywhere else, where you have a caller who may want to know when interesting things happen in your code. To expose an event, you just need to define it in the class, and invoke it when something interesting happens. It's generally as easy as: public class Foo { public event EventHandler SomethingHappened ; public void Go ( ) { SomethingHappened? . Invoke ( this , EventArgs . Empty ) ; } } Foo foo = new ( ) ; foo . SomethingHappened + = ( sender , e ) = > Console . WriteLine ( " Something happened... " ) ; View code on GitHub

Basic RSA in .NET

Here’s a very basic example of RSA encryption in .NET: string priv , pub ; string plain = " hello world " ; byte [ ] plainBytes = Encoding . UTF8 . GetBytes ( plain ) ; byte [ ] encBytes ; using ( var rsa = new RSACryptoServiceProvider ( 2048 ) ) { priv = rsa . ToXmlString ( true ) ; Console . WriteLine ( priv ) ; Console . WriteLine ( ) ; pub = rsa . ToXmlString ( false ) ; Console . WriteLine ( pub ) ; encBytes = rsa . Encrypt ( plainBytes , true ) ; } using ( var rsa = new RSACryptoServiceProvider ( 2048 ) ) { rsa . FromXmlString ( priv ) ; byte [ ] decBytes = rsa . Decrypt ( encBytes , true ) ; Console . WriteLine ( Encoding . UTF8 . GetString ( decBytes ) ) ; } And a very basic example of verifying data using a signature: byte [ ] input = new byte [ ] { 1 , 2 , 3 , 4 , 5 , 6 } ; string rsaParams ; byte [ ] sig ; using ( var rsa = new RSACryptoServiceProvider ( ) ) {

SQL Server Date/Time Formatting

Here are my favorite date formats in SQL Server. These work with older versions, in case you’re not able to use the new format feature: declare @theDate datetime = getdate ( ) ; select -- yyyy-MM-dd convert ( char ( 10 ) , @theDate , 126 ) -- MM/dd/yyyy , convert ( char ( 10 ) , @theDate , 101 ) -- yyyy-MM-dd HH:mm:ss , convert ( char ( 19 ) , @theDate , 120 ) -- yyyy-MM-dd HH:mm:ss.fff , convert ( char ( 23 ) , @theDate , 121 ) -- yyyy-MM-ddTHH:mm:ss.fff (ISO8601) , convert ( char ( 23 ) , @theDate , 126 ) -- MMM _d yyyy _h:mm:ss.fff --(if day/hour < 10, space is inserted so len is always 26) , convert ( char ( 26 ) , @theDate , 109 )

Move junk to inbox in outlook.com

Image
Recently I switched over to Microsoft 365 with Outlook.com, using my custom domain and email address. The process is overly complex, requiring GoDaddy to run the domain, and overall the tools are not fantastic. But the thing that really got me was the junk filter is atrocious. Messages go to junk, even after whitelisting them. I have the junk settings to allow everything, and still, even messages from contacts and safe senders still end up in junk. I was thinking about digging up some VBA tutorials, or whatever the language of choice for Office is now. But I found that Microsoft Flow has the ability to do what I needed. I set up a rule to just move all junk mail back to the inbox. Of course, this means I get spam in the inbox. But with some rules on keywords, and some patience, I can catch those and auto-delete those messages. The flow is really straightforward:

Handlebars

Handlebars is a fantastic templating engine which is available for .NET. It’s similar to Mustache, which I tend to prefer, but Handlebars has more features that can be very useful. This is a basic example showing how easy it is to apply a template. // <package id="Handlebars.Net" version="1.7.1" targetFramework="net40" />   // {{{ triple-stash to avoid encoding }}}   using System; using HandlebarsDotNet;   class Program {     static void Main(string[] args) {         string source =  @" {{title}} Hello {{person.name}}, I see that you are {{person.age}} years old. You have the following cars: {{#each cars}}     {{year}} {{make}} {{model}} {{#if color}}(Color={{color}}){{/if}} {{/each}} ";           var template = Handlebars.Compile(source);           var data = new {             title = "My Data Object",             person = new { name = "Billy", age = 34 },             cars = new object[] {                 new { year

GZip in .NET

public class Gzip { public static void Compress ( Stream inputStream , Stream outputStream ) { using ( var gzip = new GZipStream ( outputStream , CompressionMode . Compress ) ) { byte [ ] buffer = new byte [ 8192 ] ; int count ; while ( ( count = inputStream . Read ( buffer , 0 , buffer . Length ) ) > 0 ) { gzip . Write ( buffer , 0 , count ) ; } } } public static void Decompress ( Stream inputStream , Stream outputStream ) { using ( var gzip = new GZipStream ( inputStream , CompressionMode . Decompress ) ) { byte [ ] buffer = new byte [ 8192 ] ; int count ; while ( ( count = gzip . Read ( buffer , 0 , buffer . Length ) ) > 0 ) { outputStream . Write ( buffer , 0 , count ) ; } } } }

Get EXIF date from photo

It’s not straightforward to retrieve the EXIF date from an image. Here’s a method to retrieve it using the MetadataExtractor package. It looks for the appropriate date, and if not found, falls back to the file properties. // <package id="MetadataExtractor" version="2.0.0" targetFramework="net40" /> static DateTime GetImageDate ( string file ) { var directories = ImageMetadataReader . ReadMetadata ( file ) ; ExifSubIfdDirectory subIfdDirectory = null ; try { subIfdDirectory = directories . OfType < ExifSubIfdDirectory > ( ) . FirstOrDefault ( ) ; } catch ( Exception ex ) { } DateTime? dateTime ; try { dateTime = subIfdDirectory? . GetDateTime ( ExifDirectoryBase . TagDateTime ) ; return dateTime . Value ; } catch ( Exception ex ) { try { dateTime = subIfdDirectory? . GetDateTime ( ExifDirectoryBase . TagDateTimeOriginal ) ;

Force IE in Edge Mode

If you’re seeing Internet Exploder loading your site in an old compatibility mode, try adding the following to your web.config file: < system.webServer > < httpProtocol > < customHeaders > < add name = " X-UA-Compatible " value = " IE=Edge " /> </ customHeaders > </ httpProtocol > </ system.webServer > It may or may not work – I haven’t had the time or patience to learn all the various scenarios that screw up Internet Exploder, but this works in at least some scenarios.

Fluent XML writer

Writing XML in .NET is not too terrible, but it sometimes is a bit tricky and lengthy. A few years ago, I put this library together to write XML easily, using fluent techniques. static void Main ( string [ ] args ) { FluentXmlWriter . Start ( " root " ) . Simple ( " First " ) . Simple ( " Second " ) . Attr ( " a " , " b " ) . Complex ( " Arr " ) . ManySimple ( SimpleElement . Create ( " Arr1 " ) . Attr ( " key1 " , " val1 " ) , SimpleElement . Create ( " Arr2 " ) . Attr ( " key2 " , " val2 " ) ) . EndElem ( ) . Complex ( " Third " ) . Text ( " My Text " ) . EndElem ( ) . Complex ( " Fourth " ) . CData ( " Hello there! " ) . EndElem ( ) . Comment ( " A comment! " ) . OutputToString ( Con

Super cheap Azure SQL Database

Image
If you're looking for a super simple, super cheap SQL Server database, for basic development or for a very lightly used production application, Azure offers their "Basic" instance for about $5 per month. It's extremely limited, but if you're looking to spare every dime, it'll function. Developing .NET on a Mac or a cloud IDE means you don't have access to a local SQL Server instance. This kind of thing may suit your needs. And if it doesn't, you're only out a tiny amount of money.

Disposable pattern

public class Something : IDisposable { #region Disposable private bool _disposed ; void IDisposable . Dispose ( ) { Dispose ( true ) ; GC . SuppressFinalize ( this ) ; } protected void Dispose ( bool disposing ) { if ( ! _disposed ) { if ( disposing ) { DisposeManagedResources ( ) ; } DisposeUnmanagedResources ( ) ; _disposed = true ; } } protected virtual void DisposeManagedResources ( ) { } protected virtual void DisposeUnmanagedResources ( ) { } ~Something ( ) { Dispose ( false ) ; } #endregion }

ASP.NET Embedded Resource

You can compile binary or text files into the application assembly – here’s the basic idea. Add the file to the project in Visual Studio, and in the Properties, mark it as “Embedded Resource”. The name of the resource is the default namespace for the project + relative namespace (folder structure) + filename. This is not the same as a resx file. In the code, you can grab the file contents as follows: var stream = Assembly . GetExecutingAssembly ( ) . GetManifestResourceStream ( " WebApplication2.Resources.SomeExcelFile.xlsx " ) ) ; // Do whatever you want to with this stream // copy to byte[], write to output, etc.

Custom config items

<? xml version = " 1.0 " encoding = " utf-8 " ?> < configuration > < configSections > < section name = " accounts " type = " MyApp.Config.AccountsSection, MyApp " /> </ configSections > < appSettings > </ appSettings > < accounts host = " myhost " > < add user = " abc " password = " def " /> < add user = " 123 " password = " 456 " /> </ accounts > </ configuration > using System . Collections . Generic ; using System . Configuration ; using System . Linq ; namespace MyApp . Config { public class AccountsSection : ConfigurationSection { [ ConfigurationProperty ( " " , IsRequired = true , IsDefaultCollection = true ) ] public AccountCollection Instances { get { return ( AccountCollection ) this [

Console output

class Program { static void Main ( ) { var process = new Process { StartInfo = new ProcessStartInfo { CreateNoWindow = true , RedirectStandardOutput = true , RedirectStandardInput = true , UseShellExecute = false , FileName = @" C:\temp\Hello.exe " , Arguments = " world " } , EnableRaisingEvents = true } ; process . OutputDataReceived + = ( sender , e ) = > { Debug . WriteLine ( e . Data ) ; } ; process . Start ( ) ; process . BeginOutputReadLine ( ) ; process . WaitForExit ( ) ; process . CancelOutputRead ( ) ; } }

Config for SMTP

< system.net > < mailSettings > < smtp deliveryMethod = " Network " > < network host = " smtp.something.something " defaultCredentials = " false " enableSsl = " true " password = " 1122334455 " port = " 587 " userName = " postmaster@example.com " /> </ smtp > </ mailSettings > </ system.net >

Configuration in .NET Core

Here’s some basic examples for reading from a configuration file: 1) Create an appsettings.json file in your project. 2) Add this to your csproj file, so that it gets to your output directory: < ItemGroup > < None Update = " appsettings.json " > < CopyToOutputDirectory > Always </ CopyToOutputDirectory > </ None > </ ItemGroup > 3) Install the appropriate NuGet packages: dotnet add package Microsoft.Extensions.Configuration.Json dotnet add package Microsoft.Extensions.Configuration.Binder 4) Add data to your appsettings file, either as simple key-value pairs, or nest them: { " ApplicationName " : " Some Application " , " ConnectionStrings " : { " CS1 " : " some-connection-string " , " CS2 " : " some-other-connection-string " } , " Queries " : { " Q1 " : { "

Add EXIF date to photo

If you have a photo that you need to add a timestamp to the EXIF information, you can use the following .NET code. Apparently there are a ridiculous number of formats and standards which are incompatible with each other and conflicting, but from what I’ve found, this should cover regular use cases. I’m sure there’s a better solution, but this requires that you have some unrelated image file that has the appropriate tags in it, in case your photo is missing the properties entirely. Not exactly a great solution, but it does seem to work. static void Go ( string oldFile , string newFile ) { DateTime theDate = new DateTime ( 2009 , 1 , 15 ) ; Func < int , PropertyItem > getPropItem = id = > { using ( var image = Image . FromFile ( @" c:\temp\IMG_6139.jpg " ) ) { // Some unrelated image file that already has EXIF data return image . GetPropertyItem ( id ) ; } } ; using ( var image = Image . From

AWS Cloud9 IDE

Image
AWS Cloud9 IDE is incredibly easy to set up, and is an affordable way to do some work outside of our normal development machine. If you have an AWS account already set up, building a Cloud9 machine just takes about 1 minute, and is immediately available for use. When you're done, the EC2 instance will power down after a short time, meaning you're only charged for the EC2 time, plus the storage space for the persistant disk. This may be significantly less than you'd pay with other subscription cloud IDEs, depending on your situation. Out of the box you get a bunch of languages/frameworks ready to use, but if you're looking for something like .NET, you have to install it , but that's no problem since you have full access to the underlying machine.

Local Storage in the browser

Image
Local storage lets you store things indefinitely in the user's browser, specific to your site. This can be used for all kinds of things, like caching dropdown values, storing user information, keeping client-side shopping carts, whatever else you can think of. It's a simple store, just string-value pairs, so if this doesn't suit your needs, check out the much more powerful and more complex IndexedDB . View code on GitHub

Async/await in console app

// PM> Install-Package Nito.AsyncEx using Nito . AsyncEx ; class Program { static void Main ( string [ ] args ) { AsyncContext . Run ( ( ) = > MainAsync ( args ) ) ; } static async void MainAsync ( string [ ] args ) { // await Something... } } This was an answer on StackOverflow by async/await superstar and blogger Stephen Cleary , who wrote the referenced NuGet package.