레이블이 C#인 게시물을 표시합니다. 모든 게시물 표시
레이블이 C#인 게시물을 표시합니다. 모든 게시물 표시

2024년 6월 27일 목요일

C# - 기본 및 활용

 
//-----------------------------------------------
        [AllowAnonymous]
        public ActionResult 함수_페이지(string reftype = null)
        {
            return View(new Tuple<클래스타입1, 클래스타입2[], 클래스타입3[], 클래스타입4[]>(객체1, 객체2, 객체3, 객체4));
        }
        @using Model.Common
        @model Tuple<클래스타입1, 클래스타입2[], 클래스타입3[], 클래스타입4[]>


//-----------------------------------------------
        [AllowAnonymous, ChildActionOnly]
        public PartialViewResult 함수_Partial()
        {
            return PartialView(new Tuple<Banner>(adBanner));
        }
        @using Model.Common
        @model Tuple<Banner>

        @Html.Action("함수_Partial", "Main")

//-----------------------------------------------
        [HttpPost]
        public JsonResult 함수_기능(int Idx)
        {
            //return Json(new {객체1, 객체2});
            return Json(객체);
        }

//-----------------------------------------------
        [NonAction]
        private object 함수_기능()
        {
            return list.Select(x => new
            {
                PROD_NUM = x.PROD_NUM,
                IDX = x.IDX
            });
        }


//-----------------------------------------------
[FilterConfig.cs]
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class UserAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        public RoleType Role { get; set; }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if ((Role & RoleType.Wos) == RoleType.Wos)
            {
                if (!객체.IsWos) // Wos가 아니면
                {
                    throw new Exception("Wos 권한이 없습니다.");
                }
            }
        }
    }

    [Flags]
    public enum RoleType
    {
        Wos
    }


[View1.cs]
        [UserAuthorization(Role = RoleType.Wos)]
        public ActionResult WosCart(string cList)
        {
            ViewBag.Name = Common.객체1.Name;
            return View(Json(cList));
        }



//-----------------------------------------------
        private Dictionary<string, string> GetParameterResultMap(string parameter)
        {
            // + 기호가 공백으로 넘어 오는경우 처리
            string decString = parameter.Replace(" ","+");
            Dictionary<string, string> resultMap = parseStringToMap(decString);
            return resultMap;
        }

        public static System.Collections.Generic.Dictionary<string, string> parseStringToMap(string text)
        {
            System.Collections.Generic.Dictionary<string, string> retMap = new System.Collections.Generic.Dictionary<string, string>();
            if (string.IsNullOrEmpty(text) || string.IsNullOrWhiteSpace(text))
                return retMap;
            string[] arText = text.Split('&');
            for (int i = 0; i < arText.Length; i++)
            {
                string[] arKeyVal = arText[i].Split('=');
                retMap.Add(arKeyVal[0], arKeyVal[1]);
            }
            return retMap;
        }




//-----------------------------------------------
    public enum CancelState : int
    {
        [Description("취소요청")]
        RequestCancel = 0,
        [Description("취소대기")]
        ProcessingCancel = 1,
        [Description("취소불가")]
        ImpossibleCancel = 2,
        [Description("취소완료")]
        CompleteCancel = 3
    }




//-----------------------------------------------
    public class InicisRequest
    {
        #region 기본 데이터 필드
        [Required]
        [StringLength(20)]
        public string version { get; set; }
        [Required]
        [StringLength(10)]
        public string mid { get; set; }
        [Required]
        public int price { get; set; }
        public int tax { get; set; }
        #endregion
    }



2023년 12월 18일 월요일

c# - BaseController (Authorization)

 

로그인을 해야지만 접속이 가능한 Controller에 상속한 BaseController를 만든다. 

 

1. BaseController.cs

    public class BaseController : Controller
    {
        public string actionName { get; protected set; }
        public string controllerName { get; protected set; }

        protected override void OnActionExecuting(ActionExecutingContext filter)
        {
            
            //로그인 체크
            LogonCheck(filter);

			//DoNotAuthorizeAttribute가 설정되어 있으면 접속권한 체크하지 않는다. 
            if (filter.ActionDescriptor.GetCustomAttributes(true).Any(x => x is DoNotAuthorizeAttribute))
            {
                return;
            }

			//Ajax 호출은 접속권한 체크하지 않는다. 
            if (filter.HttpContext.Request.IsAjaxRequest())
            {
                return;
            }

            //메뉴 권한체크 추가 
            CheckAccessAuth(filter);
        }

        private void LogonCheck(ActionExecutingContext filter)
        {

            if (!isLogin) //session or cookie로 로그인 여부 확인
            {

                var routeDictionary = new RouteValueDictionary { { "action", "Logout" }, { "controller", "Account" } };
                //강제 로그아웃 시킨다. 
                filter.Result = new RedirectToRouteResult(routeDictionary);

                return;
            }
        }

        private void CheckAccessAuth(ActionExecutingContext filter)
        {
            //컨트롤러, 액션
            actionName = filter.ActionDescriptor.ActionName;
            controllerName = filter.ActionDescriptor.ControllerDescriptor.ControllerName;
			
            //로그인 계정정보, controller, action 정보로 접속권한 db 체크 
            if (!CanAccessMenu(loginInfo, controllerName, actionName)) {

                //권한없을 경우는 로그인 말고 다른페이지로 이동
                var routeDictionary = new RouteValueDictionary() { { "action", "NotAuthorized" }, { "controller", "Account" } };
                filter.Result = new RedirectToRouteResult(routeDictionary);
                return;
            }
        }
    }

 

2. 권한체크 필요한 Controller에서 BaseController 상속받는다. 

 

    public class NoticeController : BaseController
    {
    
    }

 

출처 : https://bigexecution.tistory.com/78


C# - Dapper Helper Class #3 (DapperManager 예문)

 

1. Nuget 패키지 관리자에서 Dapper 설치

.NET Framework에 맞는 버전으로 설치

 

2. DapperManager.cs

    public class DapperManager
    {
        public string DBConn = "DBNAME";
        public SqlConnection con;

        public DapperManager(DB_StrName eDB)
        {
            DBConn = eDB.ToString();
        }

        private SqlConnection SqlConnection()
        {
            return new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[DBConn].ConnectionString);
        }

        /// <summary>
        /// Open new connection and return it for use
        /// </summary>
        /// <returns></returns>
        private IDbConnection CreateConnection()
        {
            var conn = SqlConnection();
            conn.Open();
            return conn;
        }

        public IEnumerable<T> GetAll<T>(string selectQuery)
        {
            using (var connection = CreateConnection())
            {
                return connection.Query<T>(selectQuery);
            }
        }

        public int GetCount(string selectQuery)
        {
            using (var connection = CreateConnection())
            {
                return connection.Query(selectQuery).Count();
            }
        }
        public T GetByIdx<T>(int idx, string tableName, string idxColumnName = null)
        {
            using (var connection = CreateConnection())
            {
                string columnName = string.IsNullOrEmpty(idxColumnName) ? "idx" : idxColumnName;
                return connection.QuerySingleOrDefault<T>($"SELECT * FROM {tableName} WHERE {columnName} = @Idx", new { Idx = idx });
            }
        }
        public T GetById<T>(string id, string tableName, string idColumnName)
        {
            using (var connection = CreateConnection())
            {
                return connection.QuerySingleOrDefault<T>($"SELECT * FROM {tableName} WHERE {idColumnName} = @Id", new { Id = id });
            }
        }

        public int AddRow<T>(string insertQuery, T entity)
        {
            using (var connection = CreateConnection())
            {
                int affectedRows = connection.Execute(insertQuery, entity);
                return affectedRows;
            }
        }

        public int UpdateRow<T>(string updateQuery, T entity)
        {
            using (var connection = CreateConnection())
            {
                int affectedRows = connection.Execute(updateQuery, entity);
                return affectedRows;
            }
        }

        public int DeleteRow(int idx, string tableName, string idxColumnName = null)
        {
            using (var connection = CreateConnection())
            {
                string columnName = string.IsNullOrEmpty(idxColumnName) ? "idx" : idxColumnName;
                int affectedRows = connection.Execute($"DELETE FROM {tableName} WHERE {columnName} = @Idx", new { Idx = idx });
                return affectedRows;
            }
        }

        public IEnumerable<T> ExecuteProcedure<T>(string storedProcedure, object parameters = null)
        {
            int commandTimeout = 180;

            using (var connection = CreateConnection())
            {
                if (parameters != null)
                {
                    return connection.Query<T>(storedProcedure, parameters,
                        commandType: CommandType.StoredProcedure, commandTimeout: commandTimeout);
                }
                else
                {
                    return connection.Query<T>(storedProcedure,
                        commandType: CommandType.StoredProcedure, commandTimeout: commandTimeout);
                }
            }
        }

    }

3. NoticeDTO.cs

    public class Notice
    {
        public int idx_num { get; set; }
        public string title { get; set; }
        public string contents { get; set; }
        public string file1 { get; set; }
        public DateTime reg_date { get; set; }
        public DateTime mod_date { get; set; }
    }

 

4. NoticeDA.cs

        #region 공지사항 등록하기
        public static int Add_Notice(Notice notice)
        {
            DapperManager dm = new DapperManager("DBNAME");
            var insertQuery = "INSERT INTO NOTICE(title, contents, file1, reg_Date, mod_date, click_count) VALUES (@title, @contents, @file1, @reg_Date, @mod_date, 0)";
            return dm.AddRow<Notice>(insertQuery, notice);
        }
        #endregion

        #region 공지사항 수정하기
        public static int Update_Notice(Notice notice)
        {
            DapperManager dm = new DapperManager("DBNAME");
            var updateQuery = "UPDATE NOTICE SET title = @title, file1 = @file1, contents = @contents WHERE idx_num = @idx_num";
            return dm.UpdateRow<Notice>(updateQuery, notice);
        }
        #endregion
        
        #region 공지사항 삭제하기
        public static int Delete_Notice(int idx)
        {
            DapperManager dm = new DapperManager("DBNAME");
            return dm.DeleteRow(idx, "NOTICE", "idx_num");
        }
        #endregion
        
        #region 공지사항 가져오기
        public static Notice Get_Notice(int idx)
        {
            DapperManager dm = new DapperManager("DBNAME");
            return dm.GetByIdx<Notice>(idx, "NOTICE", "idx_num");
        }
        #endregion

 

출처 : https://bigexecution.tistory.com/79



2023년 9월 25일 월요일

C# - HtmlTemplate

 
[HtmlTemplate 예문]


using System;
using System.IO;
public class HtmlTemplate
{
    private string _html;
    public HtmlTemplate(string templatePath)
    {
        using (var reader = new StreamReader(templatePath))
            _html = reader.ReadToEnd();
    }
    public string Render(object values)
    {
        string output = _html;
        foreach (var p in values.GetType().GetProperties())
            output = output.Replace("[" + p.Name + "]", (p.GetValue(values, null) as string) ?? string.Empty);
        return output;
    }
}
public class Program
{
    void Main()
    {
        var template = new HtmlTemplate(@"C:\MyTemplate.txt");
        var output = template.Render(new {
            TITLE = "My Web Page",
            METAKEYWORDS = "Keyword1, Keyword2, Keyword3",
            BODY = "Body content goes here",
            ETC = "etc"
        });
        Console.WriteLine(output);
    }
}

Using this, all you have to do is create some HTML templates and fill them with replaceable tokens such as [TITLE], [METAKEYWORDS], etc. Then pass in anonymous objects that contain the values to replace the tokens with. You could also replace the value object with a dictionary or something similar.


출처 : https://stackoverflow.com/questions/897226/generating-html-using-a-template-from-a-net-application





  • dotliquid: .NET port of the liquid templating engine
  • Fluid .NET liquid templating engine
  • Nustache: Logic-less templates for .NET
  • Handlebars.Net: .NET port of handlebars.js
  • Textrude: UI and CLI tools to turn CSV/JSON/YAML models into code using Scriban templates
  • NTypewriter: VS extension to turn C# code into documentation/TypeScript/anything using Scriban templates

예문 : https://scribanonline.azurewebsites.net

출처 : https://github.com/scriban/scriban






2023년 3월 17일 금요일

HTML - 엑셀 다운로드 시 한글 깨짐 현상 (여러가지 처리 방법)


<ASP - euc-kr 기준>

[#1]

<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=euc-kr">
or
<meta http-equiv="content-type" content="text/html; charset=euc-kr"> 


[#2]

Response.Buffer = True
Response.CharSet = "euc-kr"
'Response.CacheControl = "public"
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment;filename=엑셀파일명.xls"


[#3]

Session.CodePage = 949



<ASP - utf-8 기준>

[#1]

<meta http-equiv="Content-Language" content="ko">

FileName = Server.urlEncode("한글깨짐방지")
or
FileName = Server.URLPathEncode("한글깨짐방지")




<C# 기준>


[#1]

<meta name="viewport" http-equiv="Content-Type" content="text/html; charset=utf-8" />
or
<meta name="viewport" http-equiv="Content-Type" content="text/html; charset=euc-kr" />


[#2]

Response.Charset = "euc-kr";   
Response.ContentType = "application/vnd.ms-excel"; 
Response.ContentEncoding = System.Text.Encoding.GetEncoding("euc-kr"); 


[#3]

Response.Clear();
Response.ClearHeaders();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + "파일명_" + DateTime.Now.ToString("yyyy_MM_dd") + ".xls");
Response.Charset = "utf-8";
Response.ContentType = "application/vnd.xls";
 
string table = @"<Table><tr><td>111</td></tr><tr><td>222</td></tr></Table>";
Response.Write(table);
Response.End();











2023년 2월 24일 금요일

C# - string.Format


int a = 10;

int b = 20;


// [1] 문자열에 변수를 적용하는 기본 방법

string s = string.Format("{0} + {1} = {2}", a, b, a+b);


// [2] 문자열에 직접 변수를 사용하고 할 경우 (조금 더 직관적)

string s = string.Format($"{a} + {b} = {a+b}");


// [3] 여러 줄의 문자열로 구성된 내용을 표시 할 경우의 기본 방법

StringBuilder sb = new StringBuilder();

sb.Append("<table>");

sb.Append("<tr>");

sb.Append("<td>");

sb.Append("a=" + a + ", b=" + b);

sb.Append("</td>");

sb.Append("</tr>");

sb.Append("</table>");


// [4] 여러 줄의 문자열로 구성된 내용을 표시 할 경우 (조금 더 직관적)

string s = string.Format($@"

    <table>

        <tr>

            <td>

            a={a}, b={b}

            <td>

        </tr>

    </table>

               ");


[추가 설명]

$ : 문자열에 직접 변수를 사용하고 할 경우

@ : 여러 문자열을 화면에 표현되는 그대로 인식하고자 할 경우



2022년 12월 5일 월요일

C# - 클래스, 함수, 권한 등 사용 예문

 
//-----------------------------------------------
        [AllowAnonymous]
        public ActionResult 함수_페이지(string reftype = null)
        {
            return View(new Tuple<클래스타입1, 클래스타입2[], 클래스타입3[], 클래스타입4[]>(객체1, 객체2, 객체3, 객체4));
        }
        @using Model.Common
        @model Tuple<클래스타입1, 클래스타입2[], 클래스타입3[], 클래스타입4[]>


//-----------------------------------------------
        [AllowAnonymous, ChildActionOnly]
        public PartialViewResult 함수_Partial()
        {
            return PartialView(new Tuple<Banner>(adBanner));
        }
        @using Model.Common
        @model Tuple<Banner>


        @Html.Action("함수_Partial", "Main")


//-----------------------------------------------
        [HttpPost]
        public JsonResult 함수_기능(int Idx)
        {
            //return Json(new {객체1, 객체2});
            return Json(객체);
        }


//-----------------------------------------------
        [NonAction]
        private object 함수_기능()
        {
            return list.Select(x => new
            {
                PROD_NUM = x.PROD_NUM,
                IDX = x.IDX
            });
        }


//-----------------------------------------------
[FilterConfig.cs]
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class UserAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        public RoleType Role { get; set; }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if ((Role & RoleType.Wos) == RoleType.Wos)
            {
                if (!전역_객체.IsWos) // Wos가 아니면
                {
                    throw new Exception("Wos 권한이 없습니다.");
                }
            }
        }
    }

    [Flags]
    public enum RoleType
    {
        Wos
    }


[View1.cs]
        [UserAuthorization(Role = RoleType.Wos)]
        public ActionResult WosCart(string cList)
        {
            ViewBag.Name = Common.객체1.Name;
            return View(Json(cList));
        }


//-----------------------------------------------
        private Dictionary<string, string> GetParameterResultMap(string parameter)
        {
            // + 기호가 공백으로 넘어 오는경우 처리
            string decString = parameter.Replace(" ","+");
            Dictionary<string, string> resultMap = parseStringToMap(decString);
            return resultMap;
        }

        public static System.Collections.Generic.Dictionary<string, string> parseStringToMap(string text)
        {
            System.Collections.Generic.Dictionary<string, string> retMap = new System.Collections.Generic.Dictionary<string, string>();
            if (string.IsNullOrEmpty(text) || string.IsNullOrWhiteSpace(text))
                return retMap;
            string[] arText = text.Split('&');
            for (int i = 0; i < arText.Length; i++)
            {
                string[] arKeyVal = arText[i].Split('=');
                retMap.Add(arKeyVal[0], arKeyVal[1]);
            }
            return retMap;
        }


//-----------------------------------------------
    public enum CancelState : int
    {
        [Description("취소요청")]
        RequestCancel = 0,
        [Description("취소대기")]
        ProcessingCancel = 1,
        [Description("취소불가")]
        ImpossibleCancel = 2,
        [Description("취소완료")]
        CompleteCancel = 3
    }


//-----------------------------------------------
    public class InicisRequest
    {
        #region 기본 데이터 필드
        [Required]
        [StringLength(20)]
        public string version { get; set; }
        [Required]
        [StringLength(10)]
        public string mid { get; set; }
        [Required]
        public int price { get; set; }
        public int tax { get; set; }
        :
        #endregion
    }


2022년 9월 16일 금요일

C# - SameSiteMode

 

쿠키의 SameSite 특성에 대한 값을 나타내는 상수를 지정합니다.


public enum SameSiteMode

상속
 -> ValueType
 -> Enum
 -> SameSiteMode

필드

Lax1

쿠키는 "동일 사이트" 요청 및 "교차 사이트" 최상위 탐색과 함께 전송됩니다.

None0

쿠키가 모든 요청과 함께 전송됩니다(설명 참조).

Strict2

값이 Strict이면 쿠키는 "동일 사이트" 요청과 함께 전송됩니다.

설명

의 동작은 None kb 문서 4531182 및 kb 문서 4524421에 설명 된 업데이트에 의해 수정 되었습니다.

이러한 업데이트를 사용 하지 않으면 None 값이 쿠키 헤더를 내보내지 않습니다. SameSite

이는 준수 https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1 합니다.

이러한 업데이트를 적용 한 후에는 None 값이 SameSite=None 쿠키 헤더를 내보냅니다.

이 새 동작은를 준수 https://tools.ietf.org/html/draft-west-cookie-incrementalism-00 합니다. 

이러한 변경의 일환으로 양식 인증 및 SessionState 쿠키는 이전 기본값 대신 SameSite=를 사용 하여 발급 됩니다. Lax None

단, 이러한 값은 web.config에서 재 정의 할 수 있습니다.

이러한 업데이트가 적용 된 시스템에서는 를로 설정하여 이전 동작을 지정할 수 있습니다. SameSiteMode(SameSiteMode)(-1) 

web.config에서 문자열을 사용하여 이 동작을 지정할 수 있습니다 "Unspecified" .



[추가]

Unspecified  ( -1 )


Lax (느슨한)1

Indicates the client should send the cookie with "same-site" requests, and with "cross-site" top-level navigations.

클라이언트가 "동일한 사이트" 요청 및 "교차 사이트" 최상위 탐색과 함께 쿠키를 보내야 함을 나타냅니다.

None (없음)0

Indicates the client should disable same-site restrictions.

클라이언트가 동일 사이트 제한을 비활성화해야 함을 나타냅니다.

Strict (엄격한)2

Indicates the client should only send the cookie with "same-site" requests.

클라이언트가 "같은 사이트" 요청이 있는 쿠키만 보내야 함을 나타냅니다.

Unspecified (지정되지 않음)-1

No SameSite field will be set, the client should follow its default cookie policy.

SameSite 필드가 설정되지 않으며 클라이언트는 기본 쿠키 정책을 따라야 합니다.



2021년 11월 4일 목요일

C# - Dapper Helper Class #2

 

I organized a Dapper Helper class by myself

Link string configuration:

<connectionStrings>
    <add name="db" connectionString="server=.;database=db;uid=sa;pwd=123456;integrated security=false;"/>
  </connectionStrings>

DapperHelper.cs :

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
using Dapper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace PullChargeData.Helper
{
    public class DapperHelper<T>
    {
        /// <summary>
        /// Database connection string
        /// </summary>
        private static readonly string connectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
 
        /// <summary>
                 /// Query list (return to DataTable)
        /// </summary>
        /// <returns></returns>
        public static DataTable QueryToDataTable(string sql)
        {
            DataTable table = new DataTable("MyTable");
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                var reader = con.ExecuteReader(sql);
                table.Load(reader);
                return table;
            }
        }
 
        /// <summary>
                 /// Query list
        /// </summary>
                 /// <param name="sql">query sql</param>
                 /// <param name="param">Replace parameters</param>
        /// <returns></returns>
        public static List<T> Query(string sql, object param = null)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                return con.Query<T>(sql, param).ToList();
            }
        }
 
        /// <summary>
                 /// Query the first data
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T QueryFirst(string sql, object param = null)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                return con.Query<T>(sql, param).ToList().First();
            }
        }
 
        /// <summary>
                 /// The first data in the query did not return the default value
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T QueryFirstOrDefault(string sql, object param = null)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                return con.Query<T>(sql, param).ToList().FirstOrDefault();
            }
        }
 
        /// <summary>
                 /// Query a single data
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T QuerySingle(string sql, object param = null)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                return con.Query<T>(sql, param).ToList().Single();
            }
        }
 
        /// <summary>
                 /// Query a single piece of data does not return the default value
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T QuerySingleOrDefault(string sql, object param = null)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                return con.Query<T>(sql, param).ToList().SingleOrDefault();
            }
        }
 
        /// <summary>
                 /// Addition, deletion and modification
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns>Number of rows affected</returns>
        public static int Execute(string sql, object param)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                return con.Execute(sql, param);
            }
        }
 
        /// <summary>
                 /// Reader gets data
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static IDataReader ExecuteReader(string sql, object param)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                return con.ExecuteReader(sql, param);
            }
        }
 
        /// <summary>
                 /// Scalar gets data
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static object ExecuteScalar(string sql, object param)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                return con.ExecuteScalar(sql, param);
            }
        }
 
        /// <summary>
                 /// Scalar gets data
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T ExecuteScalarForT(string sql, object param)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                return con.ExecuteScalar<T>(sql, param);
            }
        }
 
        /// <summary>
                 /// Stored procedure with parameters
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static List<T> ExecutePro(string proc, object param)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                List<T> list = con.Query<T>(proc,
                    param,
                    null,
                    true,
                    null,
                    CommandType.StoredProcedure).ToList();
                return list;
            }
        }
 
 
        /// <summary>
                 /// Transaction 1-Full SQL
        /// </summary>
                 /// <param name="sqlarr">Multiple SQL</param>
        /// <param name="param">param</param>
        /// <returns></returns>
        public static int ExecuteTransaction(string[] sqlarr)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (var transaction = con.BeginTransaction())
                {
                    try
                    {
                        int result = 0;
                        foreach (var sql in sqlarr)
                        {
                            result += con.Execute(sql, null, transaction);
                        }
 
                        transaction.Commit();
                        return result;
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        return 0;
                    }
                }
            }
        }
 
        /// <summary>
                 /// Transaction 2-declare parameters
        ///demo:
        ///dic.Add("Insert into Users values (@UserName, @Email, @Address)",
                 /// new {UserName = "jack", Email = "380234234@qq.com", Address = "Shanghai" });
        /// </summary>
                 /// <param name="Key">Multiple SQL</param>
        /// <param name="Value">param</param>
        /// <returns></returns>
        public static int ExecuteTransaction(Dictionary<string, object> dic)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (var transaction = con.BeginTransaction())
                {
                    try
                    {
                        int result = 0;
                        foreach (var sql in dic)
                        {
                            result += con.Execute(sql.Key, sql.Value, transaction);
                        }
 
                        transaction.Commit();
                        return result;
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        return 0;
                    }
                }
            }
        }
    }
}

 

Call method

copy code
//No parameters
var list = DapperHelper<T_User>.Query("select * from T_User ").ToList();
//Check with parameters
var list = DapperHelper<T_User>.Query("select * from T_User where uid=@uid", new { uid = 1, }).ToList();
//increase
int ins = DapperHelper<T_User>.Execute("insert into T_User (uid,username) value(@uid,@username)", new { uid = 1, username = "Zhang San" });
//change
int upd = DapperHelper<T_User>.Execute("update T_User set username=@username where uid=@uid", new { username = "Li Si", uid = 1});
//delete
int del = DapperHelper<T_User>.Execute("delete from T_User where uid=@uid", new { uid = 1 });
copy code

 

참조 : https://programmerall.com/article/7102414933/


MSSQL - Cursor vs Temp Table

#테이블 변수사용의 예 use pubs go declare @tmptable table (     nid int identity(1,1) not null,     title varchar (80) not null ) -- 테이블 변수 선언 inse...