milosev.com
  • Home
    • List all categories
    • Sitemap
  • Downloads
    • WebSphere
    • Hitachi902
    • Hospital
    • Kryptonite
    • OCR
    • APK
  • About me
    • Gallery
      • Italy2022
    • Curriculum vitae
      • Resume
      • Lebenslauf
    • Social networks
      • Facebook
      • Twitter
      • LinkedIn
      • Xing
      • GitHub
      • Google Maps
      • Sports tracker
    • Adventures planning
  1. You are here:  
  2. Home
  3. C#

Entity framework and Mef example

Details
Written by: Stanko Milosev
Category: C#
Published: 20 May 2016
Last Updated: 17 November 2021
Hits: 6127

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

Hello world MEF example

Details
Written by: Stanko Milosev
Category: C#
Published: 11 May 2016
Last Updated: 20 May 2016
Hits: 11126

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.

Connecting to Oracle XE with ManagedDataAccess

Details
Written by: Stanko Milosev
Category: C#
Published: 31 January 2016
Last Updated: 23 August 2018
Hits: 5788

First I downloaded Oracle Developer Tools for Visual Studio 2015 from here. In my reference list I added Oracle.ManagedDataAccess. My App.config looks like:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="maxaDB"
      connectionString="User ID=userName;Password=pass;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=ipAddress)(PORT=myPort))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=XE)))"
    />
  </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

User ID and Password have to go before Data Source. Then I added "Oracle.ManagedDataAccess.Client;" in using list, and after that connecting was simple:

string maxaDb = ConfigurationManager.ConnectionStrings["maxaDB"].ConnectionString;
OracleConnection conn = new OracleConnection();
In using list you will need System.Configuration, as well in references.

The name 'ConfigurationManager' does not exist in the current context

Details
Written by: Stanko Milosev
Category: C#
Published: 30 January 2016
Last Updated: 30 January 2016
Hits: 5744

In my case I was receiving this error because I was trying to access configuration in my App.config, like:

string maxaDb = ConfigurationManager.ConnectionStrings["maxaDB"].ConnectionString;

To solve this I had to add System.Configuration assembly:

In your using list add:

using System.Configuration;
  1. WebSockets
  2. XSL transformations
  3. Simple events example
  4. Another way of getting exe path

Subcategories

WPF

Beginning

Code snippets

NUnit

LINQ

Windows Forms

Page 11 of 33

  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15