Tuesday, February 14, 2012

[Csharp] Dynamic Property to Get Name of Property

In my project, I see a greatly function. I can help developer to get name of property as a string and know it right or wrong in debug or test.

Here is a demo:

   1:      public static class EntityHelper
   2:      {
   3:          public static dynamic GetProperties(this ClassDemo obj)
   4:          {
   5:              return GetDynaObject(obj);
   6:          }
   7:   
   8:          public static dynamic Properties(this Type type)
   9:          {
  10:              PropertyInfo[] properties = type.GetProperties();
  11:              Dictionary<string, string> propertyList = properties.ToDictionary(propertyInfo => propertyInfo.Name,
  12:                                                                                propertyInfo => propertyInfo.Name);
  13:              var myDyna = new DynamicUtility(propertyList, type.Name);
  14:              return myDyna;
  15:          }
  16:   
  17:          private static DynamicUtility GetDynaObject(object targetObject)
  18:          {
  19:              PropertyInfo[] properties = targetObject.GetType().GetProperties();
  20:              Dictionary<string, string> propertyList = properties.ToDictionary(propertyInfo => propertyInfo.Name,
  21:                                                                                propertyInfo => propertyInfo.Name);
  22:              var myDyna = new DynamicUtility(propertyList, targetObject.GetType().Name);
  23:              return myDyna;
  24:          }
  25:      }
  26:   
  27:      public class DynamicUtility : DynamicObject
  28:      {
  29:          private readonly string _baseType;
  30:   
  31:          private readonly Dictionary<string, string> _properties;
  32:   
  33:          public DynamicUtility(Dictionary<string, string> properties, string baseType)
  34:          {
  35:              _properties = properties;
  36:              _baseType = baseType;
  37:          }
  38:   
  39:          public override bool TryGetMember(GetMemberBinder binder, out object result)
  40:          {
  41:              if (_properties.ContainsKey(binder.Name))
  42:              {
  43:                  result = _properties[binder.Name];
  44:                  return true;
  45:              }
  46:              throw new Exception(string.Format("Property '{0}.{1}' is not existed.", _baseType, binder.Name));
  47:          }
  48:      }

And how to run it:
   1:  public class ClassDemo
   2:      {
   3:          public string StringProperty { get; set; }
   4:          public int IntProperty { get; set; }
   5:          public float FloatProperty { get; set; }
   6:   
   7:          private dynamic _properties;
   8:          public virtual dynamic Properties
   9:          {
  10:              get
  11:              {
  12:                  _properties = _properties ?? this.GetProperties();
  13:                  return _properties;
  14:              }
  15:          }
  16:      }
  17:   
  18:      class Program
  19:      {
  20:          static void Main(string[] args)
  21:          {
  22:              var classDemo = new ClassDemo();
  23:   
  24:              Console.WriteLine(classDemo.Properties.StringProperty);
  25:              Console.WriteLine(classDemo.Properties.IntProperty);
  26:              Console.WriteLine(classDemo.Properties.FloatProperty);
  27:   
  28:              Console.ReadKey(true);
  29:          }
  30:      }

So when we use it. Imagine you are working on a big project, with many functions and files. So some functions' parameters are a string (it's an property of object class). So, in normally, you can use constant string like this "MyProperty". Then all your Unit Test will pass, although you add wrong string property. Dynamic property now is useful. Can you agree!
Enjoy it!

Today I don't feel like doing anything

Today I don't feel like doing anything...
No, it's not me. It's lyric of "The lazy song", this is nice song I here every morning. In a bad weather day, I decide to get up early everyday and do exercise. I remember for sure I decided it many times, I didn't do it like I want.
Now, it's the first time I found a right things can help me make "dream become true". It's my project management, he sits next to me.
I try to get up early and go to company, start my great word day.
Today is like this. Thank you.

Sunday, February 12, 2012

[English everyday] Cannot join in blog at home

Now, I am at home.
Maybe you feel it's funny, I can browse manager page of my blog, but I cannot browse view page. I am an IT man, I find it so many time in the internet and you see I haven't any solution.
I feel quite angrily, quite boring. Then I will come back to study English, I don't think about it again.

 Now, I think about how a person can use English. You can see, in a English country, a silly boy really can hear and talk English in correct. Why I am not? I really found some reasons, maybe I think it defend for my lazy :( Oh, some reasons like:
- I don't live in a English country. Almost people around me communication with Vietnamese.
- I am adult, my experience make me hard to study English. Sometime intelligent is not good :))
- English is difficult study language. Maybe, It have many exception in grammar. Too popular, I mean it's not standard, I hard to hear people in each other country talking with not pure English.
- Why English people are rapidly talking. If you try to compare talking speed with my country, you will see many differences. How I listen to, yes, how I am talking like this.
- The last think, training English is in my country so bad. Focus to grammar, I think it lose right way.
...
Oh, you can help me add more reasons, maybe I forgot them. But I don't this post to complain, it's an action I change myself in study English everyday.

Thank for free time to read it!



Monday, February 6, 2012

[Csharp] Play Audio use winmm.dll

Today, I really early go to my company. It's a nice day.

In this post, I want show you a class C# to play audio use API winmm.dll, here is code snippet:



   1:      public class AudioPlayHelper
   2:      {
   3:          [DllImport("winmm.dll")]
   4:          private static extern long mciSendString(
   5:              string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);
   6:   
   7:          #region Play Audio
   8:   
   9:          public static void Play(string fileName, bool repeat)
  10:          {
  11:              mciSendString("open \"" + fileName + "\" type mpegvideo alias MediaFile",
  12:                          null, 0, IntPtr.Zero);
  13:   
  14:              mciSendString("play MediaFile" + (repeat ? " repeat" : String.Empty), null,
  15:                            0, IntPtr.Zero);
  16:          }
  17:   
  18:          public static void Play(byte[] embeddedResource, bool repeat)
  19:          {
  20:              ExtractResource(embeddedResource, Path.GetTempPath() + "resource.tmp");
  21:              mciSendString("open \"" + Path.GetTempPath() + "resource.tmp" +
  22:                            "\" type mpegvideo alias MediaFile", null, 0, IntPtr.Zero);
  23:              mciSendString("play MediaFile" + (repeat ? " repeat" : String.Empty),
  24:                            null, 0, IntPtr.Zero);
  25:          }
  26:   
  27:          public static void Pause()
  28:          {
  29:              mciSendString("stop MediaFile", null, 0, IntPtr.Zero);
  30:          }
  31:   
  32:          public static void Stop()
  33:          {
  34:              mciSendString("close MediaFile", null, 0, IntPtr.Zero);
  35:          }
  36:   
  37:          private static void ExtractResource(IEnumerable<byte> res, string filePath)
  38:          {
  39:              if (File.Exists(filePath)) return;
  40:   
  41:              var fs = new FileStream(filePath, FileMode.OpenOrCreate);
  42:              var bw = new BinaryWriter(fs);
  43:   
  44:              foreach (var b in res) bw.Write(b);
  45:   
  46:              bw.Close();
  47:              fs.Close();
  48:          }
  49:   
  50:          #endregion
  51:   
  52:          #region Record
  53:   
  54:          public static void Record()
  55:          {
  56:              mciSendString("open new type waveaudio alias MediaFile", null, 0, IntPtr.Zero);//cannot record mp3
  57:              mciSendString("record MediaFile", null, 0, IntPtr.Zero);
  58:          }
  59:   
  60:          public static void Save(string fileName)
  61:          {
  62:              mciSendString("save MediaFile \"" + fileName + "\"", null, 0, IntPtr.Zero); //extension .wav
  63:              mciSendString("close MediaFile ", null, 0, IntPtr.Zero);
  64:          }
  65:   
  66:          #endregion
  67:      }
Before add this code you need using System.Runtime.InteropServices;
This application will be play mp3 sound and record wav sound by easy call static function.
Hope you enjoy it!

Friday, February 3, 2012

[Csharp] Tip/Trick to select text in TextBox

Today, I write an application to load long text document on TextBox. Working with long text, so I need to create some alternative functions such as: search text, go to line. All function is around how to select text on TextBox. Here is some code snippet to do it:

* Search on textbox: keyword is your input


   1:                  textBox.Focus();                
   2:                  textBox.SelectionStart = index;
   3:                  textBox.SelectionLength = keyword.Length;
   4:                  textBox.ScrollToCaret();

 * Go to line: lineToGo is your input


   1:              textBox.Focus();
   2:              textBox.SelectionLength = 0;
   3:              textBox.SelectionStart = textBox.GetFirstCharIndexFromLine(lineToGo);
   4:              textBox.ScrollToCaret();

* Select all and copy text


   1:              textBox.Focus();
   2:              textBox.SelectAll();
   3:   
   4:              if (string.IsNullOrEmpty(textBox.SelectedText)) return;
   5:              Clipboard.SetText(textBox.SelectedText);
   6:              textBox.Focus();
OK, I think it's so easy and we will meet it many times in code.
Thank to enjoy!

*Update:
Get number of lines of selected text


   1:          private static int GetSelectedLines(TextBox textBox)
   2:          {
   3:              if (textBox.SelectionLength == 0) return 0;
   4:   
   5:              return textBox.GetLineFromCharIndex(textBox.GetFirstCharIndexOfCurrentLine()) -
   6:                     textBox.GetLineFromCharIndex(textBox.SelectionStart);
   7:          }
:)