C# dynamic ExpandoObject()

using System;
using System.Dynamic;
public class HomeController : Controller
{
       public ActionResult SingleObject()
       {
           dynamic contact = new ExpandoObject(); //Declaring new dynamic object

           contact.Name = "ABC"; // manually adding property & value
           string propertyName = "Age";  int propertyValue = 5; 
           AddProperty(contact, propertyName, propertyValue); //dynamically adding   
                                                                prop & value

           return View(contact);
       }

       //SingleObject.cshtml
       @model dynamic
       <h1>@Model.Name</h1>
       <h1>@Model.Age</h1>

       public ActionResult ObjectList()
       {
          // declaring a list of dynamic object
          dynamic contacts = new List<dynamic>(); 

          // Adding 1st object to the list
          contacts.Add(new ExpandoObject());
          contacts[0].Name = "ABC";
          contacts[0].Phone = "123";

          // Adding 2nd object to the list
          contacts.Add(new ExpandoObject());
          contacts[1].Name = "XYZ";
          contacts[1].Phone = "456";

          return View(contacts);
        }

        //ObjectList.cshtml
        @model dynamic
        @foreach (var item in Model)
        {
           <h2>@item.Name;</h2>
        }

        //Helper method to add property in run-time.
        public void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
        {
            // ExpandoObject supports IDictionary so we can extend it like this
            var expandoDict = expando as IDictionary<string, object>;
            if (expandoDict.ContainsKey(propertyName))
                expandoDict[propertyName] = propertyValue;
            else
                expandoDict.Add(propertyName, propertyValue);
        }
}

Custom Attribute in C#

public class MyCustomAttribute : Attribute
{
    public bool IgnoreIt { get; set; }
    public string FormatString { get; set; }
}

public class Student
{
    [MyCustom(FormatString = "hello", IgnoreIt = false)]
    public string Name { get; set; }

    [MyCustom(IgnoreIt = true)]
    public string Id { get; set; }
}

// Directly check for specific attribute (i.e. FormatString) in specific property 
// (i.e. Name)

var formatString = AttributeHelper.GetPropertyAttributeValue<Student, string, MyCustomAttribute, string>(prop => prop.Name, attr => attr.FormatString.ToString());

public static class AttributeHelper
{
    public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
        Expression<Func<T, TOut>> propertyExpression,
        Func<TAttribute, TValue> valueSelector)
        where TAttribute : Attribute
    {
        var expression = (MemberExpression)propertyExpression.Body;
        var propertyInfo = (PropertyInfo)expression.Member;
        var att = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
        return att != null ? valueSelector(att) : default(TValue);
    }
}

//Dynamically check attribute and it's value
PropertyInfo[] props = typeof(Student).GetProperties();
foreach (PropertyInfo prop in props)
{
    var attribute = prop.GetCustomAttributes(typeof(MyCustomAttribute), true).FirstOrDefault() as MyCustomAttribute;
    if (attribute != null)
    {
        if (attribute.FormatString == null)
        {
            Console.WriteLine("null");
        }
        else
        {
            Console.WriteLine(attribute.FormatString);
        }
    }
}

Dynamically enumerate properties from a class

//Let's have a class first- 
public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
}


using System;
using System.Collections.Generic;
using System.Reflection;

//In case of single object
-----------------------------
void EnumerateField<T>(T t)
{
    PropertyInfo[] props = typeof(T).GetProperties();
    foreach (PropertyInfo property in props)
    {
        string propertyName = property.Name.ToString();
        string propertyType = property.PropertyType.ToString();
        string propertyValue = property.GetValue(t).ToString();
    }
}

//Usage-
Student student = new Student() { StudentId = 100, StudentName = "Shindhu-100" };
EnumerateField(student);


//In case of list<T>
-----------------------------------
void EnumerateFields<T>(List<T> ListOfT)
{
    PropertyInfo[] props = typeof(T).GetProperties();
    foreach (var t in ListOfT)
    {
        foreach (PropertyInfo property in props)
        {
            string propertyName = property.Name.ToString();
            string propertyType = property.PropertyType.ToString();
            string propertyValue = property.GetValue(t).ToString();
        }
    }
}

//Usage-
List<Student> students = new List<Student>();
students.Add(new Student() { StudentId = 1, StudentName = "a" });
students.Add(new Student() { StudentId = 2, StudentName = "b" });
Student st = new Student() { StudentId = 100, StudentName = "Shindhu-100" };
students.Add(st);
EnumerateFields<Student>(students);

Split String Based On Upper Case

string ConvertToWord(string value)
{
    StringBuilder builder = new StringBuilder();
    foreach (char c in value)
    {
        if (Char.IsUpper(c) && builder.Length>0)
        {
            builder.Append(' ');
        }

        builder.Append(c);
    }

    string result = builder.ToString();
    return result;
}


//Usage:
string beforeConvert = "IAmAGoodBoy";
string afterConvert = ConvertToWord(beforeConvert); //I Am A Good Boy

Client-Server File Handling Technique

//Server side
[ValidateInput(false)]
[HttpPost]
public JsonResult ReceiveAudio()
{
    try
    {
        foreach (string f in Request.Files.AllKeys)
        {
            var file = Request.Files[f];
            string fileName = file.FileName.ToString();
        }

        return Json("success");
    }
    catch (Exception Ex)
    {

    }
}

Recursively enumerate files within a directory

private void SearchVoiceFiles(string MainDirectoryPath)
{
    try
    {
        foreach (string dir in Directory.GetDirectories(MainDirectoryPath))
        {
            foreach (string file in Directory.GetFiles(dir))
            {
                string fileName = System.IO.Path.GetFileName(file);
                string fileExtenstion = Path.GetExtension(file);
                MessageBox.Show(fileExtenstion);
            }

            SearchVoiceFiles(dir);
        }
    }
    catch (System.Exception)
    {
        throw;
    }
}

Upload file from WinForm application to server

using BizArk.Core.Web; // http://bizark.codeplex.com/
var response = WebHelper.MakeRequest
                  ("http://Domain.com/Home/ReceiveAudio/",
                    new
                       {
                          wavFile = new FileInfo(e.FullPath)
                          //Test = "Hello",
                          //File1 = new UploadFile(@"text\plain", "file1.txt", 
                                   new MemoryStream(Encoding.UTF8.GetBytes("Hello "))),
                          //File2 = new FileInfo("MyFile.txt")
                        });

var result = response.ResultToString();

Working with FileSystemWatcher Class

private void ToggleMonitor(object sender, EventArgs e)
{
    // Create a new FileSystemWatcher object.
    FileSystemWatcher fsWatcher = new FileSystemWatcher();
    switch (btnToggleMonitor.Text)
    {
        //Start Monitoring…
        case startMonitoring:
            if (!txtMonitoringPath.Text.Equals(String.Empty))
            {
                fsWatcher.Path = txtMonitoringPath.Text;
                        
                // Set File Type Filter.
                fsWatcher.Filter = "*.*" or  "*.txt"

                // Monitor files and subdirectories.
                fsWatcher.IncludeSubdirectories = true;


                // Monitor all changes specified in the NotifyFilters.
                fsWatcher.NotifyFilter = NotifyFilters.Attributes |
                                            NotifyFilters.CreationTime |
                                            NotifyFilters.DirectoryName |
                                            NotifyFilters.FileName |
                                            NotifyFilters.LastAccess |
                                            NotifyFilters.LastWrite |
                                            NotifyFilters.Security |
                                            NotifyFilters.Size;
                        
                fsWatcher.EnableRaisingEvents = true;
                       
                // Raise Event handlers.
                fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
                fsWatcher.Created += new FileSystemEventHandler(OnCreated);
                fsWatcher.Deleted += new FileSystemEventHandler(OnDeleted);
                fsWatcher.Renamed += new RenamedEventHandler(OnRenamed);
                fsWatcher.Error += new ErrorEventHandler(OnError);

                btnToggleMonitor.Text = stopMonitoring;
                txtMonitoringPath.Enabled = false;
                txtFileType.Enabled = false;
            }
            break;

        // Stop Monitoring…
        case stopMonitoring:
        default:
            fsWatcher.EnableRaisingEvents = false;
            fsWatcher = null;
            btnToggleMonitor.Text = startMonitoring;
            txtMonitoringPath.Enabled = true;
            txtFileType.Enabled = true;
            break;
    }
}






 
// FileSystemWatcher – OnCreated Event Handler
public void OnCreated(object sender, FileSystemEventArgs e)
{
    // Add event details in listbox.
    this.Invoke((MethodInvoker)delegate { textbox.text(e.FullPath, e.ChangeType); });
}

// FileSystemWatcher – OnChanged Event Handler
public void OnChanged(object sender, FileSystemEventArgs e)
{
    //Do something.
}


// FileSystemWatcher – OnRenamed Event Handler
public void OnRenamed(object sender, RenamedEventArgs e)
{
     System.Threading.Thread.Sleep(6000);
     string oldPath = e.OldFullPath;
     string newPath = e.FullPath;
     string oldName = e.OldName;
     string newName = e.Name;
}

// FileSystemWatcher – OnDeleted Event Handler
public void OnDeleted(object sender, FileSystemEventArgs e)
{
//Do something
}

// FileSystemWatcher – OnError Event Handler
public void OnError(object sender, ErrorEventArgs e)
{
e.GetException().Message
}