using System.Configuration; using System; namespace PawJershauge.Extensions { namespace Configuration { /// <summary> /// Provides Extension for the Configuration manager /// </summary> public static class ConfigurationExtensions { #region SettingsPropertyValue /// <summary> /// Get the string value of the property /// </summary> /// <param name="obj">SettingsPropertyValue object to extend the method onto.</param> /// <returns>null if value is null; else the string representing tha value.</returns> /// <remarks>Developed by Paw Jershauge (Check my Blog fore more C# tips: [C# and I] Url: http://pawjershauge.blogspot.com)</remarks> public static string GetValue(this SettingsPropertyValue obj) { return obj.PropertyValue == null ? null : obj.PropertyValue.ToString(); } /// <summary> /// Get the T value of the property /// </summary> /// <typeparam name="T">Generic type to get as</typeparam> /// <param name="obj">SettingsPropertyValue object to extend the method onto.</param> /// <returns>The T value of the property, if the value is null, then default(T) is returned.</returns> /// <remarks>Developed by Paw Jershauge (Check my Blog fore more C# tips: [C# and I] Url: http://pawjershauge.blogspot.com)</remarks> public static T GetValue<T>(this SettingsPropertyValue obj) where T : struct { if (obj.PropertyValue == null) return default(T); else return (T)Convert.ChangeType(obj.PropertyValue, typeof(T)); } /// <summary> /// Tries to get the T value of the property. /// </summary> /// <typeparam name="T">Generic type to get as</typeparam> /// <param name="obj">SettingsPropertyValue object to extend the method onto.</param> /// <param name="value">if return value is true, the out value parameter has the T value of the property</param> /// <returns>True if the value is not null, else False.</returns> /// <remarks>Developed by Paw Jershauge (Check my Blog fore more C# tips: [C# and I] Url: http://pawjershauge.blogspot.com)</remarks> public static bool TryGetValue<T>(this SettingsPropertyValue obj, out T value) where T : struct { if (obj.PropertyValue == null) { value = default(T); return false; } else { value = (T)Convert.ChangeType(obj.PropertyValue, typeof(T)); return true; } } #endregion #region SettingsPropertyValueCollection /// <summary> /// Checks if the collection contains the key. /// </summary> /// <param name="obj">SettingsPropertyValueCollection object to extend the method onto.</param> /// <param name="name">Name of the key to lookup</param> /// <returns>true if the key exists else false.</returns> /// <remarks>Developed by Paw Jershauge (Check my Blog fore more C# tips: [C# and I] Url: http://pawjershauge.blogspot.com)</remarks> public static bool ContainsKey(this SettingsPropertyValueCollection obj, string name) { if (obj == null || obj.Count == 0) return false; foreach (SettingsPropertyValue item in obj) { if (item.Name == name) return true; } return false; } /// <summary> /// Get the string value of the property /// </summary> /// <param name="obj">SettingsPropertyValueCollection object to extend the method onto.</param> /// <returns>null if value is null; else the string representing tha value.</returns> /// <remarks>Developed by Paw Jershauge (Check my Blog fore more C# tips: [C# and I] Url: http://pawjershauge.blogspot.com)</remarks> public static string GetValue(this SettingsPropertyValueCollection obj, string name) { if (!obj.ContainsKey(name)) return null; return obj[name].GetValue(); } /// <summary> /// Get the T value of the property /// </summary> /// <typeparam name="T">Generic type to get as</typeparam> /// <param name="obj">SettingsPropertyValueCollection object to extend the method onto.</param> /// <returns>The T value of the property, if the value is null, then default(T) is returned.</returns> /// <remarks>Developed by Paw Jershauge (Check my Blog fore more C# tips: [C# and I] Url: http://pawjershauge.blogspot.com)</remarks> public static T GetValue<T>(this SettingsPropertyValueCollection obj, string name) where T : struct { if (!obj.ContainsKey(name)) return default(T); return obj[name].GetValue<T>(); } /// <summary> /// Tries to get the T value of the property. /// </summary> /// <typeparam name="T">Generic type to get as</typeparam> /// <param name="obj">SettingsPropertyValueCollection object to extend the method onto.</param> /// <param name="value">if return value is true, the out value parameter has the T value of the property</param> /// <returns>True if the value is not null, else False.</returns> /// <remarks>Developed by Paw Jershauge (Check my Blog fore more C# tips: [C# and I] Url: http://pawjershauge.blogspot.com)</remarks> public static bool TryGetValue<T>(this SettingsPropertyValueCollection obj, string name, out T value) where T : struct { if (!obj.ContainsKey(name)) { value = default(T); return false; } return obj[name].TryGetValue(out value); } #endregion } } }
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
June 11, 2012
SettingsPropertyValue and SettingsPropertyValueCollection Extensions
I wrote some Configuration Extension, hope you like em ;)
Etiketter:
.Net Framework,
C#,
Extension,
Framework 3.5,
Generic
January 19, 2011
8 ICustomAttributeProvider Extensions
Following Extensions Methods are in the code below. hope you like em ;)
The source code is also available on MSDN here: http://msdn.microsoft.com/en-us/library/system.reflection.icustomattributeprovider.getcustomattributes(v=vs.90).aspx
The source code is also available on MSDN here: http://msdn.microsoft.com/en-us/library/system.reflection.icustomattributeprovider.getcustomattributes(v=vs.90).aspx
- T GetCustomAttribute(bool)
- T GetCustomAttribute()
- T[] GetCustomAttributes(bool)
- T[] GetCustomAttributes()
- bool TryGetCustomAttribute(bool, out T)
- bool TryGetCustomAttribute(out T)
- bool TryGetCustomAttributes(bool, out T[])
- bool TryGetCustomAttributes(out T[])
using System; using System.Reflection; namespace Extensions { public static class Reflection { #region ICustomAttributeProvider /// <summary> /// Returns the first custom attributes defined on this member, identified by type T, or null if there are no custom attributes of that type. /// </summary> /// <typeparam name="T">Type of the custom attributes to extract.</typeparam> /// <param name="customAttributeProvider">Provider to extract the custom attribute from.</param> /// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param> /// <returns>An single custom attributes located on index zero in the custom attribute array, or null.</returns> /// <remarks>Developered by Paw Jershauge for rapid Custom Attribute extraction.</remarks> public static T GetCustomAttribute<T>(this ICustomAttributeProvider customAttributeProvider, bool inherit) where T : Attribute { T outval = null; if (TryGetCustomAttribute<T>(customAttributeProvider, inherit, out outval)) return outval; return null; } /// <summary> /// Returns the first custom attributes defined on this member, identified by type T, or null if there are no custom attributes of that type. /// </summary> /// <typeparam name="T">Type of the custom attributes to extract.</typeparam> /// <param name="customAttributeProvider">Provider to extract the custom attribute from.</param> /// <returns>An single custom attributes located on index zero in the custom attribute array, or null.</returns> /// <remarks>Developered by Paw Jershauge for rapid Custom Attribute extraction.</remarks> public static T GetCustomAttribute<T>(this ICustomAttributeProvider customAttributeProvider) where T : Attribute { T outval = null; if (TryGetCustomAttribute<T>(customAttributeProvider, true, out outval)) return outval; return null; } /// <summary> /// Returns an array of custom attributes defined on this member, identified by type T, or an empty array if there are no custom attributes of that type. /// </summary> /// <typeparam name="T">Type of the custom attributes to extract.</typeparam> /// <param name="customAttributeProvider">Provider to extract the custom attribute from.</param> /// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param> /// <returns>An array of custom attributes, or an empty custom attribute array.</returns> /// <remarks>Developered by Paw Jershauge for rapid Custom Attribute extraction.</remarks> public static T[] GetCustomAttributes<T>(this ICustomAttributeProvider customAttributeProvider, bool inherit) where T : Attribute { T[] outval = null; if (TryGetCustomAttributes<T>(customAttributeProvider, inherit, out outval)) return outval; return new T[0]; } /// <summary> /// Returns an array of custom attributes defined on this member, identified by type T, or an empty array if there are no custom attributes of that type. /// </summary> /// <typeparam name="T">Type of the custom attributes to extract.</typeparam> /// <param name="customAttributeProvider">Provider to extract the custom attribute from.</param> /// <returns>An array of custom attributes, or an empty custom attribute array.</returns> /// <remarks>Developered by Paw Jershauge for rapid Custom Attribute extraction.</remarks> public static T[] GetCustomAttributes<T>(this ICustomAttributeProvider customAttributeProvider) where T : Attribute { T[] outval = null; if (TryGetCustomAttributes<T>(customAttributeProvider, true, out outval)) return outval; return new T[0]; } /// <summary> /// Extracts the first custom attributes defined on this member, identified by type T, or null if there are no custom attributes of that type. /// A return value indicates whether the extraction was successfull or failed. /// </summary> /// <typeparam name="T">Type of the custom attributes to extract.</typeparam> /// <param name="customAttributeProvider">Provider to extract the custom attribute from.</param> /// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param> /// <param name="value">When this method returns, contains the custom attribute value contained in customAttributeProvider, if the extraction succeeded, or null if the extraction failed. /// The extraction fails if the customAttributeProvider parameter is null, or customAttributeProvider does not contain the custom attribute.</param> /// <returns>true if the extraction was successfully; otherwise, false.</returns> /// <remarks>Developered by Paw Jershauge for rapid Custom Attribute extraction.</remarks> public static bool TryGetCustomAttribute<T>(this ICustomAttributeProvider customAttributeProvider, bool inherit, out T value) where T : Attribute { value = null; if (customAttributeProvider == null) return false; object[] attributes = customAttributeProvider.GetCustomAttributes(typeof(T), inherit); if (attributes == null) return false; if (attributes.Length == 0) return false; value = (T)attributes[0]; return true; } /// <summary> /// Extracts the first custom attributes defined on this member, identified by type T, or null if there are no custom attributes of that type. /// A return value indicates whether the extraction was successfull or failed. /// </summary> /// <typeparam name="T">Type of the custom attributes to extract.</typeparam> /// <param name="customAttributeProvider">Provider to extract the custom attribute from.</param> /// <param name="value">When this method returns, contains the custom attribute value contained in customAttributeProvider, if the extraction succeeded, or null if the extraction failed. /// The extraction fails if the customAttributeProvider parameter is null, or customAttributeProvider does not contain the custom attribute.</param> /// <returns>true if the extraction was successfully; otherwise, false.</returns> /// <remarks>Developered by Paw Jershauge for rapid Custom Attribute extraction.</remarks> public static bool TryGetCustomAttribute<T>(this ICustomAttributeProvider customAttributeProvider, out T value) where T : Attribute { return TryGetCustomAttribute<T>(customAttributeProvider, true, out value); } /// <summary> /// Extracts an array of custom attributes defined on this member, identified by type T, or an empty array if there are no custom attributes of that type. /// A return value indicates whether the extraction was successfull or failed. /// </summary> /// <typeparam name="T">Type of the custom attributes to extract.</typeparam> /// <param name="customAttributeProvider">Provider to extract the custom attribute from.</param> /// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param> /// <param name="value">When this method returns, contains the custom attribute array contained in customAttributeProvider, if the extraction succeeded, or null if the extraction failed. /// The extraction fails if the customAttributeProvider parameter is null, or customAttributeProvider does not contain the custom attribute.</param> /// <returns>true if the extraction was successfully; otherwise, false.</returns> /// <remarks>Developered by Paw Jershauge for rapid Custom Attribute extraction.</remarks> public static bool TryGetCustomAttributes<T>(this ICustomAttributeProvider customAttributeProvider, bool inherit, out T[] value) where T : Attribute { value = new T[0]; if (customAttributeProvider == null) return false; object[] attributes = customAttributeProvider.GetCustomAttributes(typeof(T), inherit); if (attributes == null) return false; if (attributes.Length == 0) return false; value = new T[attributes.Length]; for (int i = 0; i < attributes.Length; i++) value[i] = attributes[0] as T; return true; } /// <summary> /// Extracts an array of custom attributes defined on this member, identified by type T, or an empty array if there are no custom attributes of that type. /// A return value indicates whether the extraction was successfull or failed. /// </summary> /// <typeparam name="T">Type of the custom attributes to extract.</typeparam> /// <param name="customAttributeProvider">Provider to extract the custom attribute from.</param> /// <param name="value">When this method returns, contains the custom attribute array contained in customAttributeProvider, if the extraction succeeded, or null if the extraction failed. /// The extraction fails if the customAttributeProvider parameter is null, or customAttributeProvider does not contain the custom attribute.</param> /// <returns>true if the extraction was successfully; otherwise, false.</returns> /// <remarks>Developered by Paw Jershauge for rapid Custom Attribute extraction.</remarks> public static bool TryGetCustomAttributes<T>(this ICustomAttributeProvider customAttributeProvider, out T[] value) where T : Attribute { return TryGetCustomAttributes<T>(customAttributeProvider, true, out value); } #endregion } }
March 12, 2010
DateTime Extensions
Some Extensions i grabbed along the way or made up. I often have use for som simple extension, so heres my DateTime Extensions
DateTime Examples:
Having the following demo Variable called DemoDate set to 2010/6/29 13:15:59.321 ( Tuesday 29 of June ) we will test the Extensions I've made.
Just to illustrate heres the calendar for June & July in 2010.
DateTime Examples:
Having the following demo Variable called DemoDate set to 2010/6/29 13:15:59.321 ( Tuesday 29 of June ) we will test the Extensions I've made.
DateTime DemoDate = new DateTime(2010, 6, 29, 13, 15, 59, 321); // representing an datetime equal to 2010/6/29 13:15:59.321 ( Tuesday 29 of June ) DemoDate.AddFinancialDays(4) // returns 2010-07-05 13:15:59.321 DemoDate.BeginningOfDay() // returns 2010-06-29 00:00:00.000 DemoDate.BeginningOfMonth() // returns 2010-06-01 00:00:00.000 DemoDate.Between(new DateTime(2010, 3, 1), new DateTime(2010, 7, 1)) // returns True DemoDate.CountFinancialDays(new DateTime(2010, 7, 9, 12, 0, 0, 0)) // returns 7 DemoDate.CountFinancialDays(new DateTime(2010, 7, 9, 14, 0, 0, 0)) // returns 8 DemoDate.EndOfDay() // returns 2010-06-29 23:59:59.999 DemoDate.EndOfMonth() // returns 2010-06-30 23:59:59.999 DemoDate.FindClosestWeekDay() // returns 2010-06-29 13:15:59.321 DemoDate.FirstDayOfWeekInMonth(DayOfWeek.Thursday) // returns 2010-06-03 00:00:00.000 DemoDate.FirstWeekDayOfMonth() // returns 2010-06-01 00:00:00.000 DemoDate.GetDateByWeek(45, DayOfWeek.Wednesday) // returns 2010-11-10 00:00:00.000 DemoDate.IsWeekend() // returns False DemoDate.LastDayOfWeekInMonth(DayOfWeek.Saturday) // returns 2010-06-26 00:00:00.000 DemoDate.LastWeekDayOfMonth() // returns 2010-06-30 00:00:00.000 DemoDate.Next(DayOfWeek.Monday) // returns 2010-07-05 13:15:59.321 DemoDate.Previous(DayOfWeek.Friday) // returns 2010-06-25 13:15:59.321 DemoDate.Quarter() // returns 2 DemoDate.SetDate(2020) // returns 2020-06-29 13:15:59.321 NOTE: although we only wanted to set the month, the day will shift also, since the 29 of february 2019 does not exist. DemoDate.SetDate(2019, 2) // returns 2019-03-01 13:15:59.321 DemoDate.SetDate(2021, 3, 12) // returns 2021-03-12 13:15:59.321 DemoDate.SetTime(20) // returns 2010-06-29 20:15:59.321 DemoDate.SetTime(21, 35) // returns 2010-06-29 21:35:59.321 DemoDate.SetTime(17, 45, 3) // returns 2010-06-29 17:45:03.321 DemoDate.SetTime(9, 12, 59, 600) // returns 2010-06-29 09:12:59.600 DemoDate.ToMicrosoftNumber() // returns 1214745359,321
Just to illustrate heres the calendar for June & July in 2010.
| June 2010 | |||||||
| Week | Mon | Tue | Wen | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|---|
| 22 | 31 | 1 | 2 | 3 | 4 | 5 | 6 |
| 23 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 24 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 25 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 26 | 28 | 29 | 30 | 1 | 2 | 3 | 4 |
| July 2010 | |||||||
| Week | Mon | Tue | Wen | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|---|
| 26 | 28 | 29 | 30 | 1 | 2 | 3 | 4 |
| 27 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 28 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 29 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 30 | 26 | 27 | 28 | 29 | 30 | 31 | 1 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; using PawJershauge.Extensions.ValueTypes; namespace PawJershauge.Extensions { namespace DateAndTime { public static class DateTimeExtensions { /// <summary> /// Returns the first day of week with in the month. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="dow">What day of week to find the first one of in the month.</param> /// <returns>Returns DateTime object that represents the first day of week with in the month.</returns> public static DateTime FirstDayOfWeekInMonth(this DateTime obj, DayOfWeek dow) { DateTime firstDay = new DateTime(obj.Year, obj.Month, 1); int diff = firstDay.DayOfWeek - dow; if (diff > 0) diff -= 7; return firstDay.AddDays(diff * -1); } /// <summary> /// Returns the first weekday (Financial day) of the month /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns DateTime object that represents the first weekday (Financial day) of the month</returns> public static DateTime FirstWeekDayOfMonth(this DateTime obj) { DateTime firstDay = new DateTime(obj.Year, obj.Month, 1); for (int i = 0; i < 7; i++) { if (firstDay.AddDays(i).DayOfWeek != DayOfWeek.Saturday && firstDay.AddDays(i).DayOfWeek != DayOfWeek.Sunday) return firstDay.AddDays(i); } return firstDay; } /// <summary> /// Returns the last day of week with in the month. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="dow">What day of week to find the last one of in the month.</param> /// <returns>Returns DateTime object that represents the last day of week with in the month.</returns> public static DateTime LastDayOfWeekInMonth(this DateTime obj, DayOfWeek dow) { DateTime lastDay = new DateTime(obj.Year, obj.Month, DateTime.DaysInMonth(obj.Year, obj.Month)); DayOfWeek lastDow = lastDay.DayOfWeek; int diff = dow - lastDow; if (diff > 0) diff -= 7; return lastDay.AddDays(diff); } /// <summary> /// Returns the last weekday (Financial day) of the month /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns DateTime object that represents the last weekday (Financial day) of the month</returns> public static DateTime LastWeekDayOfMonth(this DateTime obj) { DateTime lastDay = new DateTime(obj.Year, obj.Month, DateTime.DaysInMonth(obj.Year, obj.Month)); for (int i = 0; i < 7; i++) { if (lastDay.AddDays(i * -1).DayOfWeek != DayOfWeek.Saturday && lastDay.AddDays(i * -1).DayOfWeek != DayOfWeek.Sunday) return lastDay.AddDays(i * -1); } return lastDay; } /// <summary> /// Returns the closest Weekday (Financial day) Date /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns the closest Weekday (Financial day) Date</returns> public static DateTime FindClosestWeekDay(this DateTime obj) { if (obj.DayOfWeek == DayOfWeek.Saturday) return obj.AddDays(-1); if (obj.DayOfWeek == DayOfWeek.Sunday) return obj.AddDays(1); else return obj; } /// <summary> /// Returns the very end of the given month (the last millisecond of the last hour for the given date) /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns the very end of the given month (the last millisecond of the last hour for the given date)</returns> public static DateTime EndOfMonth(this DateTime obj) { return new DateTime(obj.Year, obj.Month, DateTime.DaysInMonth(obj.Year, obj.Month), 23, 59, 59, 999); } /// <summary> /// Returns the Start of the given month (the fist millisecond of the given date) /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns the Start of the given month (the fist millisecond of the given date)</returns> public static DateTime BeginningOfMonth(this DateTime obj) { return new DateTime(obj.Year, obj.Month, 1, 0, 0, 0, 0); } /// <summary> /// Returns the very end of the given day (the last millisecond of the last hour for the given date) /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns the very end of the given day (the last millisecond of the last hour for the given date)</returns> public static DateTime EndOfDay(this DateTime obj) { return obj.SetTime(23, 59, 59, 999); } /// <summary> /// Returns the Start of the given day (the fist millisecond of the given date) /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns the Start of the given day (the fist millisecond of the given date)</returns> public static DateTime BeginningOfDay(this DateTime obj) { return obj.SetTime(0, 0, 0, 0); } /// <summary> /// Returns a given datetime according to the week of year and the specified day within the week. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="week">A number of whole and fractional weeks. The value parameter can only be positive.</param> /// <param name="dayofweek">A DayOfWeek to find in the week</param> /// <returns>A DateTime whose value is the sum according to the week of year and the specified day within the week.</returns> public static DateTime GetDateByWeek(this DateTime obj, int week, DayOfWeek dayofweek) { if (week > 0 && week < 54) { DateTime FirstDayOfyear = new DateTime(obj.Year, 1, 1); int daysToFirstCorrectDay = (((int)dayofweek - (int)FirstDayOfyear.DayOfWeek) + 7) % 7; return FirstDayOfyear.AddDays(7 * (week - 1) + daysToFirstCorrectDay); } else return obj; } private static int Sub(DayOfWeek s, DayOfWeek e) { if ((s - e) > 0) return (s - e) - 7; if ((s - e) == 0) return -7; return (s - e); } /// <summary> /// Returns first next occurence of specified DayOfTheWeek /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="day">A DayOfWeek to find the next occurence of</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the enum value represented by the day.</returns> public static DateTime Next(this DateTime obj, DayOfWeek day) { return obj.AddDays(Sub(obj.DayOfWeek, day) * -1); } /// <summary> /// Returns next "first" occurence of specified DayOfTheWeek /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="day">A DayOfWeek to find the previous occurence of</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the enum value represented by the day.</returns> public static DateTime Previous(this DateTime obj, DayOfWeek day) { return obj.AddDays(Sub(day, obj.DayOfWeek)); } private static DateTime SetDateWithChecks(DateTime obj, int year, int month, int day, int? hour, int? minute, int? second, int? millisecond) { DateTime StartDate; if (year == 0) StartDate = new DateTime(obj.Year, 1, 1, 0, 0, 0, 0); else { if (DateTime.MaxValue.Year < year) StartDate = new DateTime(DateTime.MinValue.Year, 1, 1, 0, 0, 0, 0); else if (DateTime.MinValue.Year > year) StartDate = new DateTime(DateTime.MaxValue.Year, 1, 1, 0, 0, 0, 0); else StartDate = new DateTime(year, 1, 1, 0, 0, 0, 0); } if (month == 0) StartDate = StartDate.AddMonths(obj.Month - 1); else StartDate = StartDate.AddMonths(month - 1); if (day == 0) StartDate = StartDate.AddDays(obj.Day - 1); else StartDate = StartDate.AddDays(day - 1); if (!hour.HasValue) StartDate = StartDate.AddHours(obj.Hour); else StartDate = StartDate.AddHours(hour.Value); if (!minute.HasValue) StartDate = StartDate.AddMinutes(obj.Minute); else StartDate = StartDate.AddMinutes(minute.Value); if (!second.HasValue) StartDate = StartDate.AddSeconds(obj.Second); else StartDate = StartDate.AddSeconds(second.Value); if (!millisecond.HasValue) StartDate = StartDate.AddMilliseconds(obj.Millisecond); else StartDate = StartDate.AddMilliseconds(millisecond.Value); return StartDate; } /// <summary> /// Returns the original DateTime with Hour part changed to supplied hour parameter /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="hour">A number of whole and fractional hours. The value parameter can be negative or positive.</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the numbers represented by the parameters.</returns> public static DateTime SetTime(this DateTime obj, int hour) { return SetDateWithChecks(obj, 0, 0, 0, hour, null, null, null); } /// <summary> /// Returns the original DateTime with Hour and Minute parts changed to supplied hour and minute parameters /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="hour">A number of whole and fractional hours. The value parameter can be negative or positive.</param> /// <param name="minute">A number of whole and fractional minutes. The value parameter can be negative or positive.</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the numbers represented by the parameters.</returns> public static DateTime SetTime(this DateTime obj, int hour, int minute) { return SetDateWithChecks(obj, 0, 0, 0, hour, minute, null, null); } /// <summary> /// Returns the original DateTime with Hour, Minute and Second parts changed to supplied hour, minute and second parameters /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="hour">A number of whole and fractional hours. The value parameter can be negative or positive.</param> /// <param name="minute">A number of whole and fractional minutes. The value parameter can be negative or positive.</param> /// <param name="second">A number of whole and fractional seconds. The value parameter can be negative or positive.</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the numbers represented by the parameters.</returns> public static DateTime SetTime(this DateTime obj, int hour, int minute, int second) { return SetDateWithChecks(obj, 0, 0, 0, hour, minute, second, null); } /// <summary> /// Returns the original DateTime with Hour, Minute, Second and Millisecond parts changed to supplied hour, minute, second and millisecond parameters /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="hour">A number of whole and fractional hours. The value parameter can be negative or positive.</param> /// <param name="minute">A number of whole and fractional minutes. The value parameter can be negative or positive.</param> /// <param name="second">A number of whole and fractional seconds. The value parameter can be negative or positive.</param> /// <param name="millisecond">A number of whole and fractional milliseconds. The value parameter can be negative or positive.</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the numbers represented by the parameters.</returns> public static DateTime SetTime(this DateTime obj, int hour, int minute, int second, int millisecond) { return SetDateWithChecks(obj, 0, 0, 0, hour, minute, second, millisecond); } /// <summary> /// Returns DateTime with changed Year part /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="year">A number of whole and fractional years. The value parameter can be negative or positive.</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the numbers represented by the parameters.</returns> public static DateTime SetDate(this DateTime obj, int year) { return SetDateWithChecks(obj, year, 0, 0, null, null, null, null); } /// <summary> /// Returns DateTime with changed Year and Month part /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="year">A number of whole and fractional years. The value parameter can be negative or positive.</param> /// <param name="month">A number of whole and fractional month. The value parameter can be negative or positive.</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the numbers represented by the parameters.</returns> public static DateTime SetDate(this DateTime obj, int year, int month) { return SetDateWithChecks(obj, year, month, 0, null, null, null, null); } /// <summary> /// Returns DateTime with changed Year, Month and Day part /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="year">A number of whole and fractional years. The value parameter can be negative or positive.</param> /// <param name="month">A number of whole and fractional month. The value parameter can be negative or positive.</param> /// <param name="day">A number of whole and fractional day. The value parameter can be negative or positive.</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the numbers represented by the parameters.</returns> public static DateTime SetDate(this DateTime obj, int year, int month, int day) { return SetDateWithChecks(obj, year, month, day, null, null, null, null); } /// <summary> /// Adds the specified number of financials days to the value of this instance. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="days">A number of whole and fractional financial days. The value parameter can be negative or positive.</param> /// <returns>A DateTime whose value is the sum of the date and time represented by this instance and the number of financial days represented by days.</returns> public static DateTime AddFinancialDays(this DateTime obj, int days) { int addint = Math.Sign(days); for (int i = 0; i < (Math.Sign(days) * days); i++) { do { obj = obj.AddDays(addint); } while (obj.IsWeekend()); } return obj; } /// <summary> /// Calculate Financial days between two dates. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="otherdate">End or start date to calculate to or from.</param> /// <returns>Amount of financial days between the two dates</returns> public static int CountFinancialDays(this DateTime obj, DateTime otherdate) { TimeSpan ts = (otherdate - obj); int addint = Math.Sign(ts.Days); int unsigneddays = (Math.Sign(ts.Days) * ts.Days); int businessdays = 0; for (int i = 0; i < unsigneddays; i++) { obj = obj.AddDays(addint); if (!obj.IsWeekend()) businessdays++; } return businessdays; } /// <summary> /// Converts any datetime to the amount of seconds from 1972.01.01 00:00:00 /// Microsoft sometimes uses the amount of seconds from 1972.01.01 00:00:00 to indicate an datetime. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Total seconds past since 1972.01.01 00:00:00</returns> public static double ToMicrosoftNumber(this DateTime obj) { return (obj - new DateTime(1972, 1, 1, 0, 0, 0, 0)).TotalSeconds; } /// <summary> /// Returns true if the day is Saturday or Sunday /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>boolean value indicating if the date is a weekend</returns> public static bool IsWeekend(this DateTime obj) { return (obj.DayOfWeek == DayOfWeek.Saturday || obj.DayOfWeek == DayOfWeek.Sunday); } /// <summary> /// Returns true if the date is between or equal to one of the two values. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <param name="startvalue">Start date to check for</param> /// <param name="endvalue">End date to check for</param> /// <returns>boolean value indicating if the date is between or equal to one of the two values</returns> public static bool Between(this DateTime obj, DateTime startDate, DateTime endDate) { return obj.Ticks.Between(startDate.Ticks, endDate.Ticks); } /// <summary> /// Get the quarter that the datetime is in. /// </summary> /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param> /// <returns>Returns 1 to 4 that represenst the quarter that the datetime is in.</returns> public static int Quarter(this DateTime obj) { return ((obj.Month - 1) / 3) + 1; } } } }
Etiketter:
C#,
DateTime,
Extension,
Framework 3.5,
Managed types
March 5, 2010
The missing Generic CancelEventHandler<T> Delegate in the BCL
How to make an Generic implementation of an cancel event handler
/// <summary> /// Represents the method that handles a cancelable event. /// </summary> /// <typeparam name="TCancelEventArgs">The type specifier for the event.</typeparam> /// <param name="sender">The source of the event.</param> /// <param name="e">A CancelChangingEventArg<T> that contains the event data.</param> [Serializable] [System.Security.Permissions.HostProtection(System.Security.Permissions.SecurityAction.LinkDemand, SharedState = true)] public delegate void CancelEventHandler<TCancelEventArgs>(object sender, TCancelEventArgs e) where TCancelEventArgs : System.ComponentModel.CancelEventArgs; /// <summary> /// Provides data for a cancelable changing event. /// </summary> /// <typeparam name="T">The type of the property that is changing.</typeparam> public class CancelChangingEventArg<T> : System.ComponentModel.CancelEventArgs { private T cv = default(T); /// <summary> /// Gets the current value of a property as reported by a changing event. /// </summary> /// <returns>The generic value. In a practical implementation of the CancelChangingEventArg<T>, the generic type of this property is replaced with the constrained type of the implementation.</returns> [Description("Current value of a property")] public T CurrentValue { get { return cv; } } private T nv = default(T); /// <summary> /// Gets the new value of a property as reported by a changing event. /// </summary> /// <returns>The generic value. In a practical implementation of the CancelChangingEventArg<T>, the generic type of this property is replaced with the constrained type of the implementation.</returns> [Description("New value of a property")] public T NewValue { get { return nv; } } /// <summary> /// Initializes a new instance of the CancelChangingEventArg<T> class, with provided old and new values and the CancelChangingEventArg.Cancel property set to false. /// </summary> /// <param name="oldValue">Current value of the property at the time of the event.</param> /// <param name="newValue">New value of the property.</param> public CancelChangingEventArg(T currentValue, T newValue) : base() { cv = currentValue; nv = newValue; } /// <summary> /// Initializes a new instance of the CancelChangingEventArg<T> class, with provided old and new values and the CancelChangingEventArg.Cancel property set to the given value. /// </summary> /// <param name="oldValue">Current value of the property at the time of the event.</param> /// <param name="newValue">New value of the property.</param> /// <param name="cancel">true to cancel the event; otherwise, false.</param> public CancelChangingEventArg(T currentValue, T newValue, bool cancel) : base(cancel) { cv = currentValue; nv = newValue; } } //Using the code: public class MyClass { public event CancelEventHandler<CancelChangingEventArg<int>> SomePropertyChanging; private int _SomeProperty; public int SomeProperty { get { return _SomeProperty; } set { SetProperty(ref _SomeProperty, ref value); } } private void SetProperty(ref int property, ref int value) { if (SomePropertyChanging != null) { CancelChangingEventArg<int> ResponseArg = new CancelChangingEventArg<int>(property,value); SomePropertyChanging(this, ResponseArg); if (!ResponseArg.Cancel) property = value; } else property = value; } public MyClass() { _SomeProperty = 10; } } public class MyProgram { MyClass myc = new MyClass(); public MyProgram() { myc.SomePropertyChanging += new CancelEventHandler<CancelChangingEventArg<int>>(myc_SomePropertyChanging); myc.SomeProperty = 9; //this will be canceled. myc.SomeProperty = 11; //this will be accepted, and the value of the SomeProperty is now 11. } private void myc_SomePropertyChanging(object sender, CancelChangingEventArg<int> e) { //here we say if the new value is smaller than the one already in, then cancel the operation. //else set the value. e.Cancel = (e.CurrentValue > e.NewValue); } }
Etiketter:
C#,
CancelEventArgs,
CancelEventHandler,
Events,
Generic,
Implementation
December 9, 2009
CLR Datatype Mapping tables
SQL CLR Data type mapping
Source: http://msdn.microsoft.com/en-us/library/ms131092.aspx

Image Source: http://msdn.microsoft.com/en-us/library/bb386947.aspx
Platform Invoke Data Types
Source: http://msdn.microsoft.com/en-us/library/aa720411(VS.71).aspx
Multiple Data Types Mapping Table
Source: http://msdn.microsoft.com/en-us/library/aa720713(VS.71).aspx
| SQL Server data type | CLR data type (SQL Server) | CLR data type (.NET Framework) |
|---|---|---|
| bigint | SqlInt64 | Int64, Nullable<Int64> |
| binary | SqlBytes, SqlBinary | Byte[] |
| bit | SqlBoolean | Boolean, Nullable<Boolean> |
| char | None | None |
| cursor | None | None |
| date | SqlDateTime | DateTime, Nullable<DateTime> |
| datetime | SqlDateTime | DateTime, Nullable<DateTime> |
| datetime2 | SqlDateTime | DateTime, Nullable<DateTime> |
| DATETIMEOFFSET | None | DateTimeOffset, Nullable<DateTimeOffset> |
| decimal | SqlDecimal | Decimal, Nullable<Decimal> |
| float | SqlDouble | Double, Nullable<Double> |
| geography | SqlGeography defined in Microsoft.SqlServer.Types.dll Download here:feature pack. | None |
| geometry | SqlGeometry defined in Microsoft.SqlServer.Types.dll Download here: feature pack. | None |
| hierarchyid | SqlHierarchyId defined in Microsoft.SqlServer.Types.dll Download here: feature pack. | None |
| image | None | None |
| int | SqlInt32 | Int32, Nullable<Int32> |
| money | SqlMoney | Decimal, Nullable<Decimal> |
| nchar | SqlChars, SqlString | String, Char[] |
| ntext | None | None |
| numeric | SqlDecimal | Decimal, Nullable<Decimal> |
| nvarchar | SqlChars, SqlString SQLChars is a better match for data transfer and access, and SQLString is a better match for performing String operations. | String, Char[] |
| nvarchar(1), nchar(1) | SqlChars, SqlString | Char, String, Char[], Nullable<char> |
| real | SqlSingle | Single, Nullable<Single> |
| rowversion | None | Byte[] |
| smallint | SqlInt16 | Int16, Nullable<Int16> |
| smallmoney | SqlMoney | Decimal, Nullable<Decimal> |
| sql_variant | None | Object |
| table | None | None |
| text | None | None |
| time | TimeSpan | TimeSpan, Nullable<TimeSpan> |
| timestamp | None | None |
| tinyint | SqlByte | Byte, Nullable<Byte> |
| uniqueidentifier | SqlGuid | Guid, Nullable<Guid> |
| User-defined type(UDT) | None | The same class that is bound to the user-defined type in the same assembly or a dependent assembly. |
| varbinary | SqlBytes, SqlBinary | Byte[] |
| varbinary(1), binary(1) | SqlBytes, SqlBinary | byte, Byte[], Nullable<byte> |
| varchar | None | None |
| xml | SqlXml | None |

Image Source: http://msdn.microsoft.com/en-us/library/bb386947.aspx
Platform Invoke Data Types
| Unmanaged type in Wtypes.h | Unmanaged C language type | Managed class name | Description |
|---|---|---|---|
| HANDLE | void* | System.IntPtr | 32 bits |
| BYTE | unsigned char | System.Byte | 8 bits |
| SHORT | short | System.Int16 | 16 bits |
| WORD | unsigned short | System.UInt16 | 16 bits |
| INT | int | System.Int32 | 32 bits |
| UINT | unsigned int | System.UInt32 | 32 bits |
| LONG | long | System.Int32 | 32 bits |
| BOOL | long | System.Int32 | 32 bits |
| DWORD | unsigned long | System.UInt32 | 32 bits |
| ULONG | unsigned long | System.UInt32 | 32 bits |
| CHAR | char | System.Char | Decorate with ANSI. |
| LPSTR | char* | System.String or System.StringBuilder | Decorate with ANSI. |
| LPCSTR | Const char* | System.String or System.StringBuilder | Decorate with ANSI. |
| LPWSTR | wchar_t* | System.String or System.StringBuilder | Decorate with Unicode. |
| LPCWSTR | Const wchar_t* | System.String or System.StringBuilder | Decorate with Unicode. |
| FLOAT | Float | System.Single | 32 bits |
| DOUBLE | Double | System.Double | 64 bits |
Source: http://msdn.microsoft.com/en-us/library/aa720411(VS.71).aspx
Multiple Data Types Mapping Table
| Category | Class name | Description | Visual Basic data type | C# data type | Managed Extensions for C++ data type | JScript data type |
|---|---|---|---|---|---|---|
| Integer | Byte | An 8-bit unsigned integer. | Byte | byte | char | Byte |
| SByte | An 8-bit signed integer.Not CLS-compliant. | SByte No built-in type. | sbyte | signed char | SByte | |
| Int16 | A 16-bit signed integer. | Short | short | short | short | |
| Int32 | A 32-bit signed integer. | Integer | int | int -or- long | int | |
| Int64 | A 64-bit signed integer. | Long | long | __int64 | long | |
| UInt16 | A 16-bit unsigned integer.Not CLS-compliant. | UInt16 No built-in type. | ushort | unsigned short | UInt16 | |
| UInt32 | A 32-bit unsigned integer.Not CLS-compliant. | UInt32 No built-in type. | uint | unsigned int -or- unsigned long | UInt32 | |
| UInt64 | A 64-bit unsigned integer.Not CLS-compliant. | UInt64 No built-in type. | ulong | unsigned __int64 | UInt64 | |
| Floating point | Single | A single-precision (32-bit) floating-point number. | Single | float | float | float |
| Double | A double-precision (64-bit) floating-point number. | Double | double | double | double | |
| Logical | Boolean | A Boolean value (true or false). | Boolean | bool | bool | bool |
| Other | Char | A Unicode (16-bit) character. | Char | char | wchar_t | char |
| Decimal | A 96-bit decimal value. | Decimal | decimal | Decimal | Decimal | |
| IntPtr | A signed integer whose size depends on the underlying platform (a 32-bit value on a 32-bit platform and a 64-bit value on a 64-bit platform). | IntPtr No built-in type. | IntPtr No built-in type. | IntPtr No built-in type. | IntPtr | |
| UIntPtr | An unsigned integer whose size depends on the underlying platform (a 32- bit value on a 32-bit platform and a 64-bit value on a 64-bit platform).Not CLS-compliant. | UIntPtr No built-in type. | UIntPtr No built-in type. | UIntPtr No built-in type. | UIntPtr | |
| Class objects | Object | The root of the object hierarchy. | Object | object | Object* | Object |
| String | An immutable, fixed-length string of Unicode characters. | String | string | String* | String |
Source: http://msdn.microsoft.com/en-us/library/aa720713(VS.71).aspx
Etiketter:
C#,
C++,
CLR,
Datatype,
Framework 4.0,
JScript,
Managed types,
Mapping,
Pinvoke,
SQL,
SQL2005,
SQL2008,
SQL2008R2,
SQL2012,
Unmanaged types,
VB.Net,
Visual Basic
Subscribe to:
Posts (Atom)