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

2015년 6월 23일 화요일

MSSQL 임의의 한개의 ROW SELECT




SELECT TOP(1) [columns] FROM [table_name]
ORDER BY NEWID()

2015년 5월 21일 목요일

C# Get Clinent MacAddress




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Net.NetworkInformation;

namespace test
{
    public static class MacAddress
    {
        public static string GetMacAddress()
        {
            const int MIN_MAC_ADDR_LENGTH = 12;
            string    macAddress          = string.Empty;
            long      maxSpeed            = -1;

            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                string tempMac = nic.GetPhysicalAddress().ToString();
                if (nic.Speed > maxSpeed && !string.IsNullOrEmpty(tempMac) && tempMac.Length >= MIN_MAC_ADDR_LENGTH)
                {
                    maxSpeed   = nic.Speed;
                    macAddress = tempMac;
                }
            }
            return macAddress;
        }
    }
}

2015년 4월 7일 화요일

Update(), FixedUpdate(), LateUpdate()의 차이





Update() - 매 프레임마다 한번씩 호출되는 함수. 프레임단위로 호출되기 때문에 이전 프레임과의 시간차가 일정하지 않으므로 TIme.deltaTime을 사용하여 이전 프레임과의 시간차를 확인하여 사용해야한다.


FixedUpdate() - 매 프레임별로 호출되지만 시간차가 부정확한 Update와는 달리 일정한 시간 간격차를 두고 한번씩 호출되는 함수. Framerate가 낮으면 한 프레임에 여러번 불려질 수 있으며 Framerate가 높으면 한 프레임에 호출이 없을수도 있다. 이러한 Framerate와 독립적인 타이머에 의한 호출때문에 Time.deltaTime이 많이 필요한 모든 물리적 연산과 업데이트는 FixedUpdate()가 호출이 완료된 다음 이루어진다.
(Framerate와 독립적이기 때문에 FixedUpdate()메소드 안에선 Time.deltaTime을 사용할 필요가 없다.)


LateUpdate() - Update와 마찬가지로 매 프레임마다 한번씩 호출되는 함수이지만, Update가 호출이 완료된 이후에 호출되는 특징을 갖고있다.
주로 Update()에서 캐릭터를 움직인다음, LateUpdate()에서 카메라를 이동시킨다거나 하는 용도로 사용한다.
(LateUpdate()에서 카메라를 이동시키는 이유는 Update()에서 캐릭터가 이동했다고 확실하게 신뢰할수 있기 때문.)

2015년 1월 9일 금요일

참조 전달인자는 언제 사용하는가?

참조 전달인자를 사용하는 주된 이유 두가지:

  • 호출 함수에 있는 데이터 객체의 변경을 허용하기 위해
  • 전체 데이터 객체 대신에 참조를 전달하여 프로그램의 속도를 높이기 위해





함수가 전달된 데이터를 변경하지 않고 사용만 하는 경우:

  • 데이터 객체가 기본 데이터형이나 작은 구조체라면 값으로 전달한다.
  • 데이터 객체가 배열이라면 포인터가 유일한 선택이므로 포인터를 사용한다. 포인터를 const를 지시하는 포인터로 만든다.
  • 데이터 객체가 덩치 큰 구조체라면 const 포인터나 const 참조를 사용하여 프로그램의 속도를 높인다.
  • 데이터 객체가 클래스 객체라면 const 참조를 사용한다.

함수가 호출 함수의 데이터를 변경하는 경우:

  • 데이터 객체가 기본 데이터형이면 포인터를 사용한다.
  • 데이터 객체가 배열이면 유일한 선택은 포인터를 사용하는 것이다.
  • 데이터 객체가 구조체이면 참조 또는 포인터를 사용한다.
  • 데이터 객체가 클래스 객체이면 참조를 사용한다.