RoutingProtocol Test Method

IT/C# 2016. 9. 23. 00:41

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Reflection;
using System.Web;
using System.Web.Routing;

namespace WebApplication1.Tests
{
    [TestClass]
    public class RouteTests
    {
        private HttpContextBase CreateHttpContext(String targetUrl = null, string httpMethod = "GET")
        {
            // Mock request 객체를 생성한다.
            Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();

            mockRequest.Setup(m => m.AppRelativeCurrentExecutionFilePath).Returns(targetUrl);

            mockRequest.Setup(m => m.HttpMethod).Returns(httpMethod);

            // Mock response를 생성한다.
            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();
            mockResponse.Setup(m => m.ApplyAppPathModifier(It.IsAny<String>())).Returns<string>(s => s);

            // request 개체와 reponse 개체를 사용하는 mock 컨텍스트 개체를 생성한다.

            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
            mockContext.Setup(m => m.Request).Returns(mockRequest.Object);
            mockContext.Setup(m => m.Response).Returns(mockResponse.Object);

            return mockContext.Object;
        }

        private void TestRouteMatch(string url, string controller, string action, object routeProperties = null, string httpMethod = "GET")
        {
            //Arrange
            RouteCollection routes = new RouteCollection();
            RouteConfig.RegisterRoutes(routes);

            // Act - 라우트를 처리한다.
            RouteData result = routes.GetRouteData(CreateHttpContext(url, httpMethod));

            // Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(TestIncomingRouteResult(result, controller, action, routeProperties));
        }

        private bool TestIncomingRouteResult(RouteData routeResult, string controller, string action, object propertySet = null)
        {
            Func<object, object, bool> valCompare = (v1, v2) =>
            {
                return StringComparer.InvariantCultureIgnoreCase.Compare(v1, v2) == 0;
            };

            bool result = valCompare(routeResult.Values["controller"], controller) && valCompare(routeResult.Values["action"], action);

            if(propertySet != null)
            {
                PropertyInfo[] propInfo = propertySet.GetType().GetProperties();
                foreach(PropertyInfo pi in propInfo)
                {
                    if(!(routeResult.Values.ContainsKey(pi.Name)
                        && valCompare(routeResult.Values[pi.Name],
                        pi.GetValue(propertySet, null))))
                    {
                        result = false;
                        break;
                    }
                }
            }

            return result;
        }

        private void TestRouteFail(string url)
        {
            // Arrange
            RouteCollection routes = new RouteCollection();
            RouteConfig.RegisterRoutes(routes);

            // Act
            RouteData result = routes.GetRouteData(CreateHttpContext(url));

            // Assert
            Assert.IsTrue(result == null || result.Route == null);
        }

        [TestMethod]
        public void TestIncomingRoutes()
        {
            // 성공 라우트
            TestRouteMatch("~/Admin/Index", "Admin", "Index");

            TestRouteMatch("~/One/Two", "One", "Two");

            TestRouteMatch("~/Admin", "Admin", "Index");

            TestRouteMatch("~/Admin/Index/Segment", "Admin", "Index");

            TestRouteMatch("~/Admin/Index/1/userid/5", "Admin", "Index", new { search = "userid/5"});
           
            // 실패 라우트
            //TestRouteFail("~/");
        }
    }
}




-----------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;


namespace WebApplication1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            //routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("myRoute", "{controller}/{action}",
                new { action = "Index" }
            );

            routes.MapRoute(null, "{controller}/{action}/{id}/{*search}",
                new { controller = "Admin", action = "Index", id = UrlParameter.Optional });
        }
    }
}


Posted by lI헐헐Il
,
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
int FrameCnt = trace.FrameCount; for(int i =0; i<FrameCnt ; i++) {
Console.WriteLine(trace.GetFrame(i).GetMethod().DeclaringType.FullName + "." + trace.GetFrame(i).GetMethod().Name);
}


C# 소스 내에서 현재 메소스 호출 스택트레이스를 확인하고 싶을 때, System.Diagnostics namespace에 구현된 클래스들로 해당 기능을 구현할 수 있다.
특정한 메소드 호출 시점에 이르기까지의 호출 스택을 확인할 수 있으므로  소스 분석에도 도움이 될 수 있을 것이다.

[MSDN] http://msdn.microsoft.com/ko-kr/library/system.diagnostics.stacktrace(v=vs.110).aspx
Posted by lI헐헐Il
,
NET-Remoting-Events-Explained [www.codeproject.com]

 

닷넷 리모팅에서 서버 - 클라이언트 간에 이벤트를 적용하는 부분을 설명한 페이지. 

Posted by lI헐헐Il
,

LDAP 예제

IT/C# 2014. 3. 13. 17:08

LDAP(Lightweighted Directory Access Protocol)

 

경량 디렉터리 액세스 프로토콜(LDAP)은 TCP/IP 위에서 디렉터리 서비스를 조회하고 수정하는 응용 프로토콜이다.

디렉터리는 논리, 계급 방식 속에서 조직화된, 비슷한 특성을 가진 객체들의 모임이다. 가장 일반적인 예로는 전화 번호부(telephone directory)가 있는데 가나다 순의 일련의 이름을 가지고 있고, 이름마다 전화 번호와 주소가 포함되어 있다. 이러한 기본 설계 때문에 LDAP는 인증을 위한 다른 서비스에 의해 자주 사용된다.

LDAP 디렉터리 트리는 선택된 모델에 따라 다양한 정치적, 지질학적, 조직적 경계를 반영하기도 한다. 오늘날 LDAP의 배치는 최상위 수준의 계급을 구조화하기 위해 도메인 이름 서비스의 이름을 사용하는 경향이 있다. 디렉터리 안에 들어가면 들어갈수록 사람들, 조직, 프린터, 문서, 그룹 등을 대표하는 항목들이 나타난다.

 

 

쉽게 얘기하자면 LDAP은 인증서버 역할을 한다. 관련 예제 링크는 아래를 클릭...

 

http://www.youcanlearnseries.com/Programming%20Tips/CSharp/WhatisLDAP.aspx

Posted by lI헐헐Il
,

Autoupdater

IT/C# 2014. 1. 10. 17:10

Description

Fixing bugs and adding new features is a part of developing software applications. From my experience, sending application updates to users is also a critical part of developing applications, especially when the user has no advanced knowledge of computers. In the Internet era today, the software developer must make application deployment and updating easier and often makes automatic application updates to do this.I already searched through the internet on this topic, but not much seems suited to my needs. So, I tried to create one myself. This sample application is developed in C# as a library with the project name “AutoUpdater”. The DLL “AutoUpdater” can be used in a C# Windows application(WinForm and WPF).

About the features

There are certain features about the AutoUpdater:

1,Easy to implement and use.
2,Application automatic re-run after checking update.
3,Update process transparent to the user .
4,To avoid blocking the main thread using multi-threaded download.
5,Ability to upgrade the system and also the auto update program.
6,A code that doesn't need change when used by different systems and could be compiled in a library.
7,Easy for user to download the update files.

 


Codeplex에서 퍼온 링크이다. Client-side에 실제 배포된 dll, exe 등의 버전 정보를 확인하지는 않는다.
Server와 Client 상에 XML 파일을 두고 이를 통해 Version 정보를 관리한다. 프로그램이 오동작할 경우, Update된 XML 정보와 실제 dll이 어긋날 가능성은 있어보인다.
실제 배포파일에서 버전정보를 확인하는 방법은 없는지 찾아보면 좀 더 나은 Autoupdater가 될 수 있을 것 같다.

 

 

Posted by lI헐헐Il
,

메소드 비동기호출

IT/C# 2013. 9. 6. 17:14
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace AsyncCallbackTest
{
      public delegate String FixByItselfDelegate(String part); 

      class Program
      {
            public static void Main(String[] args)
            {
                  Car myCar  = new Car();
                  FixByItselfDelegate d = new FixByItselfDelegate(myCar.FixByItself);
                  AsyncCallback oCallback = new AsyncCallback(myCar.FixCompleted); 
 
                  d.BeginInvoke("Engine", oCallback, null);
                  Console.WriteLine("Method is called asyncronously in {0}", Thread.CurrentThread.GetHashCode());
                  Thread.Sleep(5000); // Thread will wait for 5 seconds.
                  Console.WriteLine(Thread.CurrentThread.GetHashCode() + " Thread is ended. Press enter,please.");
                  Console.ReadLine();
             }
      }
      
      public class Car
      {
            public String Name;
            public String ProductYear;
            public String FixByItself(String part)
            {
                  Console.WriteLine("Now Fixing {0} in Thread {1}", part, Thread.CurrentThread.GetHashCode());
                  Thread.Sleep(3000); // Thread will wait for 3 seconds.
                  return "Fixing " + part + " is completed";
            }
            
            public void FixCompleted(IAsyncResult ar)
            {
                  AsyncResult AR = (AsyncResult)ar; 
                  FixByItselfDelegate d = (FixByItselfDelegate)AR.AsyncDelegate; // ar을 FixByItselfDelegate로 변환 후 
                     String strResult = d.EndInvoke(ar); // EndInvoke로 return 값을 읽어온다.
                  Console.WriteLine(strResult);
            }
      }
}

 

C#에서 비동기적으로 메소드를 호출하는 방법이다.

리턴값이 필요한 경우에는 델리게이트명.BeginInvoke를 호출할 때 두번째 인수로 AsyncCallback 개체를 넘겨주면 된다. 이 메소드 안에서 IAsyncResult 객체를 비동기적으로 호출한 메소드에 대한 델리게이트로 변환한 후 EndInvoke를 호출하면 Return 값을 얻어올 수 있다.

Posted by lI헐헐Il
,

확장메소드 사용하기

IT/C# 2013. 5. 29. 09:26
using System.Collections.Generic;

public class ShoppingCart {
     public List Products { get; set; }
}

public static class MyExtensionMethods {
     public static decimal TotalPrices(this ShoppingCart cartParam) {
          decimal total = 0;
          foreach(Product prod in cartParam.Products) {
               total += prod.Price;
          }
          return total;
     }
}

decimal cartTotal = cart.TotalPrices();
// DLL을 참조하는 경우에도 해당 클래스에 메소드를 추가한 것처럼 호출할 수 있다.

현재 클래스와 동일한 네임스페이스에 포함되어 있거나, using문으로 지정된 네임스페이스에 존재해야만 한다.
Posted by lI헐헐Il
,
FileStream fs = File.OpenRead(filePath);

MemoryStream ms = new MemoryStream();
ms.SetLength(fs.Length);

fs.Read(ms.GetBuffer(), 0, (int)ms.Length);
fs.Close();
			

fs = File.OpenWrite(filePath + ".bak");
ms.WriteTo(fs);

fs.Close();
ms.Close();
fs = null; ms = null;

Posted by lI헐헐Il
,
<?xml version="1.0" encoding="utf-8" ?>
<Persons>
  <Person name="John Smith">
    <Age>30</Age>
    <Gender>Male</Gender>
  </Person>
  <Person name="Mike Folley">
    <Age>25</Age>
    <Gender>Male</Gender>
  </Person>
  <Person name="Lisa Carter">
    <Age>22</Age>
    <Gender>Female</Gender>
  </Person>
  <Person name="Jerry Frost">
    <Age>27</Age>
    <Gender>Male</Gender>
  </Person>
  <Person name="Adam Wong">
    <Age>35</Age>
    <Gender>Male</Gender>
  </Person>
</Persons>

 XPath Query

Description 

Selects the current node. 

.. 

Selects the parent of the current node. 

Selects all the child of the current node. 

Selects the root nodes. 

// 

Selects nodes from the current node that match the selection expressions no matter where they are. 

 //*

Selects all elements in the document. 

 /element

Selects the root element named element. Staring a path with a / means you are using an absolute path to an element. 

 /element/*

Selects all the child of the root element. 

 element/*

Selects all the child nodes of a child element. 

 element/child

Selects the child elements which are a child of a sprecified child element of the current node. 

 //element

Selects all elements with the specified name regardless of where they are in the document. 

element/child 

Selects the child elements which are a child of a specified child element of the current node. 

 //element

Selects all elements with the specified name regardless if where they are in the document.

 element//child

Selects all child elements of the parent regardless of where they are in the document. 

 @attribute

Selects an attribute of the current node where attribute is the name of the attribute. 

 //@attribute

Selects all the attributes specified by its name regardless of where they are in the document. 

 @*

Selects all attribute of the current node. 

 element[i]

Selects an element with the specified element name and the specified index. 

 text()

Selects the text of all the child nodes of the current element. 

 //text()

Selects text of every element in the document. 

 //element/text()

Selects the text of all the matching elements. 

 //element[name='value']

Selects the text of all the matching elements. 

 //elements[@att='value']

Selects all elements with the specified attribute having the specified value. 

 


FileStream fs = new FileStream("...경로", FileMode.Open, FileAccess.Read);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(fs);
XmlNodeList xNodes = xDoc.SelectNodes("/Persons/Person"); // SelectNodes의 xPath 사용법을 알아둘 것!!

if(xNodes[0] != null) // SelectNodes 후에는 선택해온 값이 있는지 확인부터 할것. 
{                           //  아닌 경우 NullReference 예외가 발생할 수 있음.
          // To do:
         string strTmp = xNodes[0].Attribute["name"].Value;
}

fs.Close(); fs = null;
Posted by lI헐헐Il
,
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Ini
{
    /// 
    /// Create a New INI file to store or load data
    /// 
    public class IniFile
    {
        public string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,
            string key,string val,string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,
                 string key,string def, StringBuilder retVal,
            int size,string filePath);

        /// 
        /// INIFile Constructor.
        /// 
        /// 
        public IniFile(string INIPath)
        {
            path = INIPath;
        }
        /// 
        /// Write Data to the INI File
        /// 
        /// 
        /// Section name
        /// 
        /// Key Name
        /// 
        /// Value Name
        public void IniWriteValue(string Section,string Key,string Value)
        {
            WritePrivateProfileString(Section,Key,Value,this.path);
        }
        
        /// 
        /// Read Data Value From the Ini File
        /// 
        /// 
        /// 
        /// 
        /// 
        public string IniReadValue(string Section,string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section,Key,"",temp, 
                                            255, this.path);
            return temp.ToString();

        }
    }
}

INI 파일에 설정을 저장해두자. kernel32.dll을 Import하니 이리도 간단하다 캬~

[출처]CODEPROJECT : An INI file handling class using C#
Posted by lI헐헐Il
,