잊지 않겠습니다.

Microsoft.ajax

.NET Framework 2009. 1. 7. 13:01

MS에서 ASP.NET에서 사용하기 쉽도록 만든 java script library. 

    

1. call local web service 

Sys.Net.WebServiceProxy.invoke("Service Address", "method name", "IsPost Action", "Parameters", "return action")

  1. function check_activateion_requested(user_id) {  
  2.     Sys.Net.WebServiceProxy.invoke(          
  3. "/SYNCmailUtil.asmx",        "IsActivationRequired",        false,        { userId: user_id },        inputbox_enable        )}    function inputbox_enable(enable) {    if (enable) {        document.getElementsByName('logonName')[0].readOnly = "false";        document.getElementsByName('password')[0].readOnly = "false";    }    else {        document.getElementsByName('logonName')[0].readOnly = "true";        document.getElementsByName('password')[0].readOnly = "true";        document.getElementsByName('logonName')[0].value = "";        document.getElementsByName('password')[0].value = "";        document.getElementById('infoLabel').innerHTML = "Activation을 할 수 없는 유저입니다.";    }}  

    

    

Posted by Y2K
,

JSON 형태의 데이터를 C# 형태로의 변환

  

java script에서나 Netscape 진형에서 주로 사용되는 JSON 데이터 형태를 C# class로 변환 및 이를 이용한 AJAX 개발이 가능하다.  

  

먼저, C# class의 선언

  1. public class Company  
  2.     {  
  3.         public string Name { getset; }  
  4.         public string Location { getset; }  
  5.         public string Subject { getset; }  
  6.     }  

  

여기서 간단히 3개의 Input box를 갖는 View Page의 생성

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="CompanyView.aspx.cs" Inherits="MvcJson.Views.Home.CompanyView" %>  
  2. <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">  
  3. Company Name : <%=Html.TextBox("CompanyName") %> <br />  
  4. Company Subject : <%=Html.TextBox("Subject") %> <br />  
  5. Company Location : <%=Html.TextBox("Location") %> <br />  
  6. <input type="button" id="sendCompanyData" value="Send Company Data" /><br />  
  7. <div id="resultArea"></div>  
  8. </asp:Content>  


HttpContext를 이용해서 json data를 HTTP-POST로 전달하는 javascript

(jQuery 이용.) 

  1. <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.2.6.js") %>"></script>  
  2. <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.toJSON.js") %>"></script>  
  3. <script type="text/javascript">  
  4.   $(function() {  
  5.     //sending json object to controller action:  
  6.     $("#sendCompanyData").click(function() {  
  7.       var company = {  
  8.         "Name": $("#CompanyName").val(),  
  9.         "Subject": $("#Subject").val(),  
  10.         "Location": $("#Location").val()  
  11.       };  
  12.   
  13.       var encoded = $.toJSON(company);  
  14.   
  15.       $.ajax({  
  16.         url: "/Home/ShowCompany",  
  17.         type: "POST",  
  18.         dataType: 'json',  
  19.         data: encoded,  
  20.         contentType: "application/json; charset=utf-8",  
  21.         beforeSend: function() { $("#saveStatus").html("Saving").show(); },  
  22.         success: function(result) {  
  23.           alert(result.Result);  
  24.           $("#saveStatus").html(result.Result).show();  
  25.         }  
  26.       });  
  27.     });  
  28.   });   
  29. </script>  

  

데이터를 받을 Controller 작성

  1. public ActionResult ShowCompany()  
  2.         {  
  3.             if(HttpContext.Request.ContentType.Contains("application/json"))  
  4.             {  
  5.                 string inputContent;  
  6.                 int dataLength = (int) HttpContext.Request.InputStream.Length;  
  7.                 byte[] btDatas = new byte[dataLength];  
  8.                 HttpContext.Request.InputStream.Read(btDatas, 0, dataLength);  
  9.   
  10.                 inputContent = System.Text.Encoding.UTF8.GetString(btDatas);  
  11.   
  12.                 var result = (Company) JavaScriptConvert.DeserializeObject(inputContent, typeof(Company));  
  13.   
  14.                 return Json(new { Result = string.Format("{0} : {1} : {2}", result.Name, result.Subject, result.Location) });  
  15.             }  
  16.             else  
  17.             {  
  18.                 return Json(new { Result = "This data is not json" });  
  19.             }  
  20.         }  

  

결론 : JSON -> C# class 변환은 매우 자유로운 편이다. 예시의 JSON이 있다면 C# class를 자동으로 작성해주는 간단한 script만 있으면 둘이 같이 사용하기가 매우 편할것 같다.

Posted by Y2K
,

web에서 인증을 도와주고, 인증을 이용한 ActionFilter를 제공한다. 

  

1. web.config의 설정

   <authentication mode="Forms">
      <forms loginUrl="~/NotLogOn" />
    </authentication>

authentication mode는 반드시 Forms로 해주고, authorize가 되어있지 않는 경우에 돌아갈 url을 설정한다.

  

2. Login 정보 입력

FormsAuthentication 을 이용해서 user정보를 저장하는 cookie 값을 이용한다.  

   public interface IFormsAuthentication
    {
        void SetAuthCookie(string userName, bool createPersistentCookie);
        void SignOut();
    }
    public class FormsAuthenticationWrapper : IFormsAuthentication
    {
        public void SetAuthCookie(string userName, bool createPersistentCookie)
        {
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }
        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    } 

  

3. Login 정보 입력 부분 구현

       public ActionResult Logon(string userName, string password, string saveCookie)
        {
            if(Request.HttpMethod != "POST")
            {
                return Redirect("/Logon/Index");
            }
            HostwayMembership membership = new HostwayMembership();
            if( membership.ValidateUser(userName, password) )
            {
                FormsAuth.SetAuthCookie(userName, saveCookie == "on");
                csDB.CreateCSEvent(userName, com.hostway.lib.SYNCmail.Database.CSEventCase.CSUserLogin, userName,
                                   "Logon", "Logon user");
                csDB.OnSubmit();
                return Redirect("/Home/Index");
            }
            else
            {
                return Redirect("/Logon/Index");
            }
        }

  

4. 인증이 필요한 controller, 또는 action에 attribute 적용

   [Authorize(Order=0)][AuthActionFilter(Order=1)]
    public class UserController : SYNCmailController
    [Authorize]
    public ActionResult List(int? pageNumber, int? eventPageNumber)

  

controller에 적용되는 경우에는 모든 action에 일괄적으로 적용되게 된다. 

이때에, Order 순서를 정해서 적용될 ActionFilter의 순서를 결정할 수 있다.

  

또한, 아래와 같이 user 또는 , Role에 대해서도 역시 같은 적용이 가능하다.

[Authorize(Users="email@address.co.kr")] 
[Authorize(Roles="admin, friend")]

  

  

  

  

  

Posted by Y2K
,