Showing posts with label Utilities. Show all posts
Showing posts with label Utilities. Show all posts

Tuesday, September 16, 2014

How to include value types AND strings in generic constraint.

I'm very like to use generics in the code. Usually generic implementation is working smoothly but exists one small problem with generic value types: cannot use string typed value because System.String is a class.

  1. Foo<string>("abc");



  1. private void Foo(T value) where T : struct
  2. {
  3. //...
  4. }
 
The simple solution is creating overwrite method:

  1. private void Foo(T value) where T : string
  2. {
  3. //...
  4. }

Nice, but not perfect. The beautiful idea was offered by KeithS instead to restrict a value to struct change it to IConvertible. Next types implemented an interface IConvertible but now String can be included in the constraint:
Boolean   
Byte   
Char   
DateTime
Decimal   
Double   
Int16   
Int32   
Int64   
SByte   
Single   
String   
Type   
UInt16   
UInt32   
UInt64 


Final:

  1. private void Foo(T value) where T : IConvertible
  2. {
  3. //...
  4. }



Tuesday, February 26, 2013

C# property names without hardcoded strings


public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Test
{
    protected void InitDropDownList()
    {
        DropDownList ddl = new DropDownList();
        ddl.DataSource = new List<Person> { 
            new Person{ Id = 1, Name = "John Smith" },
            new Person{ Id =  2,Name = "Moshe Perez" } };

        //Old and bad way
        ddl.DataValueField = "Id";
        ddl.DataTextField = "Name";

        //New way
        ddl.DataValueField = GetPropertyName(() => new Person().Id);
        ddl.DataValueField = GetPropertyName(() => new Person().Name);

        ddl.DataBind();
    }

    private static string GetPropertyName<T>
(Expression<Func<T>> expression)
    {
        MemberExpression body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
}



From here

Wednesday, January 02, 2013

Test value generator

Frequently in the test time required to set random values to variables. The simple class will help you to save a time in the future:

public static class Generator
{
    public static readonly Random RND = new Random();
        
    // Generate IP address
    public static string GetIP(bool isIPv6 = false)
    {
        if (isIPv6)
        {
            return string.Format("{0}.{1}.{2}.{3}.{4}.{5}", RND.Next(0,256), RND.Next(0,256), RND.Next(0,256), RND.Next(0,256), RND.Next(0,256), RND.Next(0,256));
        }
        return string.Format("{0}.{1}.{2}.{3}", RND.Next(0,256), RND.Next(0,256), RND.Next(0,256), RND.Next(0,256));
    }

    // Generate GPS coordinate
    public static System.Device.Location.GeoCoordinate GetGeo()
    {
        return new System.Device.Location.GeoCoordinate
        {
            Latitude =  GetDouble(90),
            Longitude = GetDouble(90),
        };
    }
    // Generate string
    public static string GetString(int size, int percentOfSymbols = 30, int percentOfDigits = 30)
    {
        StringBuilder builder = new StringBuilder();
        int[] symbol = new[] { 33, 36, 38, 64, 94 };
        int[] digits = new[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 };
        int symbolsAmount =  (int) size * percentOfSymbols /100;
        int digitAmount = (int)size * percentOfDigits / 100;
        for (int i = 0; i < size; i++)
        {
            int switcher = RND.Next(3);
            char ch;
            if (switcher == 0 && symbolsAmount > 0)
            {
                int id = RND.Next(symbol.Length);
                ch = Convert.ToChar(symbol[id]);
                symbolsAmount--;
            }
            else if (switcher == 1 && digitAmount > 0)
            {
                int id = RND.Next(digits.Length);
                ch = Convert.ToChar(digits[id]);
                digitAmount--;
            }
            else
            {
                bool isLower = RND.Next(2) == 0 ? false : true;
                ch = Convert.ToChar(
                        Convert.ToInt32(
                        Math.Floor(26 * RND.NextDouble() + ((isLower) ? 65 : 97))
                            )
                        );

            }
            builder.Append(ch);
        }
        return builder.ToString();
    }
    // Generate Date
    public static DateTime GetDate()
    {
        return DateTime.Now.AddMinutes(  RND.Next(10000000)  * (RND.Next() % 2 == 0 ? -1 : 1));
    }
    //Get double
    public static double GetDouble(int limit = default(int))
    {
        return double.Parse(string.Format("{0}.{1}", limit == default(int) ? RND.Next() : RND.Next(90), RND.Next())) *  (RND.Next() % 2 == 0 ? -1 : 1);
    }
}

kick it on DotNetKicks.com

Sunday, October 28, 2012

Validation is a boxing value is default

I very like my lovely extension IsDefault but unpossible to use it where a value is boxing. A cool feature of C#  default(...)  cannot help because a argument required Type. After long research was created small solution:

static bool IsDefault(object o)
{
    if (o == null)
    {
        return true;
    }
    //Check is type os object is ValueType
    if (o.GetType().IsValueType)
    {
        return Activator.CreateInstance(o.GetType()).Equals(o);
    }
    //ReferenceType
    return false;
}


Also can be implemented as extension.

Sunday, August 05, 2012

Culture in .NET. All in one

By inspiration from article Hidden Gems inside .Net Classes I created static class that include short methods for quick retrieval object or properties of Cultures and Time Zones. All data based on build-in functionality of Framework 4.0


 public static class Culture
    {
        #region Consts
        private static readonly StringDictionary cultureDetails;
        private static readonly ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones(); 
        #endregion
        
        /// <summary>
        /// Ctor
        /// </summary>
        static  Culture()
        {
            #region Init culture datails
            cultureDetails = new StringDictionary();
            foreach (CultureInfo cultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
            {
                RegionInfo regionInfo = new RegionInfo(cultureInfo.Name);

                if (!cultureDetails.ContainsKey(regionInfo.EnglishName))
                {
                    cultureDetails.Add(regionInfo.EnglishName, regionInfo.Name);
                }
            } 
            #endregion
        }
        /// <summary>
        /// Get culture name by Country
        /// </summary>
        /// <param name="countryName"></param>
        /// <returns></returns>
        public static string GetCulture(string countryName)
        {
            return cultureDetails.ContainsKey(countryName) ? cultureDetails[countryName] : string.Empty;
        }
        /// <summary>
        /// Get Culture info by culture name
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static CultureInfo GetCultureInfo(string cultureName)
        {
            return CultureInfo.GetCultures(CultureTypes.SpecificCultures).FirstOrDefault(item => item.Name == cultureName);
        }
        /// <summary>
        /// Get month names by culture
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static string[] GetMonths(string cultureName)
        {
            var region = GetCultureInfo(cultureName);
            return region == null ? null : region.DateTimeFormat.MonthNames;
        }
        /// <summary>
        /// Get day names by culture
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static string[] GetDays(string cultureName)
        {
            var region = GetCultureInfo(cultureName);
            return region == null ? null : region.DateTimeFormat.DayNames;
        }
        /// <summary>
        /// Get first day of week by culture
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static DayOfWeek GetFirstDayOfWeek(string cultureName)
        {
            var region = GetCultureInfo(cultureName);
            return region == null ? default(DayOfWeek) : region.DateTimeFormat.FirstDayOfWeek;
        }
        /// <summary>
        /// Get datetime format by culture
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static string GetDateTimeFormat(string cultureName)
        {
            var region = GetCultureInfo(cultureName);
            return region == null ? string.Empty : region.DateTimeFormat.FullDateTimePattern;
        }
        /// <summary>
        /// Get TimeZone info by DisplayName
        /// </summary>
        /// <param name="displayName"></param>
        /// <returns></returns>
        public static TimeZoneInfo GetTimeZoneByDisplayName(string name)
        {
           return timeZones.FirstOrDefault(item => item.DisplayName == name);
        }
        /// <summary>
        /// Get TimeZone info by Standart Name
        /// </summary>
        /// <param name="displayName"></param>
        /// <returns></returns>
        public static TimeZoneInfo GetTimeZoneByStandartName(string name)
        {
            return timeZones.FirstOrDefault(item => item.StandardName == name);
        }
    }