Search This Blog

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

Thursday, May 31, 2018

Get File Version of Process c#

c# > System.Diagnostics > Process Class > GetProcesses

GetProcesses: use this method to create an array of new Process components and associate them with all the process resources on the local computer. 

Get File Version of Process

var processes = Process.GetProcesses();

foreach (var process in processes)
{
try
{
              Console.WriteLine("Process: {0} FileVersionInfo: {1}", process.ProcessName, process.MainModule.FileVersionInfo.FileVersion);
       }
       catch
{ };
}

Wednesday, May 3, 2017

C# Concat Example

C# > String > Methods > Concat

Concatenates strings and it does not add any delimiters.

Example


string firstName = "Dan";
string lastName = "Trump";


var name = string.Concat(firstName, " ", lastName); // "Dan Trump"






Monday, December 5, 2016

Trailing zero numeric format string C#

C# > ToString

Examples:

1. Trailing zero numeric format string C#

"N" or "n" is for number.

  double num = 4.2;

  string result = num.ToString("N2"); // "4.20"

Tuesday, September 6, 2016

LINQ OrderByDescending Example C#

C# > LINQ > Enumerable Class > OrderByDescending

Sorts the elements of a sequence in descending order.

Example

List<int> list = new List<int> {    2, 5 ,3 ,10, 7 };
IEnumerable<int> ordList = list.OrderByDescending(num => num);

foreach (int num in ordList)
{
Console.WriteLine(num);

}

Friday, July 29, 2016

Get value from object using Lambda expression

C# > Linq > Expressions > Expression > Compile

Compiles the lambda expression described by the expression tree into executable code and produces a delegate that represents the lambda expression.

Example

Get value from object using Lambda expression

using System;
using System.Linq.Expressions;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{

    public partial class Form1 : Form
    {
        public class Project
        {
            public string Name { get; set; }
            public int Id { get; set; }
        }

        public TProp GetValue(TObj obj, Expression<Func> prop)
        {
            return prop.Compile()(obj);
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var project = new Project();
            project.Name = "Project 1";
            project.Id = 1;

            int id = GetValue(project, i => i.Id);
            string name = GetValue(project, i => i.Name);

        }
    }

}

Friday, July 8, 2016

SQLite C# Example

C# > SQLite

SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection  m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");

m_dbConnection.Open();

string sql = "create table project (name varchar(100), id int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into project (name, id) values ('project 1', 1)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "select * from project order by id desc";
command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())

 Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["id"]);

Tuesday, June 7, 2016

C# get property value from object using reflection

C# > Reflection > Property Info > GetValue

Returns the property value of a specified object.

Example

Get property value from object using reflection.


private static object GetPropValue(object src, string propName)
{
   return src.GetType().GetProperty(propName).GetValue(src, null);
}


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





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'





Convert Class C#

C#  > System > Convert Class

This class is used for conversion to and from the base data types in the .NET Framework.

Methods






Thursday, January 21, 2016

Get all IP Addresses from devices attached to the machine C#

C# > System.Net > Dns > IPHostEntry > AddressList

AddressList gets or sets a list of IP addresses that are associated with a host.

Example

Get all IP Addresses from devices attached to the machine 


string hostName = Dns.GetHostName();
IPHostEntry ipHostEntry = Dns.GetHostEntry(hostName);
foreach (IPAddress item in ipHostEntry.AddressList)
{
var IPAddress = item.ToString();
}






Thursday, December 10, 2015

Clear contents of a file c#

C# > Clear contents of a file

WriteAllText creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

Example

 System.IO.File.WriteAllText(filename, string.Empty);





Wednesday, December 2, 2015

XDocument C# Example

C# > XML > System.Xml.Linq > XDocument

XDocument is an XML document.

Example


XDocument xDocument = new XDocument(
            new XElement("Hours",
                new XElement("Emp1", "0"),
                new XElement("Emp2", "25"),
                new XElement("Emp3", "40"),
                new XElement("Emp4", "30")
                )
            );

Create a new document by filtering data using Linq

XDocument doc = new XDocument(
           new XElement("Report",
                    from el in xDocument.Element("Hours").Elements()
                    where ((int)el) >=30
                    select el
                )

            );

Result contains two records: