2016년 9월 6일 화요일

Simple C# Database access framework



  1. namespace NIHDatabase.RDS
  2. {
  3. internal class NIHDbContext : DbContext
  4. {
  5. internal NIHDbContext(string connStr) : base(connStr) { }
  6. }
  7. public class NIHRdsService
  8. {
  9. public string _connStr { get; set; }
  10. public NIHRdsService() { }
  11.  
  12. #region Multi Result
  13. /// <summary>
  14. /// Multi Result
  15. /// </summary>
  16. /// <param name="procedureName"></param>
  17. /// <param name="parameters"></param>
  18. /// <param name="func"></param>
  19. /// <returns></returns>
  20. public DataSet SqlMultiResult(string procedureName, object parameters, Func<object, string, ProcedureAndParameterModel> func)
  21. {
  22. DataSet ds = new DataSet();
  23. using (SqlConnection conn = new SqlConnection(_connStr))
  24. {
  25. SqlDataAdapter adapter = new SqlDataAdapter();
  26. adapter.SelectCommand = new SqlCommand(procedureName, conn);
  27. adapter.SelectCommand.Parameters.AddRange(func(parameters, procedureName).Parameters);
  28. adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
  29. adapter.Fill(ds);
  30. }
  31.  
  32. return ds;
  33. }
  34. #endregion
  35.  
  36. #region SqlQuery<T>
  37. /// <summary>
  38. /// 특정 조건에 맞는 단일 데이터 조회
  39. /// </summary>
  40. /// <typeparam name="T"></typeparam>
  41. /// <param name="procedureName"></param>
  42. /// <param name="parameters"></param>
  43. /// <param name="func"></param>
  44. /// <returns>T</returns>
  45. public async Task<T> SqlQuerySingle<T>(string procedureName, object parameters, Func<object, string, ProcedureAndParameterModel> func)
  46. {
  47. using (var context = new NIHDbContext(_connStr))
  48. {
  49. ProcedureAndParameterModel _model = func(parameters, procedureName);
  50. return await context.Database.SqlQuery<T>(_model.ProcedureName, _model.Parameters).SingleAsync();
  51. }
  52. }
  53. /// <summary>
  54. /// 파라미터 없이 전체 테이블 스캔
  55. /// </summary>
  56. /// <typeparam name="T">object</typeparam>
  57. /// <param name="procedureName">string</param>
  58. /// <returns>List<T></returns>
  59. public async Task<List<T>> SqlQueryMulti<T>(string procedureName)
  60. {
  61. using (var context = new NIHDbContext(_connStr))
  62. {
  63. return await context.Database.SqlQuery<T>(procedureName).ToListAsync();
  64. }
  65. }
  66. /// <summary>
  67. /// 특정 조건을 맞족하는 데이터 레코드 조회
  68. /// </summary>
  69. /// <typeparam name="T"></typeparam>
  70. /// <param name="procedureName"></param>
  71. /// <param name="parameters"></param>
  72. /// <param name="func"></param>
  73. /// <returns>List<T></returns>
  74. public async Task<List<T>> SqlQueryMulti<T>(string procedureName, object parameters, Func<object, string, ProcedureAndParameterModel> func)
  75. {
  76. using (var context = new NIHDbContext(_connStr))
  77. {
  78. ProcedureAndParameterModel _model = func(parameters, procedureName);
  79. return await context.Database.SqlQuery<T>(_model.ProcedureName, _model.Parameters).ToListAsync();
  80. }
  81. }
  82. #endregion
  83.  
  84. #region ExecuteSqlCommandAsync
  85. /// <summary>
  86. ///
  87. /// </summary>
  88. /// <typeparam name="T"></typeparam>
  89. /// <param name="procedureName"></param>
  90. /// <param name="parameters"></param>
  91. /// <param name="func"></param>
  92. /// <returns></returns>
  93. public async Task<int> ExecuteCommandAsync<T>(string procedureName, object parameters, Func<object, string, ProcedureAndParameterModel> func)
  94. {
  95. using (var context = new NIHDbContext(_connStr))
  96. {
  97. ProcedureAndParameterModel _model = func(parameters, procedureName);
  98. return await context.Database.ExecuteSqlCommandAsync(_model.ProcedureName, _model.Parameters);
  99. }
  100. }
  101. #endregion
  102. }
  103. }

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

  1. namespace NIHDatabase.RDS
  2. {
  3. public static class DataHelper
  4. {
  5. /// <summary>
  6. /// 프로시저명과, 파라미터 모델을 받아서
  7. /// ProcedureAndParameter타입으로 반환
  8. /// </summary>
  9. /// <typeparam name="T">Parameter Entity</typeparam>
  10. /// <param name="model"></param>
  11. /// <param name="procName"></param>
  12. /// <returns></returns>
  13. public static ProcedureAndParameterModel GetSqlQueryString<T>(this T model, string ProcedureName)
  14. {
  15. List<SqlParameter> _parameters = new List<SqlParameter>();
  16. StringBuilder _quryString = new StringBuilder(ProcedureName);
  17.  
  18. if(model!=null)
  19. {
  20. bool _first = true;
  21. foreach (var prop in typeof(T).GetProperties())
  22. {
  23. // 파라미터 명
  24. var _name = prop.Name;
  25. // 파라미터 값
  26. var _value = prop.GetValue(model, null);
  27. // SqlParameter 값이 NULL이면 DBNull.Value로 설정
  28. var _param = new SqlParameter($"@{_name}", _value == null ? DBNull.Value : _value);
  29. // 파라미터 배열에 추가
  30. _parameters.Add(_param);
  31.  
  32. // Sql Query문 설정
  33. if (_first)
  34. {
  35. _quryString.Append($" @{_name}");
  36. _first = false;
  37. }
  38. else
  39. {
  40. _quryString.Append($", @{_name}");
  41. }
  42. }
  43. }
  44. return new ProcedureAndParameterModel { ProcedureName = _quryString.ToString(), Parameters = _parameters.ToArray() };
  45. }
  46.  
  47. /// <summary>
  48. /// DataTable => List<T>
  49. /// </summary>
  50. /// <typeparam name="T"></typeparam>
  51. /// <param name="table"></param>
  52. /// <returns>List<T></returns>
  53. public static List<T> ToList<T>(this DataTable table) where T : new()
  54. {
  55. IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
  56. List<T> result = new List<T>();
  57.  
  58. foreach (var row in table.Rows)
  59. {
  60. var item = CreateItemFromRow<T>((DataRow)row, properties);
  61. result.Add(item);
  62. }
  63.  
  64. return result;
  65. }
  66.  
  67. private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
  68. {
  69. T item = new T();
  70.  
  71. foreach (var prop in properties)
  72. {
  73. prop.SetValue(item, row[prop.Name], null);
  74. }
  75. return item;
  76. }
  77. }
  78. }

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

  1. namespace Cshop_v6._0
  2. {
  3. delegate int GetResultDelegate();
  4.  
  5. class Target
  6. {
  7. public void Do(GetResultDelegate getResult)
  8. {
  9. Console.WriteLine(getResult()); // 콜백 메서드 호출
  10. }
  11. }
  12.  
  13. class Source
  14. {
  15. public int GetResult() // 콜백 용도로 전달된 메서드
  16. {
  17. return 10;
  18. }
  19.  
  20. public void Test()
  21. {
  22. Target target = new Target();
  23. target.Do(new GetResultDelegate(this.GetResult));
  24. }
  25. }
  26. }

예제 2

  1. namespace Cshop_v6._0
  2. {
  3. delegate int GetResultDelegate(int x, int y);
  4.  
  5. class Target
  6. {
  7. public void Do(GetResultDelegate getResult, int x, int y)
  8. {
  9. Console.WriteLine(getResult(x, y));
  10. }
  11. }
  12.  
  13. class Source
  14. {
  15. public static int GetResult(int x, int y)
  16. {
  17. return x * y;
  18. }
  19.  
  20. public static void Main()
  21. {
  22. Target target = new Target();
  23. GetResultDelegate gd = GetResult;
  24. target.Do(gd, 5, 10);
  25. }
  26. }
  27. }

[C#] Delegate



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

예제 1

  1. namespace Cshop_v6._0
  2. {
  3. public class Mathematics
  4. {
  5. delegate int CalcDelegate(int x, int y);
  6.  
  7. static int Add(int x, int y) { return x + y; }
  8. static int Subtract(int x, int y) { return x - y; }
  9. static int Multiply(int x, int y) { return x * y; }
  10. static int Devide(int x, int y) { return x / y; }
  11.  
  12. CalcDelegate[] methods;
  13.  
  14. public Mathematics()
  15. {
  16. methods = new CalcDelegate[] { Mathematics.Add, Mathematics.Subtract, Mathematics.Multiply, Mathematics.Devide };
  17. }
  18.  
  19. public void Calculate(char opCode, int operand1, int operand2)
  20. {
  21. switch (opCode)
  22. {
  23. case '+': Console.WriteLine("+: " + methods[0](operand1, operand2)); break;
  24. case '-': Console.WriteLine("-: " + methods[1](operand1, operand2)); break;
  25. case '*': Console.WriteLine("*: " + methods[2](operand1, operand2)); break;
  26. case '/': Console.WriteLine("/: " + methods[3](operand1, operand2)); break;
  27. }
  28. }
  29. }
  30.  
  31. class Program
  32. {
  33. delegate void WorkDelegate(char arg1, int arg2, int arg3);
  34.  
  35. static void Main()
  36. {
  37. Mathematics math = new Mathematics();
  38. WorkDelegate work = math.Calculate;
  39.  
  40. work('+', 10, 5);
  41. work('-', 10, 5);
  42. work('*', 10, 5);
  43. work('/', 10, 5);
  44. }
  45. }
  46. }

예제 2

  1. namespace Cshop_v6._0
  2. {
  3. class Program
  4. {
  5. delegate void CalcDelegate(int x, int y);
  6.  
  7. static void Add(int x, int y) { Console.WriteLine(x + y); }
  8. static void Subtract(int x, int y) { Console.WriteLine(x - y); }
  9. static void Multiply(int x, int y) { Console.WriteLine(x * y); }
  10. static void Divide(int x, int y) { Console.WriteLine(x / y); }
  11.  
  12. static void Main()
  13. {
  14. CalcDelegate calc = Add;
  15. calc += Subtract;
  16. calc += Multiply;
  17. calc += Divide;
  18.  
  19. calc(10, 5);
  20.  
  21. // 출력결과
  22. /*
  23. 15
  24. 5
  25. 50
  26. 2
  27. */
  28.  
  29. Console.WriteLine("=================================================================");
  30.  
  31. calc -= Divide;
  32.  
  33. calc(10, 5);
  34.  
  35.  
  36. // 출력결과
  37. /*
  38. 15
  39. 5
  40. 50
  41. */
  42. }
  43. }
  44. }

2016년 4월 22일 금요일

[C#] Lambda expression-1



코드로서의 람다식

  1. class Program
  2. {
  3. delegate int? MyDivide(int a, int b);
  4. static void Main(string[] args)
  5. {
  6. MyDivide myFunc = (a, b) =>
  7. {
  8. if (b == 0)
  9. {
  10. return null;
  11. }
  12. return a / b;
  13. };
  14. Console.WriteLine("10 / 0 = " + myFunc(10, 0));
  15. }
  16. }

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

  1. // public delegate void Action(T obj);
  2. // 반환값이 없는 델리게이트로서 T 형식 매개변수는 입력될 인자 1개의 타입을 지정
  3. // public delegate TResult Func();
  4. // 반환값이 있는 델리게이트로서 TResult 형식 매개변수는 반환될 타입을 지정
  5. class Program
  6. {
  7. static void Main()
  8. {
  9. Action log = (text) =>
  10. {
  11. Console.WriteLine(text);
  12. };
  13. log("Hello world!");
  14. Func age = (a, b) => a + b;
  15. Console.WriteLine(age(14, 14));
  16. }
  17. }
  18. /*
  19. public delegate void Action(T arg);
  20. public delegate void Action(T1 arg1, T2 arg2);
  21. ...
  22. T1~T16까지 Action delegate 정의
  23. public delegate TResult Func();
  24. public delegate TResult Func(T arg);
  25. public delegate TResult Func(T1 arg1, T2 arg2);
  26. ...
  27. T1 ~ T16까지 Func delegate 정의
  28. */

Collection & Lambda expression [ForEach]

  1. // List에 정의된 ForEach
  2. // public void ForEach(Action action);
  3. // Array에 정의된 ForEach
  4. // public static void ForEach(T [] array, Action action);
  5. class Program
  6. {
  7. static void Main()
  8. {
  9. List list = new List { 1, 2, 3, 10, 100 };
  10. // 일반형식
  11. foreach(var item in list)
  12. {
  13. Console.WriteLine(item + " * 2 == " + (item * 2));
  14. }
  15. // 람다식
  16. list.ForEach((elem) => { Console.WriteLine(elem + " * 2 == " + (elem * 2)); });
  17. // 또는
  18. Array.ForEach(list.ToArray(), (elem) => { Console.WriteLine(elem + " * 2 == " + (elem * 2)); });
  19. }
  20. }

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

  1. class Program
  2. {
  3. static void Main()
  4. {
  5.  
  6. List list = new List { 1, 2, 3, 10, 100, 501 };
  7. // 짝수로 구성된 리스트 반환
  8. List result = new List();
  9. // 일반형식
  10. foreach (var item in list)
  11. {
  12. if (item % 2 == 0)
  13. {
  14. result.Add(item);
  15. }
  16. }
  17. // FindAll
  18. result = list.FindAll((elem) => elem % 2 == 0);
  19. // Where
  20. IEnumerable enumList = list.Where((elem) => elem % 2 == 0);
  21. // Count
  22. int count = list.Count((elem) => elem > 3);
  23. // Select
  24. IEnumerable doubleList = list.Select((elem) => (double)elem);
  25. IEnumerable personList = list.Select((elem) => new Person {Age = elem, Name = Guid.NewGuid().ToString()});
  26. var itemList = list.Select((elem) => new {TypeNo = elem, CreateDate = DateTime.Now});
  27. }
  28. }
  29. class Person
  30. {
  31. public int Age {get; set;}
  32. public string Name {get; set;}
  33. }

2016년 4월 16일 토요일

MSSQL Identity, 조회, 초기화




  1. //아래의 쿼리를 실행하면 현재 IDENTITY의 값을 확인할 수 있습니다.(변경되지 않음)
  2. DBCC CHECKIDENT([TableName], NORESEED)
  3.  
  4. //아래의 쿼리를 실행하면 IDENTITY의 값이 Num으로 초기화됩니다.
  5. DBCC CHECKIDENT([TableName], RESEED, [Num])
  6.  
  7. //아래의 쿼리를 실행하면 IDENTITY의 값이 현재 컬럼보다 작을 경우 값을 현재 컬럼과 같도록 변경합니다.
  8. DBCC CHECKIDENT([TableName], RESEED)

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




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


  1. using System;
  2. using System.Runtime.CompilerServices;
  3.  
  4. namespace ConsoleApplication1
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. LogMessage("test log");
  11. }
  12.  
  13. static void LogMessage(string text, [CallerMemberName] string memberName = "",
  14. [CallerFilePath] string filePath = "",
  15. [CallerLineNumber] string lineNumber = "")
  16. {
  17. Console.WriteLine("Text : " + text);
  18. Console.WriteLine("LogMessage CallerName : " + memberName);…
  19. Console.Writeline("LogMessage CallerLineNumber : " + lineNumber);
  20. }
  21. }
  22. }

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
    을 추가 후 저장