Search This Blog

Tuesday, April 5, 2016

Validate Data Models Using DataAnnotations Attributes C#

C# > System > ComponentModel > DataAnnotations

Provides attribute classes that are used to define metadata.

Example

Validate property class with range numbers



using System;
using System.ComponentModel.DataAnnotations;
using System.Windows.Forms;

namespace WindowsFormsApplication8
{
    public class Person
    {
        private int id;

        [Display(Name = "Person Id")]
        [Range(0, 1000)]
        public int Id
        {
            get { return id; }
            set
            {
                Validator.ValidateProperty(value,
                    new ValidationContext(this, null, null) { MemberName = "Id" });
                id = value;
            }
        }
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Person p = new Person();
            p.Id = 1;
            p.Id = 1001;
        }
    }
}












Wednesday, March 23, 2016

Rename files from a folder C#

C# > Files > File Class > Move


Moves a specified file to a new location.
  • option to specify a new file name

Example 

Rename files from a folder 

DirectoryInfo d = new DirectoryInfo(@"D:\folder");
FileInfo[] infos = d.GetFiles("*.*");
int i = 1;
foreach (FileInfo f in infos)
{
  File.Move(f.FullName, Path.Combine(f.DirectoryName, + i.ToString() + ".jpg"));
  i++;
}







Friday, March 11, 2016

Mock Assembly Unit Test C#

C# > Unit tests > Mock Assembly 

If you try to mock

var mock = new Mock<Assembly>();

You will get this error:

The type System.Reflection.Assembly implements ISerializable, but failed to provide a deserialization constructor

Solution

Mock _Assembly interface instead of Assembly class.


var mock = new Mock<_Assembly>();
mock.Setup(w => w.GetTypes()).Throws(new Exception());

Tuesday, March 8, 2016

yield C# Example with KeyValuePair

C# > Keywords > yield

Yield  returns each element one at a time.

When to use:

  • when calculate the next item in the list 
  • for infinite sets

Example


IEnumerable<KeyValuePair<string, string>> dataList = GetData();
dataList.ToList().ForEach(s => MessageBox.Show(s.Key + s.Value));

private IEnumerable<KeyValuePair<string, string>> GetData()
{
yield return new KeyValuePair<string, string>("1", "A");
yield return new KeyValuePair<string, string>("2", "B");
yield return new KeyValuePair<string, string>("3", "C");

}

Thursday, March 3, 2016

Concatenate list of strings c#

C#>  Enumerable > Aggregate

Aggregate performs a calculation over a sequence of values.

Example


List<string> items = new List<string>() { "1", "2", "3", "4" };

var x = items.Aggregate((a, b) => a + "," + b); // "1,2,3,4"

Friday, February 26, 2016

XmlNamespaceManager class c#

C# > XML > XmlNamespaceManager

XML namespaces associate element and attribute names in an XML document with custom and predefined URIs.

Methods












Tuesday, February 23, 2016

Convert ushort to byte array and to ASCII code C# using BitConverter

C#  > System > BitConverter

Converts 

  • base data types to an array of bytes,
  • array of bytes to base data types.


Example

Convert ushort to ASCII code.
(ascii code 2 bytes array)


ushort number = 5678;

byte[] byteArray = BitConverter.GetBytes(number);

foreach (var result in byteArray)
{
string val = System.Convert.ToChar(result).ToString();
}