Tag: .net core

Two ways to import an XML file with .Net Core or .Net Framework

It's always the simple stuff you forget how you do. For years I've mainly been working with JSON files, so when faced with that task of reading an XML file my brain went "I can do that" followed by "actually how did I used to do that?".

So here's two different methods. They work on .Net Core and theoretically .Net Framework (my project is .Net Core and haven't checked that they do actually work on framework).

My examples are using an XML in the following format:

<?xml version="1.0" encoding="utf-8"?>
<jobs>
  <job>
      <company>Construction Co</company>
      <sector>Construction</sector>
      <salary>£50,000 - £60,000</salary>
      <active>true</active>
      <title>Recruitment Consultant - Construction Management</title>
  </job>
  <job>
      <company>Medical Co</company>
      <sector>Healthcare</sector>
      <salary>£60,000 - £70,000</salary>
      <active>false</active>
      <title>Junior Doctor</title>
  </job>
</jobs>

Method 1: Reading an XML file as a dynamic object

The first method is to load the XML file into a dynamic object. This is cheating slightly by first using Json Convert to convert the XML document into a JSON string and then deserializing that into a dynamic object.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace XMLExportExample
{
  class Program
  {
      static void Main(string[] args)
      {
          string jobsxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><jobs>    <job><company>Construction Co</company><sector>Construction</sector><salary>£50,000 - £60,000</salary><active>true</active><title>Recruitment Consultant - Construction Management</title></job><job><company>Medical Co</company><sector>Healthcare</sector><salary>£60,000 - £70,000</salary><active>false</active><title>Junior Doctor</title></job></jobs>";

          byte[] byteArray = Encoding.UTF8.GetBytes(jobsxml);
          MemoryStream stream = new MemoryStream(byteArray);
          XDocument xdoc = XDocument.Load(stream);

          string jsonText = JsonConvert.SerializeXNode(xdoc);
          dynamic dyn = JsonConvert.DeserializeObject<ExpandoObject>(jsonText);

          foreach (dynamic job in dyn.jobs.job)
          {
              string company;
              if (IsPropertyExist(job, "company"))
                  company = job.company;

              string sector;
              if (IsPropertyExist(job, "sector"))
                  company = job.sector;

              string salary;
              if (IsPropertyExist(job, "salary"))
                  company = job.salary;

              string active;
              if (IsPropertyExist(job, "active"))
                  company = job.active;

              string title;
              if (IsPropertyExist(job, "title"))
                  company = job.title;

              // A property that doesn't exist
              string foop;
              if (IsPropertyExist(job, "foop"))
                  foop = job.foop;
          }

          Console.ReadLine();
      }

      public static bool IsPropertyExist(dynamic settings, string name)
      {
          if (settings is ExpandoObject)
              return ((IDictionary<string, object>)settings).ContainsKey(name);

          return settings.GetType().GetProperty(name) != null;
      }
  }
}

A foreach loop then goes through each of the jobs, and a helper function IsPropertyExist checks for the existence of a value before trying to read it.

Method 2: Deserializing with XmlSerializer

My second approach is to turn the XML file into classes and then deserialize the XML file into it.

This approch requires more code, but most of it can be auto generated by visual studio for us, and we end up with strongly typed objects.

Creating the XML classes from XML

To create the classes for the XML structure:

1. Create a new class file and remove the class that gets created. i.e. Your just left with this

using System;
using System.Collections.Generic;
using System.Text;

namespace XMLExportExample
{

}

2. Copy the content of the XML file to your clipboard
3. Select the position in the file you want to the classes to go and then go to Edit > Paste Special > Paste XML as Classes

If your using my XML you will now have a class file that looks like this:

using System;
using System.Collections.Generic;
using System.Text;

namespace XMLExportExample
{

  // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
  /// <remarks/>
  [System.SerializableAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
  [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
  public partial class jobs
  {

      private jobsJob[] jobField;

      /// <remarks/>
      [System.Xml.Serialization.XmlElementAttribute("job")]
      public jobsJob[] job
      {
          get
          {
              return this.jobField;
          }
          set
          {
              this.jobField = value;
          }
      }
  }

  /// <remarks/>
  [System.SerializableAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
  public partial class jobsJob
  {

      private string companyField;

      private string sectorField;

      private string salaryField;

      private bool activeField;

      private string titleField;

      /// <remarks/>
      public string company
      {
          get
          {
              return this.companyField;
          }
          set
          {
              this.companyField = value;
          }
      }

      /// <remarks/>
      public string sector
      {
          get
          {
              return this.sectorField;
          }
          set
          {
              this.sectorField = value;
          }
      }

      /// <remarks/>
      public string salary
      {
          get
          {
              return this.salaryField;
          }
          set
          {
              this.salaryField = value;
          }
      }

      /// <remarks/>
      public bool active
      {
          get
          {
              return this.activeField;
          }
          set
          {
              this.activeField = value;
          }
      }

      /// <remarks/>
      public string title
      {
          get
          {
              return this.titleField;
          }
          set
          {
              this.titleField = value;
          }
      }
  }

}

Notice that the active field was even picked up as being a bool.

Doing the Deserialization

To do the deserialization, first create an instance of XmlSerializer for the type of the object we want to deserialize too. In my case this is jobs.

var s = new System.Xml.Serialization.XmlSerializer(typeof(jobs));

Then call Deserialize passing in a XML Reader. I'm creating and XML reader on the stream I used in the dynamic example.

jobs o = (jobs)s.Deserialize(XmlReader.Create(stream));

The complete file now looks like this:

using System;
using System.IO;
using System.Text;
using System.Xml;

namespace XMLExportExample
{
  class Program
  {
      static void Main(string[] args)
      {
          string jobsxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><jobs>    <job><company>Construction Co</company><sector>Construction</sector><salary>£50,000 - £60,000</salary><active>true</active><title>Recruitment Consultant - Construction Management</title></job><job><company>Medical Co</company><sector>Healthcare</sector><salary>£60,000 - £70,000</salary><active>false</active><title>Junior Doctor</title></job></jobs>";

          byte[] byteArray = Encoding.UTF8.GetBytes(jobsxml);
          MemoryStream stream = new MemoryStream(byteArray);

          var s = new System.Xml.Serialization.XmlSerializer(typeof(jobs));
          jobs o = (jobs)s.Deserialize(XmlReader.Create(stream));

          Console.ReadLine();
      }
  }
}

And thats it. Any missing nodes in your XML will just be blank rather than causing an error.

ASP.NET Core Platforms for a Blog

Like a lot of Sitecore developers my blog (at time of writing) is hosted on Wordpress. The reason for it not being in Sitecore is simple. Sitecore is an enterprise level platform, which isn't really needed for a personal blog.

For a .net dev to have there blog on a php platform however just seems plain wrong, but again there's a logical reason. Wordpress is actually really good as a blogging platform, and it doesn't cost me anything.

Despite this I would much rather take control of my site and use it to play with all the cool features in Azure. It would also be nice to have the ability to do something about the Google PageSpeed result which is currently sitting at 24%. So in aid of this I've started looking into .net core based platforms and thought I'd share what I've found.

Miniblog.core

https://github.com/madskristensen/Miniblog.Core

As the name suggests Miniblog.core is both very small and based on .net core. Developed by Mads Kristensen its an extremely lightweight bare bones implementation, which if your after something you can help build upon is ideal. The code is straightforward to understand and very simple to adapt. Additionally if your after a 100% page speed score, then this achieves just that.

If on the other hand your after a deluxe admin experience full of functionality then this probably isn't for you.

Piranha CMS

http://piranhacms.org/

Piranha CMS is built as a lightweight CMS platform rather than specifically as a blog, however it also contains a blog module which for me put's it at a big advantage over the other CMS platforms I've listed below.

On the back end you get a choice of SQL Server, SQLite or MySQL. The documentation isn't exactly complete, but on the day I tried it out, I found the team building it very responsive on GitHub. They even updated the documentation with one of my suggestions the very next day.

Another aspect I particularly liked about Piranha CMS was it's block editor, which from the brief look I've had so far reminds me of the block editor Umbraco has. Whereas other platforms in this list were restricted to a large rich text field.

Orchard Core

https://github.com/OrchardCMS/OrchardCore

Orchard Core is the dot net core version of the Orchard CMS. It's currently in beta, but I'm not sure that put's it at much of a disadvantage over the others on this list.

My initial impressions of Orchard Core however weren't as high as Piranha CMS. The admin interface wasn't quite as nice and as far as I could tell, it didn't have anything like Piranha's block editor. The solution itself also seemed far more complex and I wasn't certain what I got for this. I expect Orchard Core is likely better in some ways that I have yet to discover, but for my needs as a blog this is probably not the case. It also didn't have a blog module out of the box.

Squidex

https://squidex.io/

I have't had much of a chance to play with Squidex yet, but it does offer an interesting difference to the others mentioned so far.

For a start Squidex is an entirely headless cms, and is built around the concept of CQRS and Event Sourcing. Unlike the others it also uses MongoDB rather than a SQL based database.

Where MongoDB is concerned, I often get the impression people are using it because as developers we tend to have a preference to using something new rather than something adequate. However when it comes to Azure pricing, there is potentially a saving to be made by using Mongo rather than Azure SQL.