posted by 네코냥이 2014. 2. 8. 07:30

using 문을 사용해서 연결객체를 인자로 넘기고 트랜잭션을 처리 할것이다.

아래는 그 예제에 대한 간단한 함수의 내용이다. 트랜잭션 클래스는 SqlTransaction 이며
SqlConnection 객체의 BeginTransaction 함수를 써서 시작한다. 그리고 리턴받은
SqlTrannsaction 객체로 Commit 함수를 호출해 실행한후 SqlConnection을 닫으면 된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public void TotalDBExecute()
{
    string updateSql = "UPDATE Categories SET CategoryName = 'Car' WHERE CategoryID = 10";
    string deleteSql = "DELETE Categories WHERE CategoryID = 10";
    string conn = @"Server=222.232.2.22;Database=test;user=testuser;password=1111;Integrated Security=SSPI;";
 
    using (SqlConnection con = new SqlConnection(conn))
    {
        con.Open();
 
        // SqlTrasaction 클래스의인스턴스생성
        SqlTransaction tran = con.BeginTransaction(); // 트랜잭션시작
        SqlCommand cmd = new SqlCommand();
 
        cmd.Connection = con;
        cmd.Transaction = tran; // 현재사용할트랜잭션객체지정
 
        try
        {
            cmd.CommandText = updateSql;// 쿼리지정
            cmd.ExecuteNonQuery(); // 실행
 
            cmd.CommandText = deleteSql;
            cmd.ExecuteNonQuery();
 
            tran.Commit(); // 트랜잭션commit
        }
        catch (Exception ex)
        {
            tran.Rollback(); // 에러발생시rollback
        }
    }
}


'.NET > C#' 카테고리의 다른 글

ASP.NET 2.0 DataTable => JSON 변환  (0) 2014.03.11
DB 프로시저 실행  (0) 2014.02.11
XML 유효성 및 자식노드 개수 체크  (0) 2014.01.17
[C#] Anonymous Types in C#  (2) 2014.01.06
[C#] 델리게이트 일부내용  (0) 2014.01.06
posted by 네코냥이 2014. 1. 17. 11:32

// XML 유효성 및 자식노드 개수 체크


XmlDocument xml = new XmlDocument();

        try

        {

            xml.LoadXml(CATE_INIT_XML.ToUpper());

            if (

                xml.SelectNodes("/ROOT/DATA").Count > MAX_ITEM_CNT)

            {

                String alertMsg = "자식노드가 지정한 한계보다 많습니다.";

                // Alert(this, alertMsg);

               // return false;

            }

        }

        catch (XmlException xe)

        {

           //Alert(String.Format("XML 파싱오류 {0}-{1}", xe.LineNumber, xe.Message));

           // return false;

        }

        catch (Exception ex)

        {

            //Alert(String.Format("XML 파싱오류 {0}-{1}", "197", ex.Message));

            // return false;

        }

'.NET > C#' 카테고리의 다른 글

DB 프로시저 실행  (0) 2014.02.11
DB 트랜젝션  (0) 2014.02.08
[C#] Anonymous Types in C#  (2) 2014.01.06
[C#] 델리게이트 일부내용  (0) 2014.01.06
[C#] Read only and const variable  (0) 2014.01.06
posted by 네코냥이 2014. 1. 6. 16:58


Anonymous Types in C#.pdf



'.NET > C#' 카테고리의 다른 글

DB 트랜젝션  (0) 2014.02.08
XML 유효성 및 자식노드 개수 체크  (0) 2014.01.17
[C#] 델리게이트 일부내용  (0) 2014.01.06
[C#] Read only and const variable  (0) 2014.01.06
[C#] Ref and Out Parameters  (0) 2014.01.06
posted by 네코냥이 2014. 1. 6. 16:56

C# has a data type that allows developers to pass methods as parameters of other methods. This data type is called a delegate. A delegate is a reference type. 

Delegates are used to encapsulate and pass methods as parameters to other methods. A delegate can encapsulate a named or an anonymous method. You're most likely to use a delegate in events or callbacks.

Delegates are used to encapsulate and pass methods as parameters to other methods. 

The delegate keyword is used to define a delegate type. A delegate type defines a method signature and when you create an instance of a delegate, you can associate with any method that has same signature. The method is invoked though the delegate instance. 

Let's say, we have a method called AddNumbers that adds two numbers. The following code snippet defines the AddNumbers method that returns a sum of the two integer parameters. 

public static int AddNumbers(int a, int b)
{
    return a + b;
} 

We want to use this method in a delegate. 

We need to first ensure we define a delegate with the same signature. The following code snippet declares a delegate that has the same signature as the AddNumbers method. 

public delegate int DelegateInt(int a, int b); 

Now we need to define a delegate caller method that uses the preceding declared delegate as a parameter. The following code snippet defines a method that takes three parameters. The first two parameters are integer values and the third parameter is a delegate of type DelegateInt. 

public static void DelegateCallerMethod(int a, int b, DelegateInt DelInt)
{
    Console.WriteLine(DelInt(a, b));
} 

Until now, our delegate has no idea of what it will be doing. All it knows is that it wraps a method that takes two integer values. 

Now, to do the actual work, we must create an instance of the delegate by passing a method with similar signature.

The following code snippet creates a DelegateInt instance and passes the AddNumbers method. Now the delegate knows what method to execute when it is called. 

DelegateInt dm = AddNumbers; 

The following code is a call to the DelegateCallerMethod that takes a delegate as the third parameter that actually is the AddNumbers method. 

DelegateCallerMethod(3, 6, dm); 

You may not find a delegate useful everywhere but it is very important in events and callbacks when you want to force some events to be executed. Delegates also play a major role in LINQ. 

The following code lists the complete sample. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 

namespace DelegatesSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a delegate and assign a method
            DelegateInt dm = AddNumbers;
            DelegateCallerMethod(3, 6, dm); 

            Console.ReadKey();

        } 

        // Define a delegate. It has same signature as AddNumbers method
        public delegate int DelegateInt(int a, int b);       

        // Method that will be used to assign to a delefate
        public static int AddNumbers(int a, int b)
        {
            return a + b;
        } 

        // Call delegate by passing delegate
        public static void DelegateCallerMethod(int a, int b, DelegateInt DelInt)
        {
            Console.WriteLine(DelInt(a, b));
        }
    }
} 

Summary

In this article, I explained the basics of delegates and how to use them in your code. Delegates are heavily used in events. Here is one detailed article on delegates and events. 

Delegates and Events in C# and .NET

'.NET > C#' 카테고리의 다른 글

XML 유효성 및 자식노드 개수 체크  (0) 2014.01.17
[C#] Anonymous Types in C#  (2) 2014.01.06
[C#] Read only and const variable  (0) 2014.01.06
[C#] Ref and Out Parameters  (0) 2014.01.06
[C#] 바이트 측정  (0) 2014.01.02
posted by 네코냥이 2014. 1. 6. 16:48


Read only and const variable in C#.pdf


차이라곤 선언할 때, 인스턴트를 이용할 수 있냐?

(원리는 컴파일 수준에서 값이 대입되냐, 런타임에서 대입되냐)



'.NET > C#' 카테고리의 다른 글

[C#] Anonymous Types in C#  (2) 2014.01.06
[C#] 델리게이트 일부내용  (0) 2014.01.06
[C#] Ref and Out Parameters  (0) 2014.01.06
[C#] 바이트 측정  (0) 2014.01.02
[C#] 정규식  (0) 2013.11.06
posted by 네코냥이 2014. 1. 6. 16:39


Ref and Out Parameters in C#.pdf


Ref 키워드는 Call by Refference 주소를 통한 접근

Out 키워드는 마지막에 해당 인자에 값만 전달. ms-sql과 동일

'.NET > C#' 카테고리의 다른 글

[C#] 델리게이트 일부내용  (0) 2014.01.06
[C#] Read only and const variable  (0) 2014.01.06
[C#] 바이트 측정  (0) 2014.01.02
[C#] 정규식  (0) 2013.11.06
[C#] [스크랩] C# - JSON for .NET  (0) 2013.10.11
posted by 네코냥이 2014. 1. 2. 13:16


You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding class.

or try this

  System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
  System.Text.ASCIIEncoding.ASCII.GetByteCount(string);

익명의 제보
=> 인코딩 직접 지정.
public static readonly Encoding euckr = Encoding.GetEncoding("EUC-KR");
euckr.GetByteCount(string);


'.NET > C#' 카테고리의 다른 글

[C#] Read only and const variable  (0) 2014.01.06
[C#] Ref and Out Parameters  (0) 2014.01.06
[C#] 정규식  (0) 2013.11.06
[C#] [스크랩] C# - JSON for .NET  (0) 2013.10.11
[스크랩] [C#] HTTP/HTTPS 송수신 (HttpWebRequest/HttpWebResponse)  (0) 2013.10.11
posted by 네코냥이 2013. 11. 6. 10:28


Regular Expressions.pdf


posted by 네코냥이 2013. 10. 11. 15:23


C# - JSON for .pdf


'.NET > C#' 카테고리의 다른 글

[C#] 바이트 측정  (0) 2014.01.02
[C#] 정규식  (0) 2013.11.06
[스크랩] [C#] HTTP/HTTPS 송수신 (HttpWebRequest/HttpWebResponse)  (0) 2013.10.11
[영어, 영상] What is new in C# 6.0  (0) 2013.08.20
[C#] How to display an XML file to Console  (0) 2013.07.24
posted by 네코냥이 2013. 10. 11. 14:04


[C#] http,https 송수신.pdf



밑에 소스는 Google Oauth 2.0 인증과 관련해서 RefeshToken 값을 이용해 AccessToken 값을 구하는 구

글 API입니다.

"####################################" 이 들어간 문자는 중요한 값이라 일부러 숨

겼습니다.

"대충 이런식으로 쓴다" 정도로 봐주시면 감사하겠습니다.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
 
namespace Http_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            // 요청을 보내는 URI
            string strUri = "https://accounts.google.com/o/oauth2/token";
 
            // POST, GET 보낼 데이터 입력
            StringBuilder dataParams = new StringBuilder();
            dataParams.Append("client_id=#############################################");
            dataParams.Append("&client_secret=####################################");
            dataParams.Append("&refresh_token=####################################");
            dataParams.Append("&grant_type=refresh_token");
 
            // 요청 String -> 요청 Byte 변환
            byte[] byteDataParams = UTF8Encoding.UTF8.GetBytes(dataParams.ToString());
 
            /////////////////////////////////////////////////////////////////////////////////////
            /* POST */
            // HttpWebRequest 객체 생성, 설정
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUri);
            request.Method = "POST";    // 기본값 "GET"
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteDataParams.Length;
 
            /* GET */
            // GET 방식은 Uri 뒤에 보낼 데이터를 입력하시면 됩니다.
            /*
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUri + "?" + dataParams);
            request.Method = "GET";
            */
            //////////////////////////////////////////////////////////////////////////////////////
             
 
            // 요청 Byte -> 요청 Stream 변환
            Stream stDataParams = request.GetRequestStream();
            stDataParams.Write(byteDataParams, 0, byteDataParams.Length);
            stDataParams.Close();
 
            // 요청, 응답 받기
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
             
            // 응답 Stream 읽기
            Stream stReadData = response.GetResponseStream();
            StreamReader srReadData = new StreamReader(stReadData, Encoding.Default);
 
            // 응답 Stream -> 응답 String 변환
            string strResult = srReadData.ReadToEnd();
 
            Console.WriteLine(strResult);
            Console.ReadLine();
        }
    }
}


'.NET > C#' 카테고리의 다른 글

[C#] 정규식  (0) 2013.11.06
[C#] [스크랩] C# - JSON for .NET  (0) 2013.10.11
[영어, 영상] What is new in C# 6.0  (0) 2013.08.20
[C#] How to display an XML file to Console  (0) 2013.07.24
Disposing DataContext/ObjectContext  (0) 2013.06.26