Posts

Async/await in console app

// PM> Install-Package Nito.AsyncExusing Nito.AsyncEx;class Program {staticvoid 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.

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.staticvoid 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 datareturn image.GetPropertyItem(id);}};using(var image = Image.FromFile(oldFile)){ PropertyItem propItem;int ID =0x9004;try{ propItem = image.GetPropertyItem(ID);}cat…

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":{"ConnectionStringKey":"CS1","QueryText":"some query","Timeout":40},"Q2":{"ConnectionStringKey":&qu…

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>

Console output

class Program {staticvoid 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();}}

Custom config items

<?xmlversion="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 {publicclass AccountsSection : ConfigurationSection {[ConfigurationProperty("", IsRequired =true, IsDefaultCollection =true)]public AccountCollection Instances {get{return(AccountCollection)this[""];}set{this[""]= value;}}[ConfigurationProperty("host", IsRequired =true)]publicstring Host {get{return(string)this["host"];}set{this["host"]= value;}}}publicclass AccountCollection : …

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.