Search This Blog

Tuesday, November 24, 2015

Autofac Modules C# Tutorial

C# > Patterns > Dependency Injection  > Autofac Modules


Create a project with the following structure:

Project.cs

namespace AutofacModules
{
    public class Project
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Task.cs

namespace AutofacModules
{
    public class Task
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

IProjectRepository.cs

namespace AutofacModules
{
    public interface IProjectRepository
    {
        void Create(Project project);
    }
}

ITaskRepository.cs

namespace AutofacModules
{
    public interface ITaskRepository
    {
        void Create(Task task);
    }
}

ProjectModule.cs

Register a component to be created through reflection.

using Autofac;
namespace AutofacModules
{
    public class ProjectModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ProjectRepository>().As<IProjectRepository>();
            base.Load(builder);
        }
    }
}







TaskModule.cs

using Autofac;
namespace AutofacModules
{
    public class TaskModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<TaskRepository>().As<ITaskRepository>();
            base.Load(builder);
        }
    }
}

RegistrationModule.cs

Add a module to the container.

using Autofac;
namespace AutofacModules
{
    public class RegistrationModule
    {
        public static IContainer BuildContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterModule<ProjectModule>();
            builder.RegisterModule<TaskModule>();

            return builder.Build();
        }
    }
}

Example:

            Project project = new Project()
            {
                Id = 1,
                Name = "Project 1"
            };

            Task task = new Task()
            {
                Id = 1,
                Name = "Task 1"
            };

            var container = RegistrationModule.BuildContainer();

//Retrieve a service from the context.

            var projectRepository = container.Resolve<IProjectRepository>();
            var taskRepository = container.Resolve<ITaskRepository>();

            projectRepository.Create(project);
            taskRepository.Create(task);









Friday, October 30, 2015

Dependency Injection in C# with Autofac - real world example

C# > Patterns > Dependency Injection  > Autofac

Autofac is an addictive Inversion of Control container for .NET 4.5, Silverlight 5, Windows Store apps, and Windows Phone 8 apps

Source: http://autofac.org/

Dependency Injection in C# with Autofac - real world example

using Autofac;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    public class Programmer
    {
        public string Name { get; set; }
        public IList<string> Skills { get; set; }
    }




    public class Project
    {
        public string Name { get; set; }
        readonly IList<Programmer> _programmers;
        readonly IDispatcher _dispatcher;

        public Project(IList<Programmer> programmers, IDispatcher dispatcher)
        {
            _programmers = programmers;
            _dispatcher = dispatcher;
        }

        public void FindProgrammers()
        {
            var programmers = _programmers.Where(e => e.Skills.Contains("VB"));

            foreach (var p in programmers)
                _dispatcher.Notify(p);
        }
    }

    public interface IDispatcher
    {
        void Notify(Programmer programmer);
    }

    public class Email : IDispatcher
    {
        private readonly string _message;

        public Email(string message)
        {
            _message = message;
        }

        public void Notify(Programmer programmer)
        {
            Console.WriteLine("Sent message {0} to {1}", _message,  programmer.Name);
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<Programmer> lst = new List<Programmer>();
            Programmer p = new Programmer();
            p.Name = "Dan";
            p.Skills = new List<string>();
            p.Skills.Add("VB");
            lst.Add(p);

            Email email = new Email("Notification email message");

            ContainerBuilder autofac = new ContainerBuilder();
            autofac.Register(o => new Project(o.Resolve<IList<Programmer>>(), o.Resolve<IDispatcher>()));

            autofac.RegisterType<Email>().As<IDispatcher>();
            autofac.RegisterInstance(lst).As<IList<Programmer>>();
            autofac.RegisterInstance(email).As<IDispatcher>();
           
            using (var container = autofac.Build())
            {
                container.Resolve<Project>().FindProgrammers();
            }

        }
    }
}





Thursday, October 29, 2015

SQL Server XML Data

SQL Server > XML Data

XML support is integrated into all the components in SQL Server.






Tuesday, October 27, 2015

OrderBy Key Dictionary C#

C# > LINQ Query Expressions > OrderBy Key Dictionary

dictionary.OrderBy(key => key.Key);






Saturday, October 17, 2015

'cmake' is not recognized as an internal or external command error

'cmake' is not recognized as an internal or external command

Solution:

Add the path to system variables Path










Thursday, October 15, 2015

Visual Studio show Decrease Increase Line Indent Buttons

Visual Studio > Decrease/Increase Line Indent buttons

Go o the toolbar and press:
than check Decrease/Increase Line Indent:






Wednesday, October 7, 2015

Find max value of a column in a DataTable c#

C# > System.Data   > DataTableMax Value

Find max value of a column in a DataTable C#.

var maxValue = DataTable1.AsEnumerable().Max(r => r.Field<double>("value"));





Thursday, October 1, 2015

Telerik report bind to DataTable and add a sample calculated field

Telerik > Reporting > Bind to DataTable

Example
Bind to DataTable and add a sample calculated field.

string connString = "Data Source=(local)\\SQLEXPRESS;Initial Catalog=HR;Integrated Security=True";
string cmdText = "SELECT FirstName, LastName FROM Person;";

SqlDataAdapter da = new SqlDataAdapter(cmdText, connString);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);

Telerik.Reporting.ObjectDataSource ods = new Telerik.Reporting.ObjectDataSource();
ods.DataSource = dt;
ods.CalculatedFields.Add(new Telerik.Reporting.CalculatedField("FullName", typeof(string), "=Fields.FirstName + ' ' + Fields. LastName ")); 
Telerik.Reporting.Report rpt = new Telerik.Reporting.Report();
rpt.DataSource = objectDataSource;
Telerik.Reporting.InstanceReportSource reportSource = new Telerik.Reporting.InstanceReportSource();
reportSource.ReportDocument = rpt;
reportViewer1.ReportSource = reportSource;
reportViewer1.RefreshReport();





Monday, September 28, 2015

Choose Visual Basic Example

VB.NET Functions > Choose

Returns a member of the list passed in Choice().
It is based on the value of Index. The first member of the list is selected when Index is 1.

Example

Dim choice = Choose(2, "val1", "val2", "val2") // "val2"





Thursday, September 24, 2015

Appends text to a file C#

C# > Files > File Class > AppendText

Appends text to an existing file or create a new file if the specified file does not exist.

Example

using(System.IO.StreamWriter sw = System.IO.File.AppendText(@"c:\log.txt"))
{
      sw.WriteLine("logline");
}





Tuesday, September 15, 2015

Convert to double TimeSpan C#

C# > System > TimeSpan Structure

TimeSpan represents a time structure.

Examples

1. Convert to double
   
  TimeSpan ts = TimeSpan.FromMinutes(12.45);

  double time = ts.TotalMinutes;





Friday, August 14, 2015

SOUNDEX SQL Server Example

SQL Server > Built-in Functions > SOUNDEX

SOUNDEX converts an alphanumeric string to a four-character code that is based on how the string sounds when spoken. 

Example


SELECT SOUNDEX ('Jan'), SOUNDEX ('Jane');

Result:
(No column name) (No column name)
J500                 J500