Search This Blog

Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, December 2, 2015

default keyword c#

C# > Keywords > default

This keyword is used in two ways.

  • default label in switch statement
  • generics: the default value
    • null for reference type
    • 0 for value type




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();
            }

        }
    }
}





Tuesday, October 27, 2015

OrderBy Key Dictionary C#

C# > LINQ Query Expressions > OrderBy Key Dictionary

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






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, 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;





Monday, August 10, 2015

Pow C# Example

C#  > System > Math class > Pow

Pow  number raise a  number to the specified power.

Example:

double pow = Math.Pow(2, 8); // 256




Tuesday, August 4, 2015

Scroll to selected index DataGridView

C# > DataGridViewFirstDisplayedScrollingRowIndex 

Setting this property raises scroll event to match selected index.


Example


dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.Count - 1;




Friday, July 31, 2015

Read fast text file line by line C#

C# > Files > File Class > OpenText

Open text file for reading line by line.

Example

Read fast text file line by line C#

using (StreamReader sr = File.OpenText(@"c:\filename.txt"))
{
   while (!sr.EndOfStream)
   {
     sr.ReadLine();
    }
}







Wednesday, May 20, 2015

Print PictureBox Image C# Example Using PrintDocument

C# > Print  > PrintDocument

PrintDocument sends out to the printer.


Example

Print image



using System;
using System.Drawing;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            printPreviewDialog1.Document = printDocument1;
            printPreviewDialog1.ShowDialog();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(pictureBox1.Image, 100, 100, 700, 600);
        }
    }
}





Monday, May 18, 2015

C# unit test using Moq verify property has been set

C# > Unit test > Moq > Verify property has been set

SetupSet : Specifies a setup on the mocked type for a call to a property setter.
VerifySet : Verifies that a property has been set on the mock, regardless of its value.

Example

using System;

namespace UnitTestProject1
{
    public interface Interface1
    {
        int Id { get; set; }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var mocker = new Mock<Interface1>();
            mocker.SetupSet(x => x.Id = 1);
            mocker.Object.Id = 1;
            mocker.VerifySet(x => x.Id);
        }
    }
}





Friday, May 15, 2015

Convert string to date C# example

C# > System Namespace > DateTime > Parse

Parse converts string to a date.


Example


string value = "5/15/2015";

var dte = DateTime.Parse(value, CultureInfo.InvariantCulture); // {5/15/2015 12:00:00 AM}




Wednesday, April 1, 2015

Reflection to find all classes implementing interface c#

C# > Reflection Find classes implementing interface

var iTtype = typeof(Interface);
var types = AppDomain.CurrentDomain.GetAssemblies()
           .SelectMany(a => a.GetTypes())
           .Where(t => iTtype.IsAssignableFrom(t));





Thursday, February 19, 2015

Write, read XML to memory stream using XmlWriter and XmlReader C#

C# > XML > XmlWriter

XmlWriter  writes XML data to a file, stream,, text reader, or string.
It is fast, noncached and forward only.

Example
Write/read XML to memory stream.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            MemoryStream stream = new MemoryStream();

            XmlWriter writer = XmlWriter.Create(stream);

            writer.WriteStartDocument();
            writer.WriteStartElement("Root");
            writer.WriteElementString("Child", "1");
            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Flush();
            writer.Close();

            stream.Position = 0; // Resets the position to 0 so we can read.
            XmlReader reader = XmlReader.Create(stream);
            while (reader.Read())
            {
                //
            }
            reader.Close();

        }
    }
}