2016년 9월 6일 화요일

Simple C# Database access framework



namespace NIHDatabase.RDS
{
    internal class NIHDbContext : DbContext
    {
        internal NIHDbContext(string connStr) : base(connStr) { }
    }
    public class NIHRdsService
    {
        public string _connStr { get; set; }
        public NIHRdsService() { }

        #region Multi Result
        /// <summary>
        /// Multi Result
        /// </summary>
        /// <param name="procedureName"></param>
        /// <param name="parameters"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public DataSet SqlMultiResult(string procedureName, object parameters, Func<object, string, ProcedureAndParameterModel> func)
        {
            DataSet ds = new DataSet();
            using (SqlConnection conn = new SqlConnection(_connStr))
            {
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand  = new SqlCommand(procedureName, conn);
                adapter.SelectCommand.Parameters.AddRange(func(parameters, procedureName).Parameters);
                adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
                adapter.Fill(ds);
            }

            return ds;
        }
        #endregion

        #region SqlQuery<T>
        /// <summary>
        /// 특정 조건에 맞는 단일 데이터 조회
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="procedureName"></param>
        /// <param name="parameters"></param>
        /// <param name="func"></param>
        /// <returns>T</returns>
        public async Task<T> SqlQuerySingle<T>(string procedureName, object parameters, Func<object, string, ProcedureAndParameterModel> func)
        {
            using (var context = new NIHDbContext(_connStr))
            {
                ProcedureAndParameterModel _model = func(parameters, procedureName);
                return await context.Database.SqlQuery<T>(_model.ProcedureName, _model.Parameters).SingleAsync();
            }
        }
        /// <summary>
        /// 파라미터 없이 전체 테이블 스캔
        /// </summary>
        /// <typeparam name="T">object</typeparam>
        /// <param name="procedureName">string</param>
        /// <returns>List<T></returns>
        public async Task<List<T>> SqlQueryMulti<T>(string procedureName)
        {
            using (var context = new NIHDbContext(_connStr))
            {
                return await context.Database.SqlQuery<T>(procedureName).ToListAsync();
            }
        }
        /// <summary>
        /// 특정 조건을 맞족하는 데이터 레코드 조회
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="procedureName"></param>
        /// <param name="parameters"></param>
        /// <param name="func"></param>
        /// <returns>List<T></returns>
        public async Task<List<T>> SqlQueryMulti<T>(string procedureName, object parameters, Func<object, string, ProcedureAndParameterModel> func)
        {
            using (var context = new NIHDbContext(_connStr))
            {
                ProcedureAndParameterModel _model = func(parameters, procedureName);
                return await context.Database.SqlQuery<T>(_model.ProcedureName, _model.Parameters).ToListAsync();
            }
        }
        #endregion

        #region ExecuteSqlCommandAsync
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="procedureName"></param>
        /// <param name="parameters"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public async Task<int> ExecuteCommandAsync<T>(string procedureName, object parameters, Func<object, string, ProcedureAndParameterModel> func)
        {
            using (var context = new NIHDbContext(_connStr))
            {
                ProcedureAndParameterModel _model = func(parameters, procedureName);
                return await context.Database.ExecuteSqlCommandAsync(_model.ProcedureName, _model.Parameters);
            }
        }
        #endregion
    }
}

SqlQuery 문 생성, DataTable에서 List로 변환

namespace NIHDatabase.RDS
{
    public static class DataHelper
    {
        /// <summary>
        /// 프로시저명과, 파라미터 모델을 받아서
        /// ProcedureAndParameter타입으로 반환
        /// </summary>
        /// <typeparam name="T">Parameter Entity</typeparam>
        /// <param name="model"></param>
        /// <param name="procName"></param>
        /// <returns></returns>
        public static ProcedureAndParameterModel GetSqlQueryString<T>(this T model, string ProcedureName)
        {
            List<SqlParameter> _parameters = new List<SqlParameter>();
            StringBuilder      _quryString = new StringBuilder(ProcedureName);

            if(model!=null)
            {
                bool _first = true;
                foreach (var prop in typeof(T).GetProperties())
                {
                    // 파라미터 명
                    var _name  = prop.Name;
                    // 파라미터 값
                    var _value = prop.GetValue(model, null);
                    // SqlParameter 값이 NULL이면 DBNull.Value로 설정
                    var _param = new SqlParameter($"@{_name}", _value == null ? DBNull.Value : _value);
                    // 파라미터 배열에 추가
                    _parameters.Add(_param);

                    // Sql Query문 설정
                    if (_first)
                    {
                        _quryString.Append($" @{_name}");
                        _first = false;
                    }
                    else
                    {
                        _quryString.Append($", @{_name}");
                    }
                }
            }
            
            return new ProcedureAndParameterModel { ProcedureName = _quryString.ToString(), Parameters = _parameters.ToArray() };
        }

        /// <summary>
        /// DataTable => List<T>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns>List<T></returns>
        public static List<T> ToList<T>(this DataTable table) where T : new()
        {
            IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            List<T> result = new List<T>();

            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<T>((DataRow)row, properties);
                result.Add(item);
            }

            return result;
        }

        private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
        {
            T item = new T();

            foreach (var prop in properties)
            {
                prop.SetValue(item, row[prop.Name], null);
            }
            return item;
        }
    }
}

2016년 9월 5일 월요일

mssql login failed 18456


ERROR : mssql login failed 18456

위와 같은 에러가 발생하면 SSMS(Sql Server Managerment Studio)에서 Windows Authentication 방식으로 로그인하고 다음 이미지에서와 같이 진행

2016년 4월 30일 토요일

[C#] Callback Func



예제 1

namespace Cshop_v6._0
{
    delegate int GetResultDelegate();

    class Target
    {
        public void Do(GetResultDelegate getResult)
        {
            Console.WriteLine(getResult()); // 콜백 메서드 호출
        }
    }

    class Source
    {
        public int GetResult() // 콜백 용도로 전달된 메서드
        {
            return 10;
        }

        public void Test()
        {
            Target target = new Target();
            target.Do(new GetResultDelegate(this.GetResult));
        }
    }
}

예제 2

namespace Cshop_v6._0
{
    delegate int GetResultDelegate(int x, int y);

    class Target
    {
        public void Do(GetResultDelegate getResult, int x, int y)
        {
            Console.WriteLine(getResult(x, y));
        }
    }

    class Source
    {
        public static int GetResult(int x, int y)
        {
            return x * y;
        }

        public static void Main()
        {
            Target target = new Target();
            GetResultDelegate gd = GetResult;
            target.Do(gd, 5, 10);
        }
    }
}

[C#] Delegate



접근제한자 delegate 대상_메서드_반환타입 식별자(… … 대상_메서드_매개변수_목록 … …);

예제 1

namespace Cshop_v6._0
{
    public class Mathematics
    {
        delegate int CalcDelegate(int x, int y);

        static int Add(int x, int y)      { return x + y; }
        static int Subtract(int x, int y) { return x - y; }
        static int Multiply(int x, int y) { return x * y; }
        static int Devide(int x, int y)   { return x / y; }

        CalcDelegate[] methods;

        public Mathematics()
        {
            methods = new CalcDelegate[] { Mathematics.Add, Mathematics.Subtract, Mathematics.Multiply, Mathematics.Devide };
        }

        public void Calculate(char opCode, int operand1, int operand2)
        {
            switch (opCode)
            {
                case '+': Console.WriteLine("+: " + methods[0](operand1, operand2)); break;
                case '-': Console.WriteLine("-: " + methods[1](operand1, operand2)); break;
                case '*': Console.WriteLine("*: " + methods[2](operand1, operand2)); break;
                case '/': Console.WriteLine("/: " + methods[3](operand1, operand2)); break;
            }
        }
    }

    class Program
    {
        delegate void WorkDelegate(char arg1, int arg2, int arg3);

        static void Main()
        {
            Mathematics math = new Mathematics();
            WorkDelegate work = math.Calculate;

            work('+', 10, 5);
            work('-', 10, 5);
            work('*', 10, 5);
            work('/', 10, 5);
        }
    }
}

예제 2

namespace Cshop_v6._0
{
    class Program
    {
        delegate void CalcDelegate(int x, int y);

        static void Add(int x, int y) { Console.WriteLine(x + y); }
        static void Subtract(int x, int y) { Console.WriteLine(x - y); }
        static void Multiply(int x, int y) { Console.WriteLine(x * y); }
        static void Divide(int x, int y) { Console.WriteLine(x / y); }

        static void Main()
        {
            CalcDelegate calc = Add;
            calc += Subtract;
            calc += Multiply;
            calc += Divide;

            calc(10, 5);

            // 출력결과
            /*
            15
            5
            50
            2
            */

            Console.WriteLine("=================================================================");

            calc -= Divide;

            calc(10, 5);


            // 출력결과
            /*
            15
            5
            50
            */
        }
    }
}

2016년 4월 22일 금요일

[C#] Lambda expression-1



코드로서의 람다식

class Program
{
    delegate int? MyDivide(int a, int b);
    static void Main(string[] args)
    {
        MyDivide myFunc = (a, b) =>
        {
            if (b == 0)
            {
                return null;
            }
            return a / b;
        };
        Console.WriteLine("10 / 0 = " + myFunc(10, 0));
     }
}

Func, Action 델리게이트를 이용한 Lambda expression

// public delegate void Action(T obj);
// 반환값이 없는 델리게이트로서 T 형식 매개변수는 입력될 인자 1개의 타입을 지정

// public delegate TResult Func();
// 반환값이 있는 델리게이트로서 TResult 형식 매개변수는 반환될 타입을 지정

class Program
{
    static void Main()
    {
        Action log = (text) =>
        {
            Console.WriteLine(text);
        };

        log("Hello world!");

        Func age = (a, b) => a + b;

        Console.WriteLine(age(14, 14));
    }
}

/*
public delegate void Action(T arg);
public delegate void Action(T1 arg1, T2 arg2);
...
T1~T16까지 Action delegate 정의

public delegate TResult Func();
public delegate TResult Func(T arg);
public delegate TResult Func(T1 arg1, T2 arg2);
...
T1 ~ T16까지 Func delegate 정의
*/

Collection & Lambda expression [ForEach]

// List에 정의된 ForEach
// public void ForEach(Action action);

// Array에 정의된 ForEach
// public static void ForEach(T [] array, Action action);
class Program
{
    static void Main()
    {
        List list = new List { 1, 2, 3, 10, 100 };

        // 일반형식
        foreach(var item in list)
        {
            Console.WriteLine(item + " * 2 == " + (item * 2));
        }

        // 람다식
        list.ForEach((elem) => { Console.WriteLine(elem + " * 2 == " + (elem * 2)); });
        // 또는
        Array.ForEach(list.ToArray(), (elem) => { Console.WriteLine(elem + " * 2 == " + (elem * 2)); });
    }
}

Collection & Lambda expression [FindAll, Where, Count, Select]

class Program
{
    static void Main()
    {

        List list = new List { 1, 2, 3, 10, 100, 501 };

        // 짝수로 구성된 리스트 반환
        List result = new List();

        // 일반형식
        foreach (var item in list)
        {
            if (item % 2 == 0)
            {
                result.Add(item);
            }
        }
        
        // FindAll
        result = list.FindAll((elem) => elem % 2 == 0);
 
        // Where
        IEnumerable enumList = list.Where((elem) => elem % 2 == 0);

        // Count
        int count = list.Count((elem) => elem > 3);

        // Select
        IEnumerable doubleList = list.Select((elem) => (double)elem);
        IEnumerable personList = list.Select((elem) => new Person {Age = elem, Name = Guid.NewGuid().ToString()});
        var itemList = list.Select((elem) => new {TypeNo = elem, CreateDate = DateTime.Now});
    }
}
class Person
{
    public int Age {get; set;}
    public string Name {get; set;}
}

2016년 4월 16일 토요일

MSSQL Identity, 조회, 초기화




//아래의 쿼리를 실행하면 현재 IDENTITY의 값을 확인할 수 있습니다.(변경되지 않음)
DBCC CHECKIDENT([TableName], NORESEED)

//아래의 쿼리를 실행하면 IDENTITY의 값이 Num으로 초기화됩니다.
DBCC CHECKIDENT([TableName], RESEED, [Num])

//아래의 쿼리를 실행하면 IDENTITY의 값이 현재 컬럼보다 작을 경우 값을 현재 컬럼과 같도록 변경합니다.
DBCC CHECKIDENT([TableName], RESEED)

호출자 정보 [CallerMemberName], [CallerFilePath], [CallerLineNumber]




CallerMemberName : 호출자 정보가 명시된 메서드를 호출한 측의 메서드 이름
CallerFilePath           : 호출자 정보가 명시된 메서드를 호출한 측의 소스코드 파일 경로
CallerLineNumber    : 호출자 정보가 명시된 메서드를 호출한 측의 소스코드 라인 번호


using System;
using System.Runtime.CompilerServices;

namespace ConsoleApplication1 
{
    class Program 
    {
        static void Main(string[] args) 
        {
            LogMessage("test log");
        }

        static void LogMessage(string text, [CallerMemberName] string memberName = "", 
                                            [CallerFilePath]   string filePath = "", 
                                            [CallerLineNumber] string lineNumber = "") 
        {
            Console.WriteLine("Text : " + text);
            Console.WriteLine("LogMessage CallerName : " + memberName);…
            Console.Writeline("LogMessage CallerLineNumber : " + lineNumber);
        }
    }
}

2016년 1월 24일 일요일

ValueError: unknown locale: UTF-8




1. Terminal을 실행한다.
2. vim .bash_profile을 입력후 Enter
3. export LANG=en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    을 추가 후 저장