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

2015년 11월 16일 월요일

DATETIME to CHAR



단일값 반환
 23 : yyyy-mm-dd
102 : yyyy.mm.dd
111 : yyyy/mm/dd
112 : yyyymmdd
120 : yyyy-mm-dd hh:mi:ss
121 : yyyy-mm-dd hh:mi:ss.mmm

예) 오늘(2008년 1월 9일) 기준으로

SELECT CONVERT(char(10), getdate(), 23)

출처

2015년 10월 29일 목요일

Change Time zone of Azure WebApp (애저 웹앱에서 타임존 설정하는 방법)



azure web app timezone 설정방법

1. 애저관리 포털에서 설정할 웹 앱을 선택한다.
2. 설정으로 들어간다.
3. 응용 프로그램 설정으로 들어간다.
4. 앱 설정에서 다음과 같이 설정한다.
   key : WEBSITE_TIME_ZONE
   value : Korea Standard Time

다음은 타임존 이름이다.

IndexName of Time ZoneTime
000Dateline Standard Time(GMT-12:00) International Date Line West
001Samoa Standard Time(GMT-11:00) Midway Island, Samoa
002Hawaiian Standard Time(GMT-10:00) Hawaii
003Alaskan Standard Time(GMT-09:00) Alaska
004Pacific Standard Time(GMT-08:00) Pacific Time (US and Canada); Tijuana
010Mountain Standard Time(GMT-07:00) Mountain Time (US and Canada)
013Mexico Standard Time 2(GMT-07:00) Chihuahua, La Paz, Mazatlan
015U.S. Mountain Standard Time(GMT-07:00) Arizona
020Central Standard Time(GMT-06:00) Central Time (US and Canada
025Canada Central Standard Time(GMT-06:00) Saskatchewan
030Mexico Standard Time(GMT-06:00) Guadalajara, Mexico City, Monterrey
033Central America Standard Time(GMT-06:00) Central America
035Eastern Standard Time(GMT-05:00) Eastern Time (US and Canada)
040U.S. Eastern Standard Time(GMT-05:00) Indiana (East)
045S.A. Pacific Standard Time(GMT-05:00) Bogota, Lima, Quito
050Atlantic Standard Time(GMT-04:00) Atlantic Time (Canada)
055S.A. Western Standard Time(GMT-04:00) Caracas, La Paz
056Pacific S.A. Standard Time(GMT-04:00) Santiago
060Newfoundland and Labrador Standard Time(GMT-03:30) Newfoundland and Labrador
065E. South America Standard Time(GMT-03:00) Brasilia
070S.A. Eastern Standard Time(GMT-03:00) Buenos Aires, Georgetown
073Greenland Standard Time(GMT-03:00) Greenland
075Mid-Atlantic Standard Time(GMT-02:00) Mid-Atlantic
080Azores Standard Time(GMT-01:00) Azores
083Cape Verde Standard Time(GMT-01:00) Cape Verde Islands
085GMT Standard Time(GMT) Greenwich Mean Time: Dublin, Edinburgh, Lisbon, London
090Greenwich Standard Time(GMT) Casablanca, Monrovia
095Central Europe Standard Time(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague
100Central European Standard Time(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb
105Romance Standard Time(GMT+01:00) Brussels, Copenhagen, Madrid, Paris
110W. Europe Standard Time(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna
113W. Central Africa Standard Time(GMT+01:00) West Central Africa
115E. Europe Standard Time(GMT+02:00) Bucharest
120Egypt Standard Time(GMT+02:00) Cairo
125FLE Standard Time(GMT+02:00) Helsinki, Kiev, Riga, Sofia, Tallinn, Vilnius
130GTB Standard Time(GMT+02:00) Athens, Istanbul, Minsk
135Israel Standard Time(GMT+02:00) Jerusalem
140South Africa Standard Time(GMT+02:00) Harare, Pretoria
145Russian Standard Time(GMT+03:00) Moscow, St. Petersburg, Volgograd
150Arab Standard Time(GMT+03:00) Kuwait, Riyadh
155E. Africa Standard Time(GMT+03:00) Nairobi
158Arabic Standard Time(GMT+03:00) Baghdad
160Iran Standard Time(GMT+03:30) Tehran
165Arabian Standard Time(GMT+04:00) Abu Dhabi, Muscat
170Caucasus Standard Time(GMT+04:00) Baku, Tbilisi, Yerevan
175Transitional Islamic State of Afghanistan Standard Time(GMT+04:30) Kabul
180Ekaterinburg Standard Time(GMT+05:00) Ekaterinburg
185West Asia Standard Time(GMT+05:00) Islamabad, Karachi, Tashkent
190India Standard Time(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi
193Nepal Standard Time(GMT+05:45) Kathmandu
195Central Asia Standard Time(GMT+06:00) Astana, Dhaka
200Sri Lanka Standard Time(GMT+06:00) Sri Jayawardenepura
201N. Central Asia Standard Time(GMT+06:00) Almaty, Novosibirsk
203Myanmar Standard Time(GMT+06:30) Yangon Rangoon
205S.E. Asia Standard Time(GMT+07:00) Bangkok, Hanoi, Jakarta
207North Asia Standard Time(GMT+07:00) Krasnoyarsk
210China Standard Time(GMT+08:00) Beijing, Chongqing, Hong Kong SAR, Urumqi
215Singapore Standard Time(GMT+08:00) Kuala Lumpur, Singapore
220Taipei Standard Time(GMT+08:00) Taipei
225W. Australia Standard Time(GMT+08:00) Perth
227North Asia East Standard Time(GMT+08:00) Irkutsk, Ulaanbaatar
230Korea Standard Time(GMT+09:00) Seoul
235Tokyo Standard Time(GMT+09:00) Osaka, Sapporo, Tokyo
240Yakutsk Standard Time(GMT+09:00) Yakutsk
245A.U.S. Central Standard Time(GMT+09:30) Darwin
250Cen. Australia Standard Time(GMT+09:30) Adelaide
255A.U.S. Eastern Standard Time(GMT+10:00) Canberra, Melbourne, Sydney
260E. Australia Standard Time(GMT+10:00) Brisbane
265Tasmania Standard Time(GMT+10:00) Hobart
270Vladivostok Standard Time(GMT+10:00) Vladivostok
275West Pacific Standard Time(GMT+10:00) Guam, Port Moresby
280Central Pacific Standard Time(GMT+11:00) Magadan, Solomon Islands, New Caledonia
285Fiji Islands Standard Time(GMT+12:00) Fiji Islands, Kamchatka, Marshall Islands
290New Zealand Standard Time(GMT+12:00) Auckland, Wellington
300Tonga Standard Time(GMT+13:00) Nuku'alofa

2015년 9월 30일 수요일

[ERROR]원격 서버에서 (400) 잘못된 요청 오류를 반환했습니다. Azure storage

컨테이너의 이름은 항상 소문자여야 한다. 컨테이너 이름에 대문자를 포함하거나 컨테이너 명명 규칙을 위반하는 경우에 400 오류(잘못된 요청) 메시지를 받을 수 있다.

2015년 9월 13일 일요일

EF 6 Stored Procedure



단일값 반환
var param = new SqlParameter { ParameterName = "idx", Value = 1 };
var result = context.Database.SqlQuery("ProcedureName @idx", param);
return result.FirstOrDefaultAsync().Result;

리스트 반환
context.Database.SqlQuery("GetPerson").AsQueryable();

Output parameter
var param = new SqlParameter { ParameterName = "idx", Value = 1 };
var output_param = new SqlParameter { ParameterName = "ResultCode", Value = 0, Direction = ParameterDirection.Output };
var result = context.Database.SqlQuery("GetPersons @idx, @ResultCode out", param, output_param).AsQueryable();

var resultCode = (int)output_param.Value;

위도(Latitude)와 경도(Longitude) 값을 이용한 거리계산



public double GetDistance(double lat1, double lon1, double lat2, double lon2)
        {
            double theta, dist;
            theta = lon1 - lon2;
            
            dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1))
                 * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));
            dist = Math.Acos(dist);
            dist = rad2deg(dist);

            dist = dist * 60 * 1.1515;
            dist = dist * 1.609344;    // 단위 mile 에서 km 변환.  
            dist = dist * 1000.0;      // 단위  km 에서 m 로 변환  

            return dist;
        }
        /// 
        /// 주어진 Degree 값을 Radian 값으로 변환
        /// 
        /// Degree
        /// Radian
        private double deg2rad(double deg)
        {
            return (double)(deg * Math.PI / (double)180d);
        }
        /// 
        /// 주어진 Radian 값을 Degree 값으로 변환
        /// 
        /// Radian value
        /// Degree
        private double rad2deg(double rad)
        {
            return (double)(rad * (double)180d / Math.PI);
        }

2015년 9월 8일 화요일

The database could not be exclusively locked to perform the operation. (Microsoft SQL Server, Error: 5030)



Setp 1.
 ALTER DATABASE dbName
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Setp 2.
 ALTER DATABASE OldDbName MODIFY NAME = NewDbName
Setp 3.
 ALTER DATABASE dbName
SET MULTI_USER WITH ROLLBACK IMMEDIATE

2015년 9월 7일 월요일

CSV to MSSql (CSV파일을 이용한 테이블 Insert)



 BULK INSERT dbo.tableName FROM 'C\fileName.CSV' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')

2015년 9월 3일 목요일

C# GUID



GUID : 사용할 수 있는 값의 수가 2120  임으로 적절한 알고리즘이 있다면 같은 값을 두번 생성 할 가능성은 매우 적다.

생성방법 :
    GUID guid = GUID.NewGuid()


출력예(36자) : 95267ea6-5bfe-47db-8794-7e08404672c3

2015년 9월 2일 수요일

OLE DB provider SQLNCLI11 for linked server unable to begin distributed transaction.


1. Start\Administrative Tools\Component Services

   - Right click on the Local DTC
   - Select Security tab, 아래 두번째 이미지에서와 같이 체크하고 OK.




2. Control Panel\Windows Firewall\Allow an app or feature through Windows Farewall
   - Check Distributed Transaction Coordinator (Private & Public)

2015년 8월 29일 토요일

소스코드 실행 시간 확인 Stopwatch



 Stopwatch stopwatch = Stopwatch.StartNew();
       ..............................

stopwatch.Stop();
Console.WriteLine("실행시간 : ", stopwatch.ElapsedMilliseconds);

2015년 8월 25일 화요일

ASP.NET Web api에서 항상(Chrome, Safari등에서) Json타입으로 반환하는 방법


방법 : App_Start/WebApiConfig.cs파일을 다음과 같이 수정하면 된다.
즉 아래 코드세서와 같이 4번 라인을 추가하면 된다.
 public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

2015년 8월 23일 일요일

특정 문자열이 포함된 프로시저(Procedure) 찾기


방법-1 : VARCHAR(4000)이상의 크기를 가진 프로시저는 찾아내지 못함

 SELECT ROUTINE_NAME

 FROM INFORMATION_SCHEMA.ROUTINES

 WHERE ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_DEFINITION LIKE '%문자열%'

 ORDER BY ROUTINE_NAME


방법-2 : 같은 단어가 여러개 있을 경우 결과도 여러번 나옴
 SELECT A.NAME

 FROM dbo.SYSOBJECTS AS A

 INNER JOIN dbo.SYSCOMMENTS AS B

 ON A.ID = B.ID

 WHERE A.TYPE = 'P' AND B.TEXT LIKE '%문자열%'

 ORDER BY A.NAME