Search This Blog

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





Friday, February 5, 2016

How To Convert A Number To an ASCII Character C#

C#  > System > Convert > ToChar

Converts the value of the specified 8-bit unsigned integer to its equivalent Unicode character.

Example

Convert a number to an ASCII Character

 var asciiCode = System.Convert.ToChar(65).ToString(); // 'A'