잊지 않겠습니다.

  1. Make XmlDocument Instance
  2. CreateXmlDeclaration
  3. Create XmlNode. it is root node
  4. Create another XmlNodes. it is used childNode. these are appended childen to root node

            XmlDocument xmlDocument = new XmlDocument(); -- (1)

            XmlDeclaration xmlDeclation = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null); -- (2)
            xmlDocument.InsertBefore(xmlDeclation, xmlDocument.DocumentElement);

            XmlElement rootNode = xmlDocument.CreateElement("SetTeamEXState Message"); --(3)
            xmlDocument.AppendChild(rootNode);

            XmlElement xmlActionNode = xmlDocument.CreateElement("Action");
            XmlAttribute targetAttribute = xmlDocument.CreateAttribute("Target");
            targetAttribute.Value = ouName;
            xmlActionNode.InnerXml = methodName;
            xmlActionNode.Attributes.Append(targetAttribute);
            rootNode.AppendChild(xmlActionNode);

            XmlElement xmlMessageNode = xmlDocument.CreateElement("Message");
            xmlMessageNode.InnerXml = message;
            rootNode.AppendChild(xmlMessageNode);

            return xmlDocument;

Posted by Y2K
,
class ListViewItemComparer : System.Collections.IComparer
{
    int _col;
    bool _basc;
    
    public ListViewItemComparer()
    {
        _col=0;
        _basc = true;
    }

    public ListViewItemComparer(int column, bool asc)
    {
        _col=column;
        _basc = asc;
    }

    public int Compare(object x, object y)
    {
        if(_basc)
        {
            return String.Compare(((System.Windows.Forms.ListViewItem) x ).SubItems[_col].Text,
                                              ((System.Windows.Forms.ListViewItem)y).SubItems[_col].Text);
        }
        else
        {
            return String.Compare(((System.Windows.Forms.ListViewItem) y ).SubItems[_col].Text,
                                              ((System.Windows.Forms.ListViewItem) x).SubItems[_col].Text);
        }
    }
}
Posted by Y2K
,

32bit com value convert 64bit value

ex:DateTime, long, double.. etc

using reference : COM Data Type

ActiveDs.IADsLargeInteger largeIntADSI = (ActiveDs.IADsLargeInteger) entity.Properties["lastLogonTimestamp"][0];
long timevalue = (long)largeIntADSI.HighPart << 32 | (uint)largeIntADSI.LowPart;
DateTime lastlogontime = DateTime.FromFileTimeUtc(timevalue);
Console.WriteLine(lastlogontime);
Posted by Y2K
,

FTP Client

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

가장 긴 Regular expression을 적고 만듯한 소스... 좀 고칠 방법을 찾아야지 될듯. 

 FTP Client Source

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace SYNCmailDatabaseAPI.FTP
{
    public class FTPClient
    {
        public string Host { get; set; }
        public string RemotePath { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public int Port { get; set; }
        public string FTPStatusDescription { get; private set; }

        public FTPClient()
        {
            Port = 21;
            UserName = "anonymous";
            Password = "anonymous@hostway.co.kr";
        }

        public bool  MakeDirectory(string subDirectory)
        {
            try
            {
                FtpWebRequest ftpRequest = BuildFtpWebRequest(subDirectory);
                ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;

                FtpWebResponse ftpResponse = ( FtpWebResponse )ftpRequest.GetResponse();
                FTPStatusDescription = ftpResponse.StatusDescription;
                ftpResponse.Close();

                return true;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.InnerException);
                return false;
            }
        }

        public bool UploadFile(string remoteFileName, byte[] btDatas)
        {
            FtpWebRequest ftpRequest = BuildFtpWebRequest(remoteFileName);
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            
            try
            {
                FtpWebResponse ftpResponse = (FtpWebResponse) ftpRequest.GetResponse();
                using(Stream st = ftpRequest.GetRequestStream())
                {
                    Console.WriteLine(btDatas.Length);
                    Console.WriteLine(btDatas);
                    st.Write(btDatas, 0, btDatas.Length);
                }
                FTPStatusDescription = ftpResponse.StatusDescription;
                ftpResponse.Close();
            }
            catch(Exception ex)
            {
                Console.WriteLine("Ex : " + ex.Message);
                Console.WriteLine(ex.InnerException);
                return false;
            }
            return true;
        }

        public FTPItem[] GetFileList(string rootDirectory)
        {
            FtpWebRequest ftpRequest = BuildFtpWebRequest(rootDirectory);
            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            FtpWebResponse response = (FtpWebResponse) ftpRequest.GetResponse();
            
            byte[] btDatas = new byte[4086];
            int offset = 0;
            int readCount = 0;
            using(Stream st = response.GetResponseStream())
            {
                while( (readCount = st.Read(btDatas, offset, 20)) > 0 )
                {
                    offset += readCount;    
                }
            }

            string convertedString = Encoding.Default.GetString(btDatas, 0, offset);
            string[] filesInDirectory = convertedString.Split(new char[] {'\n'}, StringSplitOptions.RemoveEmptyEntries);

            List<FTPItem> ftpObjects = new List<FTPItem>();
            foreach(string file in filesInDirectory)
            {
                Console.WriteLine("{0} / {1}", file, file.Length);

                FTPItem ftpObject = new FTPItem(file);
                ftpObjects.Add(ftpObject);
            }
            return ftpObjects.ToArray();
        }

        private FtpWebRequest BuildFtpWebRequest(string subUri)
        {
            string ftpUri = "ftp://" + Host + "/" + subUri;
            Console.WriteLine(ftpUri);
            FtpWebRequest ftpRequest = (FtpWebRequest) FtpWebRequest.Create(ftpUri);
            ftpRequest.Credentials = new NetworkCredential(UserName, Password);
            ftpRequest.UseBinary = true;

            return ftpRequest;
        }
    }
}

 

 FTPItem

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SYNCmailDatabaseAPI.FTP
{
    public class FTPItem
    {
        public string Name { get; private set; }
        public int Size { get; private set; }
        public bool IsDirectory { get; private set; }
        public DateTime LastUpdateDate { get; private set; }

        private static DateTime ConvertDateTime(string ftpMessage)
        {
            int year = int.Parse(ftpMessage.Substring(6, 2));
            int month = int.Parse(ftpMessage.Substring(0, 2));
            int day = int.Parse(ftpMessage.Substring(3, 2));
            
            int hour = int.Parse(ftpMessage.Substring(10, 2));
            int minute = int.Parse(ftpMessage.Substring(13, 2));

            bool isAM = ftpMessage.Contains("AM");
            if(!isAM)
            {
                hour = hour + 12;
            }

            Console.WriteLine("Year : {0}, Month : {1}, Day {2}, Hour : {3}, Minute {4}", year, month, day, hour, minute);

            return new DateTime(year, month, day, hour, minute, 0);
        }

        public FTPItem(string ftpResponseString)
        {
            //04-14-08  02:22PM       <DIR>          App_Data 
            //03-29-08  06:07AM                  112 Global.asax 
            Regex regx = new Regex(@"\A(?<date>[0-9]{2}\-[0-9]{2}\-[0-9]{2}\s\s[0-9]{2}\:[0-9]{2}(AM|PM))\s*((?<filesize>[0-9]+)|(?<dir>\<DIR\>\s*))\s(?<name>(\w|\W)*)\Z");
            
            Match match = regx.Match(ftpResponseString);
            string dateString = match.Groups[ "date" ].Value;
 
            LastUpdateDate = ConvertDateTime(dateString);
            IsDirectory = match.Groups[ "dir" ].Success;
            if ( !IsDirectory )
            {
                Size = int.Parse(match.Groups[ "filesize" ].Value);
            }
            else
            {
                Size = 0;
            }
            Name = match.Groups[ "name" ].Value;
        }
    }
}

Posted by Y2K
,

1. Using Excel COM Object

 private void ExportJoinCountToExcel(Worksheet excelworksheet)
{
    excelworksheet.Name = "가입 및 탈퇴";
    int index = 2;
    excelworksheet.Cells[1, 1] = "날짜";
    excelworksheet.Cells[1, 2] = "가입수";
    excelworksheet.Cells[1, 3] = "탈퇴수";
    foreach (GridViewRow row in gridviewJoinStatics.Rows)
    {
        excelworksheet.Cells[index, 1] = row.Cells[0].Text;
        excelworksheet.Cells[index, 2] = row.Cells[1].Text;
        excelworksheet.Cells[index, 3] = row.Cells[2].Text;
        index++;
    }
}

private void ExportPathToExcel(Worksheet excelworksheet, SyncmailPathType pathtype)
{
    GridView gridview = null;

    if(pathtype == SyncmailPathType.Join)
    {
        gridview = gridviewJoinPath;
        excelworksheet.Name = "가입 경로";
    }
    else
    {
        gridview = gridviewLeavePath;
        excelworksheet.Name = "탈퇴 경로";
    }

    excelworksheet.Cells[1, 1] = "날짜";
    List<PathCase> joinpathes = SyncmailDatabase.PathCases.GetByCase(pathtype);
    int index = 2;
    foreach (PathCase pathcase in joinpathes)
    {
        excelworksheet.Cells[1, index] = pathcase.Description;
        index++;
    }

    int rowindex = 2;
    foreach (GridViewRow row in gridview.Rows)
    {
        int columnindex = 2;
        excelworksheet.Cells[rowindex, 1] = row.Cells[0].Text;
        foreach (PathCase pathcase in joinpathes)
        {
            excelworksheet.Cells[rowindex, columnindex] = row.Cells[columnindex - 1].Text;
            columnindex++;
        }
        rowindex++;
    }
} 


2. Using Response.Output in ASP.NET

private void ExportToExcel(string strFileName, GridView dg)
{
    string attachment = string.Format("attachment; filename={0}", strFileName);
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    dg.RenderControl(htw);

    string s = sw.ToString();

    Response.Write(s);
    Response.End();
}
Posted by Y2K
,

object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);

Assembly.GetExecutingAssembly().GetName().Version.ToString();
Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);

  

  • Assembly의 각각의 정보들을 얻어오고,  그 정보들을 Display 시켜주는 함수들
  • 자신의 Assembly를 얻어오는 방법에 대해서 염두해둘것!
Posted by Y2K
,

1. Preview 3/4의 uninstall.

: global에 등록되어있는 System.Web.Routing, System.Web.Mvc, System.Web.Abstractions에 대한 완벽한 uninstall이 필요하다.

: 프로그램 추가/삭제에서의 제거 뿐 아닌, Registery에서  HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Assemblies\Global에서의 완벽 제거가 필요

  

2. Namespace의 이전

: Html.ActionLink<Controller>의 Namespace가 System.Web.Mvc에서 Microsoft.Web.Mvc로 이전

  

3. RenderUserControl의 제거

RenderPartial로 함수 이름 변경

: 전에는 string을 이용한 Html의 표현 방식이였으나, 이제는 함수 형태로 변경

  

4. web.config 수정

: 버젼 정보 0.0.0.0을 모두 3.5.0.0으로 변경 

Posted by Y2K
,

HTTP에서의 File upload

: form에서의 post 방식을 통한 File을 업로드시키게 된다.

   <form action="/home/uploadfiles" method="post" enctype="multipart/form-data">  
        <label for="file">Filename:</label>  
        <input type="file" name="file" id="file" />  
           <input type="submit" name="submit" value="Submit" />  
   </form>  

 

POST를 통해서 HTTP Header에 같이 넣어지는 데이터는 다음과 같다.

 

POST /home/uploadfiles HTTP/1.1
Content-Type: multipart/form-data; boundary=---------------------------7d81b516112482
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64)
Content-Length: 324

-----------------------------7d81b516112482
Content-Disposition: form-data; name="file"; filename="\\SERVER\Users\Scott\Documents\test.txt"
Content-Type: text/plain

foo
-----------------------------7d81b516112482
Content-Disposition: form-data; name="submit"

Submit
-----------------------------7d81b516112482--

 

POST를 통해서 이동되는 데이터에서는 하나 이상의 파일이 multipart/form-data를 통해서 얻어지는 것이 가능하게 된다. 또한 POST를 통해서 Header에 각각의 binary data가 저장되게 된다.

multipart/form-data를 통하지 않은 데이터는 다음과 같이 보여지게 된다.

POST /home/uploadfiles HTTP/1.1
Content-Type: application/x-www-form-urlencoded
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64)
Content-Length: 13

submit=Submit

 

차이가 확연히 보이는 것을 알수 있다. File의 업로드 시에 필요한 File의 데이터에 대한 정보는 존재하지 않고 있다.ASP.NET에서의 FileUpload control의 경우에도 역시 form에서의 multipart/form-data를 통해서 데이터를 전송시키고 있다.

 

이때에 Http-Header의 정보에 있는 데이터를 얻어오는 방법은 다음과 같다.

                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;  
                if (hpf.ContentLength == 0)  
                    continue;  

                string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName));  
                hpf.SaveAs(savedFileName);

 

요청되어진 Request에서 Files property는 multipart/form-data에서 얻어진 파일 이름과 그에 따른 File 값들로 구성되어진다. HttpPostedFileBase로 데이터를 받아서 서버단이나 원하는 위치에 지정하게 되면 저장되게 된다.

 

이러한 방법은 ASP.NET 또는 MVC 모델에서 뿐 아니라, HTTP단에서 Post를 이용한 데이터의 전송시에 항시 사용되는 방법이 된다.


Posted by Y2K
,

오늘 회사에서 대성씨의 REST에 대한 소개와 REST URI에 대한 내용을 들으면서 전부터 posting 할려고 했던 내용을 Posting 해보자 싶었다. 

  

일단, ASP.NET MVC Framework와 동일하게 진행되었던 ASP .NET의 프로젝트중 하나가 ASP.NET에서의 RESTFUL 이용 방법이였고, 이러한 방법자체가 ASP .NET MVC Framework에 같이 통합이 되어있는 상태이다.

  

기본적으로 Route에 추가하는 RouteHandler에서 회사에서 사용되는 uri.py의 기능과 동일한 기능을 사용하게 된다.

예를 들어.. User/Details/456 이라는 sub-uri를 보게 되면, User-Detail-ID 의 형태를 가지고, User의 Detail한 상태를 알아 볼 수 있는 URI에서의 정보를 제공할 수 있게 된다.

  

MVC에서 RouteHandler가 움직이는 원리는 다음에 포스팅 하기로 하고... 일단은 ASP .NET에서 권장하는 기본적인 Controller의 Action method name, 즉 동작(Action)에 대한 기본 명명법은 다음과 같다.

Action

Sample URL

Description

Details

/Product/Details/5

Displays a single resource such as a database record. For example, displays a single Product with an Id of 5.

Index

/Product/Index

Displays a collection of resources. For example, displays all of the products in the products database table.

Create

/Product/Create

Displays a form for creating a new resource. For example, displays a form for creating a new product.

Insert

/Product/Insert

Inserts a new resource into the database. Typically, you redirect to another action after performing an Insert.

Edit

/Product/Edit/5

Displays a form for editing an existing resource. For example, displays a form for editing a product with an Id of 5.

Update

/Product/Update/5

Updates existing resources in the database. Typically, you redirect to another action after performing an Update.

Destroy

/Product/Destroy/5

Displays a page that confirms whether or not you want to delete a resource from the database.

Delete

/Product/Delete/5

Deletes a resource from the database. Typically, you redirect to another action after performing a Delete.

Login

/Home/Login

Displays a login form.

Logout

/Home/Logout

Logs out a user. Typically, you redirect to another action after performing a Logout.

Authenticate

/Home/Authenticate

Authenticates a user name and password. Typically, you redirect to another action after performing an Authenticate.

  

 여기에서 주목할 점이, Update와 Delete, Destroy이다. REST에서 권장하는 HttpMethod인 PUT과 DELETE를 사용하지 않는 이유는 기본적인 ASP.NET MVC Framework에서는 PUT과 DELETE를 사용하고 있지 않기 때문이다. 기본적인 설정에서 사용하고 있지 않는 설정을 권장사항에 넣기 힘들어서 아무래도 Update와 Delete가 따로 Action으로 분류를 시키고 있는 것 같다. 

  

기본적인 MapRoute 방법자체는 다음과 같다.

             routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

 각각의 Route의 이름과 Controller, Action, 그리고 필요하다면 그에 따른 parameter의 이름을 이용한 MapRoute를 작성시키고 있다. 여기에서 {controller}의 이름은 RegularExpression을 지원하기 때문에, 기본적인 REST 서버들과 거의 유사하게 움직인다. (정확히는 모른다. --)

Posted by Y2K
,

ASP .NET MVC Framework에서는 URL에 대한 각각의 Controller를 기본적으로 다음과 같이 사용하고 있다.

 

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

 

여기에서, 각각의 Route는 기본적으로 Controller/Action/Parameters 형태로서 구성이 되지만, 다음과 같이 다른 형태의 Route역시 가능하다.

 

http://localhost/Product/Create/id          
  routes.MapRoute(
                "Product",                                              // Route name
                "Product/{action}/{id}",                           // URL with parameters
                new { controller = "ProductManager", action = "List", id = "" }  // Parameter defaults
            );


http://localhost/Product/id/Edit

routes.MapRoute(   
                 "ProductEdit",        // Route name  
                 "Product/{id}/Edit",  // URL with parameters     
                 new { controller = "ProductManager", action = "Edit", id = "" }  // Parameter defaults 
           );

 

Caution!!!

Route를 여러개 지정하는 경우에는 차례대로 먼저 알아보게 된다. 기본적인 Controller를 가장 최 상단으로 올리는 경우에 그 뒤에 나오는 모든 sub-url을 기본적으로 controller로 해석하려고 하기 때문에 무조건 에러가 발생하게 된다.

사용자 지정 URL을 넣어주는 경우에는 먼저, 사용자 URL을 먼저 넣어주고 그 후에 기본적으로 사용하는 Default Route를 넣어주는 것이 하나의 방법이 된다.

Posted by Y2K
,