Wednesday, 13 April 2016

Get and Set Private Properties using Reflection in C#

It's frustrating when you're using an API and some properties you requuire are set as private. This certainly was the case when attempting to resume a video using the YouTube V3 API the other day.

Here is a code snippet on how to set private properties using Reflection.
Code Snippet
  1. private static void SetPrivateProperty<T>(Object obj, string propertyName, object value)
  2. {
  3. var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  4. if (propertyInfo == null) return;
  5. propertyInfo.SetValue(obj, value, null);
  6. }
  7. private static object GetPrivateProperty<T>(Object obj, string propertyName)
  8. {
  9. if (obj == null) return null;
  10. var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  11. return propertyInfo == null ? null : propertyInfo.GetValue(obj, null);
  12. }
End of Code Snippet

Tuesday, 12 April 2016

MsgBox - A Better Winforms MessageBox in C#

Introduction

MsgBox is an enhanced solution to the in-built MessageBox class. It's designed so that the styles, features and behaviour mimic the in-built control with added features.

MsgBox allows a better Messagebox experience by allowing the following features:
- Do not display this message again
- Custom font styles and font colors
- Scrollbars for text which is too long

Using the code

MsgBox is used like a standard MessageBox object. There is a different return object which encapsulates the original DialogResult. This handles extra information which as whether the user clicked 'Do no display this message again'.

 

Simple Example

Code Snippet
  1. MsgBox.Show(this, &quot;Hello&quot;, &quot;Caption Text&quot;, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
End of Code Snippet

 

Custom Fonts

Code Snippet
  1. MsgBox.Show(this, &quot;Hello&quot;, &quot;Caption Text&quot;, MessageBoxButtons.OK, MessageBoxIcon.Information, true, new Font(&quot;Verdana&quot;, 12f, FontStyle.Bold), Color.Red);
End of Code Snippet

 

Long Text

Code Snippet
  1. MsgBox.Show(this, &quot;Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello&quot;, &quot;Caption Text&quot;, MessageBoxButtons.OK, MessageBoxIcon.Information, true, new Font(&quot;Verdana&quot;, 40f, FontStyle.Bold), Color.Blue);
End of Code Snippet

 

Handling the do not display message again checkbox

Code Snippet
  1. DialogResultNew res = MsgBox.Show(this, &quot;Hello&quot;, &quot;Caption Text&quot;, MessageBoxButtons.OK);
  2. if (res.DoNotDisplayMessageAgain) // Do something here
End of Code Snippet

Download


Download MsgBox Here

 

History

v1.0 - Initial write-up