Little bit about regular expressions.

First one my small example:

using System;
using System.Text.RegularExpressions;

namespace RegularExpressions
{
  class Program
  {
    static void Main(string[] args)
    {
      string pattern = "([a])";
      string myName = "Stanko Milosev";
      Console.WriteLine(Regex.IsMatch(myName, pattern));
      Console.ReadKey();
    }
  }
}

According to Regular Expression Language - Quick Reference, pattern [a] means:

[character_group] Matches any single character in character_group. By default, the match is case-sensitive.

Another example comes from codewars. Task was:

Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.

Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Polycarpus inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.

For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".

Recently, Jonny has heard Polycarpus's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Polycarpus remixed. Help Jonny restore the original song.

Solution:

return Regex.Replace(input, "(WUB)+", " " ).Trim();

Where plus sign means:

Matches the previous element one or more times.

And one more my, from my point of view, easier, example:

    static void Main(string[] args)
    {
      string pattern = "(ta)+";
      string myName = "tata";
      Console.WriteLine(Regex.Replace(myName, pattern, "ma"));
      Console.ReadKey();
    }

Result is "ma" - multiple "ta" is replaced with one ma

First install RabbitMQ server. In my case I installed the one from rabbitmq. If you don't have Erlang, it will direct you to the Erlang page. Download and install Erlang, in my case I downloaded OTP 18.3 Windows 64-bit Binary File.

Then in RabbitMQ command prompt write:

rabbitmqctl.bat status

Result should be something like:

If it is not, try to restart your computer.

Next thing is to setup our management plugin

In RabbitMQ command prompt write:

rabbitmq-plugins enable rabbitmq_management

If you installed your RabbitMQ on local host as I did, then go to:

http://localhost:15672/

Username and password is guest / guest

It can be that plugin is not started immediately and you will have to wait couple of seconds before you see login screen of management plugin.

Download .NET/C# RabbitMQ client library, unzip it.

Now, in visual studio start new console application write code like this:

using System;
using RabbitMQ.Client;
using System.Text;

namespace RabbitMQ
{
  class Program
  {
    static void Main(string[] args)
    {
      var factory = new ConnectionFactory() { HostName = "localhost" };
      using (var connection = factory.CreateConnection())
      {
        using (var channel = connection.CreateModel())
        {
          channel.QueueDeclare(queue: "hello",
                                durable: false,
                                exclusive: false,
                                autoDelete: false,
                                arguments: null);

          string message = "Hello World!";
          var body = Encoding.UTF8.GetBytes(message);

          channel.BasicPublish(exchange: "",
                               routingKey: "hello",
                               basicProperties: null,
                               body: body);
          Console.WriteLine(" [x] Sent {0}", message);
        }
      }
    }
  }
}

In reference list add files:

RabbitMQ.Client.dll

and

RabbitMQ.ServiceModel.dll

Which you previously downloaded and uzip it.

When you execute that code open RabbitMQ management, and you should see something like this:

Click on queues button, click on hello

Scroll down and expand get messages

 Click on Get messages button, and you should see your message

Here I already explained what is necessary for creating first step in Mef.  

Right click on references choose Manage NuGet Packages

Install Entity Framework

 In my case I added a folder, and I called it a model, there I created new class which I called PersonModel

Person model code:

  public class PersonModel
    {
        [Key]
        public int PersonId { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public DateTime BirthDate { get; set; }
    }

    public class MyTableDBContext : DbContext
    {
        public DbSet MyTable { get; set; }
    }

In App.config add connection string like:

 
  <connectionStrings>
    <add name="MyTableDBContext" connectionString="Data Source=myServer;
                                                    Initial Catalog=myDb;
                                                    Integrated Security=False;
                                                    Persist Security Info=True;
                                                    User ID=myUser;
                                                    Password=myPass"
             providerName="System.Data.SqlClient" />
  </connectionStrings>

Whole code for export in my case looks like:

using System;
using System.ComponentModel.Composition;
using DbToJson.Model;
using System.Linq;

namespace DbToJson
{
  public interface IDbToJson
  {
    void Seed();
    string DbToJson();
  }

  [Export(typeof(IDbToJson))]
  public class DbToJsonMef : IDbToJson
  {
    public string DbToJson()
    {
      var db = new MyTableDBContext();
      var records = db.MyTable.ToList();
      string myJson = "";
      foreach (var record in records)
      {
        if (myJson == "")
        {
          myJson = "[" +
            "{'PersonId': '" + record.PersonId + "'" +
            "', 'FirstName': '" + record.FirstName + "'" +
            "', 'LastName': '" + record.LastName + "'" +
            "', 'BirthDate': '" + record.BirthDate + "'" +
            "}";
        }
        else
        {
          myJson = myJson +
            "{'PersonId': '" + record.PersonId + "'" +
            "', 'FirstName': '" + record.FirstName + "'" +
            "', 'LastName': '" + record.LastName + "'" +
            "', 'BirthDate': '" + record.BirthDate + "'" +
            "}";
          ;
        }
      }

      myJson = myJson + "]";
      return myJson;
    }

    public void Seed()
    {
      using (var db = new MyTableDBContext())
      {
        db.MyTable.Add(new PersonModel
        {
          FirstName = "Stanko",
          LastName = "Milosev",
          BirthDate = DateTime.Now
        });
        db.MyTable.Add(new PersonModel
        {
          FirstName = "John",
          LastName = "Doe",
          BirthDate = DateTime.Now
        });
        db.MyTable.Add(new PersonModel
        {
          FirstName = "John",
          LastName = "Lennon",
          BirthDate = DateTime.Now
        });
        db.SaveChanges();
      }
    }
  }
}

I made two parts, one I called seed, that one I need to fill database with some data, the other method is for displaying data in JSON.

Now import looks like:

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using DbToJson;

namespace SeedAndConvertToJson
{
  class Program
  {
    private CompositionContainer _container;

    [Import(typeof(IDbToJson))]
    private IDbToJson dbToJson;
    private Program()
    {
      var catalog = new AggregateCatalog();
      catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
      catalog.Catalogs.Add(new DirectoryCatalog(@"../../lib"));

      _container = new CompositionContainer(catalog);

      try
      {
        this._container.ComposeParts(this);
      }
      catch (CompositionException compositionException)
      {
        Console.WriteLine(compositionException.ToString());
      }
    }
    static void Main(string[] args)
    {
      Program p = new Program();
      p.dbToJson.Seed();
      Console.WriteLine(p.dbToJson.DbToJson());
      Console.ReadKey();
    }
  }
}

For the import part we also need to install Entity Framework

Mef is Managed Extensibility Framework. That means that with MEF we can easily make plugin system.

To write this article mostly I was using this article.

In this my small example I am going to make one class library, called MefExport, and with that library I will display "hello world" message in console, in separate solution, in order to have separated as much as possible.

Then I will make console application, called MefImport where I will use method from MefExport.

Let's first make console application, which we will call MefExport:

Right click on references -> Add Reference...

Choose System.ComponentModel.Composition

Code for export:

using System;
using System.ComponentModel.Composition;

namespace MefExport
{
    public interface IHelloWorld
    {
        string HelloWorld();
    }

    [Export(typeof(IHelloWorld))]
    public class MefHelloWorld : IHelloWorld
    {
        public string HelloWorld()
        {
            return "Hello world";
        }
    }

}

After building copy export dll in the lib folder. Change line: catalog.Catalogs.Add(new DirectoryCatalog(@"../../lib")); According to where dll is located.

Import:

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using MefExport;

namespace MefImport
{

    class Program
    {
        private CompositionContainer _container;

        [Import(typeof(IHelloWorld))]
        private IHelloWorld helloWorld;

        private Program()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
            catalog.Catalogs.Add(new DirectoryCatalog(@"../../lib"));

            _container = new CompositionContainer(catalog);

            try
            {
                this._container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine(p.helloWorld.HelloWorld());
            Console.ReadKey();
        }
    }
}

Example project download from here.