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

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
  • 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.



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
WeekMonTueWenThuFriSatSun
2231123456
2378910111213
2414151617181920
2521222324252627
262829301234



July 2010
WeekMonTueWenThuFriSatSun
262829301234
27567891011
2812131415161718
2919202122232425
302627282930311


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

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&lt;T&gt; 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);    
    }
}

December 9, 2009

CLR Datatype Mapping tables

SQL CLR Data type mapping
SQL Server data typeCLR data type (SQL Server)CLR data type (.NET Framework)
bigintSqlInt64Int64, Nullable<Int64>
binarySqlBytes, SqlBinaryByte[]
bitSqlBooleanBoolean, Nullable<Boolean>
charNoneNone
cursorNoneNone
dateSqlDateTimeDateTime, Nullable<DateTime>
datetimeSqlDateTimeDateTime, Nullable<DateTime>
datetime2SqlDateTimeDateTime, Nullable<DateTime>
DATETIMEOFFSETNoneDateTimeOffset, Nullable<DateTimeOffset>
decimalSqlDecimalDecimal, Nullable<Decimal>
floatSqlDoubleDouble, Nullable<Double>
geographySqlGeography
defined in Microsoft.SqlServer.Types.dll Download here:feature pack.
None
geometrySqlGeometry
defined in Microsoft.SqlServer.Types.dll Download here: feature pack.
None
hierarchyidSqlHierarchyId
defined in Microsoft.SqlServer.Types.dll Download here: feature pack.
None
imageNoneNone
intSqlInt32Int32, Nullable<Int32>
moneySqlMoneyDecimal, Nullable<Decimal>
ncharSqlChars, SqlStringString, Char[]
ntextNoneNone
numericSqlDecimalDecimal, Nullable<Decimal>
nvarcharSqlChars, 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, SqlStringChar, String, Char[], Nullable<char>
realSqlSingleSingle, Nullable<Single>
rowversionNoneByte[]
smallintSqlInt16Int16, Nullable<Int16>
smallmoneySqlMoneyDecimal, Nullable<Decimal>
sql_variantNoneObject
tableNoneNone
textNoneNone
timeTimeSpanTimeSpan, Nullable<TimeSpan>
timestampNoneNone
tinyintSqlByteByte, Nullable<Byte>
uniqueidentifierSqlGuidGuid, Nullable<Guid>
User-defined type(UDT)NoneThe same class that is bound
to the user-defined type in
the same assembly or a
dependent assembly.
varbinary SqlBytes, SqlBinaryByte[]
varbinary(1), binary(1)SqlBytes, SqlBinarybyte, Byte[], Nullable<byte>
varcharNoneNone
xmlSqlXmlNone
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
Unmanaged type in Wtypes.h Unmanaged C language typeManaged class nameDescription
HANDLEvoid*System.IntPtr32 bits
BYTEunsigned charSystem.Byte8 bits
SHORTshortSystem.Int1616 bits
WORDunsigned shortSystem.UInt1616 bits
INTintSystem.Int3232 bits
UINTunsigned intSystem.UInt3232 bits
LONGlongSystem.Int3232 bits
BOOLlongSystem.Int3232 bits
DWORDunsigned longSystem.UInt3232 bits
ULONGunsigned longSystem.UInt3232 bits
CHARcharSystem.CharDecorate with ANSI.
LPSTRchar*System.String or System.StringBuilderDecorate with ANSI.
LPCSTRConst char*System.String or System.StringBuilderDecorate with ANSI.
LPWSTRwchar_t*System.String or System.StringBuilderDecorate with Unicode.
LPCWSTRConst wchar_t*System.String or System.StringBuilderDecorate with Unicode.
FLOATFloatSystem.Single32 bits
DOUBLEDoubleSystem.Double64 bits

Source: http://msdn.microsoft.com/en-us/library/aa720411(VS.71).aspx



Multiple Data Types Mapping Table
CategoryClass nameDescriptionVisual Basic data typeC# data typeManaged Extensions for C++ data typeJScript data type
IntegerByteAn 8-bit unsigned integer.BytebytecharByte
SByteAn 8-bit signed integer.Not CLS-compliant.SByte No built-in type.sbytesigned charSByte
Int16A 16-bit signed integer.Shortshortshortshort
Int32A 32-bit signed integer.Integerintint -or- longint
Int64A 64-bit signed integer.Longlong__int64long
UInt16A 16-bit unsigned integer.Not CLS-compliant.UInt16 No built-in type.ushortunsigned shortUInt16
UInt32A 32-bit unsigned integer.Not CLS-compliant.UInt32 No built-in type.uintunsigned int -or- unsigned longUInt32
UInt64A 64-bit unsigned integer.Not CLS-compliant.UInt64 No built-in type.ulongunsigned __int64UInt64
Floating pointSingleA single-precision (32-bit) floating-point number.Singlefloatfloatfloat
DoubleA double-precision (64-bit) floating-point number.Doubledoubledoubledouble
LogicalBooleanA Boolean value (true or false).Booleanboolboolbool
OtherCharA Unicode (16-bit) character.Charcharwchar_tchar
DecimalA 96-bit decimal value.DecimaldecimalDecimalDecimal
IntPtrA 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
UIntPtrAn 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 objectsObjectThe root of the object hierarchy.ObjectobjectObject*Object
StringAn immutable, fixed-length string of Unicode characters.StringstringString*String

Source: http://msdn.microsoft.com/en-us/library/aa720713(VS.71).aspx

Total Pageviews