顯示具有 C# (Extensions) 標籤的文章。 顯示所有文章
顯示具有 C# (Extensions) 標籤的文章。 顯示所有文章

2015年11月20日 星期五

[Entity Framework] 取得DAO對應的表格名稱

 #Entity Framework   #C Sharp


Entity Framework 如果要直接下一些Sql指令,必要條件當然是要知道 Table name
Table Name寫死在程式當然是最不好的方式; 可以利用以下代碼取得DAO對應的Table Name


使用 System.Data.Entity.DbContext extension


/// <summary>
/// DbContext/ObjectContext extensions
/// </summary>
public static class ContextExtensions
{
        /// <summary>
        /// Get the table name of Entity
        /// </summary>
        /// <typeparam name="T">Entity's type</typeparam>
        /// <param name="context">DbContext</param>
        /// <returns>Table name</returns>
        public static string GetTableName<T>(this DbContext context) where T : class
        {
            ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
            return objectContext.GetTableName<T>();
        }

        /// <summary>
        /// Get the table name of Entity
        /// </summary>
        /// <typeparam name="T">Entity's type</typeparam>
        /// <param name="context">ObjectContext</param>
        /// <returns>Table name</returns>
        public static string GetTableName<T>(this ObjectContext context) where T : class
        {
            string sql = context.CreateObjectSet<T>().ToTraceString();
            Regex regex = new Regex("FROM (?<table>.*) AS");
            Match match = regex.Match(sql);

            string table = match.Groups["table"].Value;
            return table;
        }
}

使用方式:

var targetTableName = this._dbContext.GetTableName<MyEntity>();



定義 [Table(“”)]

Entity Framework Code first中, 通常會定義 [Table("XXXX")] DAO (Entity) 類別上。

[Table("MyEntities")]
public class MyEntity : BaseEntity
{  …


這時候就可以使用 typeof(T).GetCustomAttributes 方法, 取得T類別定義的Class attributes
代碼如下:

var attr =
       typeof(T).GetCustomAttributes(false).Where(x => x.GetType().Name.Equals("TableAttribute")).FirstOrDefault();

if (attr != null)
{
    this._tableName = (attr as System.ComponentModel.DataAnnotations.Schema.TableAttribute).Name;
}
else
{
     throw new Exception("Cannot get the table name of POCO : AdOU");
}


2015年8月12日 星期三

[C#] Stopwatch Extensions


Extensions

/// <summary>
/// Stopwatch Extensions
/// </summary>
    public static class StopwatchExtensions
    {
        /// <summary>
        /// Action with Stopwatch
        /// </summary>
        /// <param name="stopwatch">Self</param>
        /// <param name="action">Action</param>
        /// <returns>Stopwatch</returns>
        public static Stopwatch Time(this Stopwatch stopwatch, Action action)
        {
            stopwatch.Reset();
            stopwatch.Start();

            action();

            stopwatch.Stop();
            return stopwatch;
        }

        public static String GetFormatedElapsedTime(this Stopwatch stopwatch)
        {
            // Get the elapsed time as a TimeSpan value.
            TimeSpan ts = stopwatch.Elapsed;

            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            return elapsedTime;
        }
    }

How to use

var sw = new Stopwatch();

Action myAction = () =>
{
    for (int i = 0; i < 5; i++)
    {
        Thread.Sleep(1000);
    }
};

sw.Time(myAction);
Trace.WriteLine(sw.GetFormatedElapsedTime(), "測試時間");
sw = null;


Reference


2015年8月4日 星期二

[C#] String Extensions (多國語系資源檔擴充)


Extensions

public static class StringExtensions
    {
        //Modify MultiLangResx.Resources.Resource to your [Namespace].[Resource name]
        public static String ToAutoMultiLang(this String source)
        {
            return MultiLangResx.Resources.Resource.ResourceManager.GetString(source);
        }
    }

How to use

@{ String submitMultiLang =  "Submit".ToAutoMultiLang(); }
<input type="submit" value="@submitMultiLang" />

or

<input type="submit" value="@Html.DisplayName( "Submit".ToAutoMultiLang())">


[C#] Enum Extensions



public static class EnumExtensions
    {
        /// <summary>
        /// Enum轉為數字
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static int ToIntValue(this Enum self)
        {
            return Convert.ToInt16(self);
        }


        /// <summary>
        /// 取得Enum的描述標籤內容
        /// </summary>
        /// <returns></returns>
        public static string GetDescription(this Enum self)
        {
            FieldInfo fi = self.GetType().GetField(self.ToString());
            DescriptionAttribute[] attributes = null;

            if (fi != null)
            {
                attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attributes != null && attributes.Length > 0)
                    return attributes[0].Description;
            }

            return self.ToString();
        }
    }