Category Archives: .NET

fuslogvw, how could I forget you?

This is one of those reminder’s to myself…

Don’t forget that you can use fuslogvw to find problems loading assemblies.

Why do I need reminding?

I had an issue whereby a release build of an application I was working on had been configured for live/prod for the first time and somebody went to test the application which simply failed at start-up – just displaying a Windows dialog asking whether I wanted to close or debug the application.

Ofcourse, the application worked perfectly on my machine and oddly the non-prod versions also worked fine on the other user’s machine. However the live/prod release had one change to the previous build. A new feature had been removed which wasn’t ready to go live and unbeknown to me, the removal of it’s project caused the build to deploy older versions of a couple of DLL’s as part of the new live/prod build.

On my machine this wasn’t an issue as .NET located the newer versions of the DLL’s, on the other user’s machines these could not be located.

This is fine, it was all part of pre-release testing cycle but a little confusing as all the non-prod configurations worked fine on other user’s machines.

When do we get to fuslogvw?

I haven’t had the need to use fuslogvw for ages, but really should probably use it a lot more. To be honest, it makes sense to have it on all the time to catch such potential issues.

What fuslogvw can do is list any failures during start-up of a .NET application. Running fuxlogvw.exe from the Windows SDK folder (for example C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.1 Tools) will result in the fuslog UI being displayed. As you might have guessed from the name the fus-log-vw is a viewer for the fusion log files.

Note: You must run fuslogvw as Admin if you want to change the settings, i.e. set the path of the log files, change the level of loggin, i.e. I just wanted to log all the bind failures, etc.

Leave fuslogvw open and then run the .NET application you’re wanting to take a look at. Now you’ll need to press the Refresh button on fuslogvw to see the logs after the application has started and depending on what you are logging you may see either a list of assemblies that were loaded (for example when just logging everything) or see failures etc.

We can now see what assembly and what version of that assembly the application (we’re monitoring) tried to load and we can inspect the log itself for more information on the failure (via the log file or the fuslogvw).

It’s as simple as that.

Where to store your application data?

Actually I don’t intend to answer the question “Where to store your application data?” because this will depend on your requirements, but what this post will look at is, some of the options available and hopefully help shed light on what best suits your application.

Application data can be separated into two types, user specific data and application specific data (or if you prefer “All User” data).

Obviously multiple user’s might have access to a single machine but an application may be available to all users of a machine, hence we need a way to store settings specific to each user on the machine, for example user preferences. However we also may have application specific data, maybe the application stores a list of URL’s specific, in essence global settings.

Let’s look at some of our options for storing data…

Within your application’s folder

Obviously we could simply store configuration data etc. along with the application, one way to locate this folder is, as follows

var folder = Path.GetDirectoryName(
   Assembly.GetExecutingAssembly().Location) +
   Path.DirectorySeparatorChar + 
   SettingsFileName;

Here we might store a file for application specific data then create another file using the username (here we can use the Environment.UserName) of the user logged into the machine for each user.

This is a simple solution and in some cases more than adequate, plus it has the benefit that if we delete the application (i.e. it wasn’t installed via an installer) then we delete any configuration files.

Program Data

The ProgramData folder is on the system drive and is hidden by default (see C:\ProgramData). As can be inferred from the name, it’s generally used for settings specific to the application itself, i.e. not based upon specific users on a machine.

We can access it using the following code

var folder = Path.Combine(
   Environment.GetFolderPath(
      Environment.SpecialFolder.CommonApplicationData),
      "YourAppName");

Interestingly you can access the ProgramData using C:\Users\AllUsers in File Explorer, although File Explorer will state that you are in C:\Users\AllUsers it’s the same folder as C:\ProgramData.

Program Data can also be located using the environment variable %programdata%.

User Data

So we’ve seen that we can use the Environment.UserName to combine with our file name to create user files, but Windows already has the capability locations for user data. Plus, depending how your OS is set up, this data may be used across any machine a user logs into (known as Roaming).

The default location for the following “User Data” folders is under the location C:\Users\<username>\AppData

Local

The Local folder can be located using the special folder LocalApplicationData, for example

var folder = Path.Combine(
   Environment.GetFolderPath(
      Environment.SpecialFolder.LocalApplicationData),
      "YourAppName");

and is also available via the environment variable %localappdata%.

This location contains data that cannot be stored in the Roaming folder, for example data that’s specific to the machine the user is logged into or that is too large to store in a synchronized roaming folder (i.e. where Roaming folders are synchronized with a server).

Roaming

As hinted at in the section on the Local folder. The Roaming folder can be synchronized with a server, i.e. this is a profile which is accessible from other machines that a user logs into on the same domain. Hence anything stored here will “follow” the user around and so is very useful for preferences, favourites etc. However the space available may be limited depending upon quota settings or other space limitations.

To access this folder we simply use the ApplicationData special folder or environment variable %appdata%, for example

var folder = Path.Combine(
   Environment.GetFolderPath(
      Environment.SpecialFolder.ApplicationData),
      "YourAppName");

LocalLow

The LocalLow folder is basically a restricted version of the Local folder. The data is not synchronized with a server and hence does not move from the machine its created on and it has a lower level of access.

When I say “restricted” or “lower level access” basically this means the application being run, itself has security constraints placed upon it.

The LocalLow folder does not have an entry within the SpecialFolder enumeration, so access the folder you need to use the following (copied from Thomans Levesque’s answer on StackOverflow – https://stackoverflow.com/questions/4494290/detect-the-location-of-appdata-locallow)

[DllImport("shell32.dll")]
static extern int SHGetKnownFolderPath(
   [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, 
   uint dwFlags, 
   IntPtr hToken, 
   out IntPtr pszPath);

public static string GetFolderLocalLow()
{
   var pszPath = IntPtr.Zero;
   try
   {
      var hr = SHGetKnownFolderPath(folderGuid, 0, IntPtr.Zero, out pszPath);
      if (hr < 0)
      {
         throw Marshal.GetExceptionForHR(hr);
      }
      return Marshal.PtrToStringAuto(pszPath);
   }
   finally
   {
      if (pszPath != IntPtr.Zero)
      {
         Marshal.FreeCoTaskMem(pszPath);
      }
   }
}

Accessing location via the environment variables

In a few places I’ve shown the environment variable for each of the locations mentioned. We can also use these variables to locate the folders, for example

var location = 
   Environment.ExpandEnvironmentVariables("%AppData%")

This will result in returning the Roaming folder location, but what’s nice is this static method will work with environment variables combined with file locations (as you’d probably expect), so for example

var location = 
   Environment.ExpandEnvironmentVariables("%AppData%\MyApp")

This will return a path along the lines C:\Users\<username>\AppData\Roaming\MyApp

Source added to https://github.com/putridparrot/blog-projects/tree/master/FileLocations

.NET’s SecureString

I’m investigating various security based topics at the moment. Whilst I have dabbled in security in the past I do not class myself an expert on the subject, hence these posts may be fairly basic.

Background

I’m doing some coding that requires a level of security around data (specifically strings) which is simply not available using the String class.

The String class has a couple of properties which make it less than secure

  • The string is stored in memory as plain text
  • The disposal of memory is non deterministic and hence can remain in memory long after it’s usage has been completed

Obviously if we were to store a password in a string we can use tools such as WinDbg to dump memory and ultimately locate all instances of the password strings. Sure it might take a bit of time, but ultimately we’d find the password as plain text.

A solution?

TL;DR SecureString is only really secure until you need to get at the string, this isn’t a solution to 100% security but may help in certain situations, not least for situations where you want to pass a string between methods.

SecureString is a .NET class which is totally unrelated to the String class and it’s aim is to fix the security issues which exist for the String class, so

  • The SecureString may be encrypted within memory, on the MS website it suggests this is dependent upon the underlying OS
  • We can dispose of a SecureString in a deterministic way, i.e. calling the Dispose method or worse case garbage collected

To store some characters in a SecureString we have to append characters, like this

public static SecureString ToSecureString(string data)
{
   var secure = new SecureString();
   foreach (var c in data)
   {
      secure.AppendChar(c);
   }
   secure.MakeReadOnly();
   return secure;
}

We can also assign characters via a constructor override which takes a char* and length argument.

To turn a SecureString back into a String we can use

public static string ToString(SecureString secureString)
{
   var ptr = Marshal.SecureStringToBSTR(secureString);
   try
   {
      return Marshal.PtrToStringBSTR(ptr);
   }
   finally
   {
      Marshal.ZeroFreeBSTR(ptr);
   }
}

If, you come from a COM and C++ background you’ll recognize the BSTR’s.

In this code we get a pointer to the unmanaged BSTR from the SecureString then we use the pointer to create a String object. In the finally clause we zero out and release the memory that the BSTR used, ensuring that our password (or whatever) is both cleared and then removed from memory.

You might now be questioning what use the SecureString really is, if we ultimately convert whatever it’s storing too and from a String.

Ofcourse what you really need to do is store data which might be around for a while in the SecureString and preferably rarely convert them to Strings.

Secure input

Control-wise, WPF contains a SecurePassword property on the PasswordBox to allow input to be turned into a SecureString. Hence we can use this to take user input and store “secure” from input until the point we need to use it.

See also

Comparing secure strings in .NET

Documenting your API’s using XML documentation

I’ve been updating one of my GitHub repositories (my Presentation.Core repo.) with some more documentation, using XML documentation comments, and thought I’d write a refresher post for taking your code from no documentation all the way through to being fully documented.

<summary>

So the /// is used for XML documenting comments in C#, for example

/// <summary>
/// A Task/async aware command object. 
/// </summary>
public class AsyncCommand : CommandCommon
{
}

In the above, the <summary> element (and it’s corresponding end element) within the /// acts as a summary of our class. This class level summary is displayed in Visual Studio Intellisense when declaring a type of AsyncCommand when we create code such as new AsyncCommand() Intellisense will display the summary for the default constructor (if such documentation exists).

The summary tag is the most important tag for documenting our code using the XML documentation as it’ll acts as the primary source of information for Intellisense and within generated help files.

<remarks>

This is an optional documentation <remarks> element which can be used to expand upon the summary or add supplementary documentation to the summary element. For example

/// <summary>
/// A Task/async aware command object. 
/// </summary>
/// <remarks>
/// Automatically handles changes to the built-in, IsBusy flag, so when
/// the command is executing the IsBusy is true and when completed or not 
/// executing IsBusy is false.
/// </remarks>
public class AsyncCommand : CommandCommon
{
}

Summary text is displayed by IntelliSense whereas Remarks are shown in the help file output via tools such as Sandcastle.

<returns>

As you might guess, the <returns> element is used on method return values, for example

/// <summary>
/// Implementation of CanExecute which returns a boolean
/// to allow the calling method to determine whether the
/// Execute method can be called
/// </summary>
/// <param name="parameter">An object is ignored in this implementation</param>
/// <returns>True if the command can be executed, otherwise False</returns>
public override bool CanExecute(object parameter)
{
}

<param>

Continuing with the elements available for a method, the param element is used for method arguments, to allow the documentation to list what each parameter is used for.

/// <summary>
/// Implementation of CanExecute which returns a boolean
/// to allow the calling method to determine whether the
/// Execute method can be called
/// </summary>
/// <param name="parameter">An object is ignored in this implementation</param>
/// <returns>True if the command can be executed, otherwise False</returns>
public override bool CanExecute(object parameter)
{
}

<value>

Like a return but used on a property, the <value> element is used along with a summary to describe what the property represents.

<para>

The <para> element is used within summary, remarks or return elements to add paragraph formatting/structure to your documentation.

<exception>

The <exception> element is used (as the name suggests) to list exceptions a method may throw during it’s execution. For example

/// <summary>
/// Constructor take a comparison function which expects two types of T and
/// returns an integer where a value less than 0 indicates the first item is 
/// before the second, a value of 0 indicates they're equivalent 
/// and a value greater than 0 indicates the first item is after
/// the second item. This constructor also takes a function for the object 
/// hash code method.
/// </summary>
/// <param name="objectComparer">
/// A function to compare two items of type T
/// </param>
/// <exception cref="System.NullReferenceException">
/// Thrown when the objectComparer is null
/// </exception>
public ComparerImpl(
   Func<T, T, int> objectComparer)
{
   _objectComparer = 
      objectComparer ?? 
      throw new NullReferenceException("Comparer cannot be null");
}

IntelliSense will display the list of exceptions

<see>

The <see> element allows us to reference documentation elsewhere within your code, it accepts a cref argument and within this we need to reference our classname.methodname etc. For example

/// <summary>
/// Sets the property value against the property and raises
/// OnPropertyChanging, OnPropertyChanged etc. as required.
/// <see cref="GetProperty{T}"/>
/// </summary>
protected bool SetProperty<T>(
   Func<T> getter, 
   Func<T, T> setter, 
   T value, 
   [CallerMemberName] string propertyName = null)
{
}

Note: In the case of reference another method within the same class we need not declare the class name within the cref, but if referencing another class we should use classname.methodname syntax.

Within IntelliSense and documentation the full method name will be displayed for the see element’s cref.

<seealso>

Usage for <seealso> is as per the see element but generated code will create a see also section and place such references within.

<typeparam>

The <typeparam> element is used to document the generic parameters passed to a class and/or methods, for example

/// <summary>
/// Implements IComparer&lt;T&gt;, IEqualityComparer&lt;T&gt; 
/// and IComparer
/// </summary>
/// <typeparam name="T">The type of being compared</typeparam>
public class ComparerImpl<T> : 
   IComparer<T>, IEqualityComparer<T>, IComparer
{
}

<paramref>

Used within a summary or remarks, the <paramref> is used to refer to a parameter on the method being documented. For example

/// <summary>
/// Gets the current value via a Func via the <paramref name="generateFunc"/>
/// </summary>
/// <typeparam name="T">The property type</typeparam>
/// <param name="generateFunc">The function to create the return value</param>
/// <param name="propertyName">The name of the property</param>
/// <returns>The value of type T</returns>
protected T ReadOnlyProperty<T>(
   Func<T> generateFunc, 
   [CallerMemberName] string propertyName = null)
{
}

In the above, generateFunc is displayed within the IntelliSense summary and highlighted (via an italic font) in generated help files.

<typeparamref>

Like paramref, the <typeparamref> element can be used within summary, remarks etc. to link to a specific generic type, for example

/// <summary>
/// Gets the current property value as type <typeparamref name="T"/>
/// </summary>
protected T GetProperty<T>(
   Func<T> getter, 
   Func<T, T> setter, 
   [CallerMemberName] string propertyName = null)
{
}

As per paramref generated documentation may highlight the name within a help file and it’s also displayed via IntelliSense within the summary.

<list>

The <list> element allows us to define formatted text in a bullet, name or table format within our summary block, for example

/// <summary>
/// Acts as a base class for view models, can be used
/// with backing fields or delegating getter/setter 
/// functionality to another class - useful for situations
/// where the underlying model is used directly
/// <list type="bullet">
/// <item><description>GetProperty</description></item>
/// <item><description>SetProperty</description></item>
/// <item><description>ReadOnlyProperty</description></item>
/// </list>
/// </summary>
public class ViewModelWithModel : ViewModelCommon
{
}

This results in generated documentation showing a bullet list of items, within IntelliSense, this isn’t quite so pretty and results in just the descriptions listed with space delimitation.

<example>

The <example> element allows us to add example code to our documentation, for example

/// <summary>
/// Sets the property value against the property and raises
/// OnPropertyChanging, OnPropertyChanged etc. as required
/// </summary>
/// <example>
/// <code>
/// public string Name
/// {
///    set => SetProperty(value);
///    get => GetProperty();
/// }
/// </code>
/// </example>
protected bool SetProperty<T>(
   T value, 
   [CallerMemberName] string propertyName = null)
{
}

Note: Without the <code> element the example is not formatted as we’d expected. This is results in a generated help file section named examples.

<code>

The <code> element is used within the example element to format code samples. See above.

<c>

The <c> element may be used within a summary or other element and formats the text within it as code.

<permission>

As you probably guessed, we can highlight the permissions expected or required for a method etc. using the <permission> element. For example

/// <summary>
/// Gets the current property value
/// </summary>
/// <permission cref="System.Security.PermissionSet">
/// Unlimited access to this method.
/// </permission>
protected T GetProperty<T>([CallerMemberName] string propertyName = null)
{
}

The above will result in generated documentation with a security section which includes a table of the cref value and the description for the permissions required for the method.

<include>

The <include> element allows us to use documentation from an external XML file.

How do we generate the XML documents?

Once we’ve documented our code using the XML documentation we will need to get Visual Studio to generate the XML files for the documents, basically extracting the comment blocks into these external files.

For each project you wish to generate documentation for (within Visual Studio) select the properties for the project and then the Build tab. In the Output sections check the XML documentation file check box and either allow the default file name or create your own.

References

Documenting your code with XML comments

Reading the BOM/preamble

Sometimes we get a file with the BOM (or preamble) bytes at the start of the file, which denote a UNICODE encoded file. We don’t always care these and want to simple remove the BOM (if one exists).

Here’s some fairly simple code which shows the reading of a stream or file with code to “skip the BOM” at the bottom

using (var stream = 
   File.Open(currentLogFile, 
      FileMode.Open, 
      FileAccess.Read, 
      FileShare.ReadWrite))
{
   var length = stream.Length;
   var bytes = new byte[length];
   var numBytesToRead = (int)length;
   var numBytesRead = 0;
   do
   {
      // read the file in chunks of 1024
      var n = stream.Read(
         bytes, 
         numBytesRead, 
         Math.Min(1024, numBytesToRead));

      numBytesRead += n;
      numBytesToRead -= n;

   } while (numBytesToRead > 0);

   // skip the BOM
   var bom = new UTF8Encoding(true).GetPreamble();
                    
   return bom.Where((b, i) => b != bytes[i]).Any() ? 
      bytes : 
      bytes.Skip(bom.Length).ToArray();
}

IOException – the process cannot access the file because it is used by another process

I’m using a logging library which is writing to a local log file and I also have a diagnostic tool which allows me to view the log files, but if I try to use File.Open I get the IOException,

“the process cannot access the file because it is used by another process”

this is obviously self-explanatory (and sadly not the first time I’ve had this and had to try and recall the solution).

So to save me searching for it, here the solution which allows me to open a file that’s already opened for writing to by another process

using (var stream = 
   File.Open(currentLogFile, 
      FileMode.Open, 
      FileAccess.Read, 
      FileShare.ReadWrite))
{
   // stream reading code
}

The key to the File.Open line is the FileShare.ReadWrite. We’re interested in opening the file to read but we still need to specify the share flag(s) FileShare.ReadWrite.

How does yield return work in .NET

A while back I had a chat with somebody who seemed very interested in what the IL code for certain C#/.NET language features might look like – whilst it’s something I did have an interest in during the early days of .NET, it’s not something I had looked into since then, so it made me interested to take a look again.

One specific language feature of interest was “what would the IL for yield return look like”.

This is what I found…

Here’s a stupidly simple piece of C# code that we’re going to use. We’ll generate the binary then decompile it and view the IL etc.

public IEnumerable<string> Get()
{
   yield return "A";
}

Using JetBrains dotPeek (ILDASM, Reflector or ILSpy can ofcourse be used to do generate the IL etc.). So the IL created for the above method looks like this

.method public hidebysig instance 
   class [mscorlib]System.Collections.Generic.IEnumerable`1<string> 
      Get() cil managed 
{
   .custom instance void  [mscorlib]System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(class [mscorlib]System.Type) 
   = (
      01 00 1b 54 65 73 74 59 69 65 6c 64 2e 50 72 6f // ...TestYield.Pro
      67 72 61 6d 2b 3c 47 65 74 3e 64 5f 5f 31 00 00 // gram+<Get>d__1..
      )
   // MetadataClassType(TestYield.Program+<Get>d__1)
   .maxstack 8

   IL_0000: ldc.i4.s     -2 // 0xfe
   IL_0002: newobj       instance void TestYield.Program/'<Get>d__1'::.ctor(int32)
   IL_0007: dup          
   IL_0008: ldarg.0      // this
   IL_0009: stfld        class TestYield.Program TestYield.Program/'<Get>d__1'::'<>4__this'
   IL_000e: ret          
} // end of method Program::Get

If we ignore the IteratorStateMachineAttribute and jump straight to the CIL code label IL_0002 it’s probably quite obvious (even if you do not know anything about IL) that this is creating a new instance of some type, which appears to be an inner class (within the Program class) named <Get>d__1. The preceeding ldc.i4.s instruction simply pushes an Int32 value onto the stack, in this instance that’s the value -2.

Note: IteratorStateMachineAttribute expects a Type argument which is the state machine type that’s generated by the compiler.

Now I could display the IL for this new type and we could walk through that, but it’d be much easier viewing some C# equivalent source to get some more readable representation of this. So I got dotPeek to generate the source for this type (from the IL).

First let’s see what changes are made by the compiler to the Get() method we wrote

[IteratorStateMachine(typeof (Program.<Get>d__1))]
public IEnumerable<string> Get()
{
   Program.<Get>d__1 getD1 = new Program.<Get>d__1(-2);
   getD1.<>__this = this;
   return (IEnumerable<string>) getD1;
}

You can now see the newobj in it’s C# form, creating the <Get>d__1 object with a ctor argument of -2 which is assigned as an initial state.

Now let’s look at this lt;Get>d__1 generated code

[CompilerGenerated]
private sealed class <Get>d__1 : 
    IEnumerable<string>, IEnumerable, 
    IEnumerator<string>, IDisposable, 
    IEnumerator
{
   private int <>1__state;
   private string <>2__current;
   private int <>l__initialThreadId;
   public Program <>4__this;

   string IEnumerator<string>.Current
   {
      [DebuggerHidden] get
      {
         return this.<>2__current;
      }
   }

   object IEnumerator.Current
   {
      [DebuggerHidden] get
      {
         return (object) this.<>2__current;
      }
   }

   [DebuggerHidden]
   public <Get>d__1(int <>1__state)
   {
      base..ctor();
      this.<>1__state = param0;
      this.<>l__initialThreadId = Environment.CurrentManagedThreadId;
   }

   [DebuggerHidden]
   void IDisposable.Dispose()
   {
   }

   bool IEnumerator.MoveNext()
   {
      switch (this.<>1__state)
      {
         case 0:
            this.<>1__state = -1;
            this.<>2__current = "A";
            this.<>1__state = 1;
            return true;
          case 1:
            this.<>1__state = -1;
            return false;
          default:
            return false;
      }
   }

   [DebuggerHidden]
   void IEnumerator.Reset()
   {
      throw new NotSupportedException();
   }

   [DebuggerHidden]
   IEnumerator<string> IEnumerable<string>.GetEnumerator()
   {
      Program.<Get>d__1 getD1;
      if (this.<>1__state == -2 && 
          this.<>l__initialThreadId == Environment.CurrentManagedThreadId)
      {
          this.<>1__state = 0;
          getD1 = this;
      }
      else
      {
          getD1 = new Program.<Get>d__1(0);
          getD1.<>4__this = this.<>4__this;
      }
      return (IEnumerator<string>) getD1;
   }

   [DebuggerHidden]
   IEnumerator IEnumerable.GetEnumerator()
   {
      return (IEnumerator) this.System.Collections.Generic.IEnumerable<System.String>.GetEnumerator();
    }
}

As you can see, yield causes the compiler to create enumerable implementation for just that one of code.

.NET Core

This should be a pretty short post, just to outline using .NET core on Linux/Ubuntu server via Docker.

We could look to install .NET core via apt-get, but I’ve found it so much simpler running up a Docker container with .NET core already implemented in, so let’s do that.

First up, we run

docker run -it microsoft/dotnet:latest

This is an official Microsoft owned container. The use of :latest means we should get the latest version each time we run this command. The -it switch switches us straight into the Docker instance when it’s started, I/e/ into bash.

Now this is great if you’re happy to lose any code within the Docker image when it’s removed, but if you want to link into your hosts file system it’s better to run

docker run -it -v /home/putridparrot/dev:/development microsoft/dotnet:latest

Where /home/putridparrot/dev on the left of the colon, is a folder on your host/server filesystem and maps to a folder inside the Docker instance which will be named development (i.e. it acts like a link/shortcut).

Now when you are within the Docker instance you can save files to the host (and vice/versa) and they’ll persist beyond the life of the Docker instance and also allow us a simply means of copying files from, say a Windows machine into the instance of dotnet on the Linux server.

And that literally is that.

But let’s write some code and run it to prove everything is working.

To be honest, you should go and look at Install for Windows (or one of the installs for Linux or Mac) as I’m pretty much going to recreate the documentation on running dotnet from these pages

To run the .NET core framework, this includes compiling code, we use the command

dotnet

Before we get going, .NET core is very much a preview/RC release, so this is the version I’m currently using (there’s no guarantee this will work the same way in a production release), running

dotnet --version

we get version 1.0.0-preview2-003131.

Let’s create the standard first application

Now, navigate to home and then make a directory for some source code

cd /home
mkdir HelloWorld
cd /HelloWorld

yes, we’re going to write the usual, Hello World application, but that’s simply because the dotnet command has a built in “new project” which generates this for us. So run

dotnet new

This creates two files, Program.cs looks like this

using System;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

nothing particularly interesting here, i.e. its a standard Hello World implementation.

However a second file is created (which is a little more interesting), the project.json, which looks like this

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.1"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

Now, we need to run the following from the same folder as the project (as it will use the project.json file)

dotnet restore

this will restore any packages required for the project to build. To build and run the program we use

dotnet run

What are the dotnet cmd options

Obviously you can run dotnet –help and find these out yourself, but just to give a quick overview, this is what you’ll see as a list of commands

Common Commands:
  new           Initialize a basic .NET project
  restore       Restore dependencies specified in the .NET project
  build         Builds a .NET project
  publish       Publishes a .NET project for deployment (including the runtime)
  run           Compiles and immediately executes a .NET project
  test          Runs unit tests using the test runner specified in the project
  pack          Creates a NuGet package

.NET Core in Visual Studio 2015

Visual Studio (2015) offers three .NET core specific project templates, Class Library, Console application and ASP.NET Core.

References

https://docs.microsoft.com/en-us/dotnet/articles/core/tutorials/using-with-xplat-cli
https://docs.asp.net/en/latest/getting-started.html
https://docs.microsoft.com/en-us/dotnet/articles/core/tools/project-json

Populating random data

I was working on a small utility which generates XML based upon a given class (which is already XML serializable). I wanted to generate random data just so I could see how the end XML looked in case I needed to tweak the XSD.

Source for the utility is available on AutoGenXml.

I figured somebody must have already approached such a problem, and thankfully I was right. There are a few solutions for populating object data. I ended up trying out two different libraries, AutoFixture and NBuilder.

Disclaimer: I have literally only just started using these libraries, so I’ve yet to find all the good and/or bad points of each library.

Let’s take a real quick look at what these libraries can do.

Test object

Let’s start out by defining an object hierarchy to test this two libraries out on. Mine looks like this

public class Album
{
   public string Title { get; set; }
   public string RecordLabel { get; set; }
   public Artist Artist { get; set; }
   public string Genre { get; set; }
}

public class Artist
{
   public string Name { get; set; }
   public BandMember[] Band { get; set; }
}

public class BandMember
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Talent { get; set; }
}

AutoFixture

AutoFixture source can be found on AutoFixture.

We can create objects with AutoFixture (hence using it as the factory for our objects) and it returns a populated object hierarchy.

Let’s look at the code (it’s pretty simple)

var fixture = new Fixture();
var album = fixture.Create<Album>();

The album will now have data in all fields and the Artist and BandMember properties are also created and data supplied.

Whilst it’d obviously be easy enough for us to create an object multiple times if we wanted a list of Albums but AutoFixture also supplies this code to do the same thing

var fixture = new Fixture {RepeatCount = 10};
var albums = fixture.
                 Repeat(fixture.Create<Album>).
                 ToArray();

NBuilder

NBuilder source can be found on NBuilder.

NBuilder also supplies a factory pattern for both creating our objects and populating the object.

Here’s the code

var album = Builder<Album>
               .CreateNew()
               .Build();

NBuilder uses a fluent style interface and offers options for creating multiple items (i.e. an IList<> of objects). There’s also a mechanism for us to intercept the object population step and supply our own data. So whilst in the usage shown above, we don’t have the object heriarchy created, we can create this ourselves fairly easily using

var albums = Builder<Album>
   .CreateListOfSize(10)
   .All()
      .With(a => a.Artist = Builder<Artist>.CreateNew()
         .With(b => b.Band = Builder<BandMember>
                    .CreateListOfSize(3)
                       .Build().ToArray())
	.Build())
   .Build();

References

This is a great post on using NBuilder with Faker which allows us to populate the objects with more realistic data than the default process.

Increasing the maximum number of connections with maxconnection

By default when calling webservices etc. we’re limited to 2 maximum connections at a time in an application, so it doesn’t matter if you (for example) create multiple background threads to run webservice calls as you’ll still be limited to two connections.

We can change this using the App.config for our application and adding the following

<system.net>
   <connectionManagement>
      <add address="*" maxconnection="20"/>
   </connectionManagement>
</system.net>

See ConnectionManagementElement.MaxConnection Property

Note: The maxconnection does not apply to local web service calls