잊지 않겠습니다.

Digest Auth

            CredentialCache webservCredentials = new CredentialCache();
            webservCredentials.Add(new Uri("http://123.123.123.123:8888/MobileAccessVersion.asmx"), "Digest", new NetworkCredential("ykyoon", "*****", "***"));
            webService.Credentials = webservCredentials;

Basic Auth

            CredentialCache webservCredentials = new CredentialCache();
            webservCredentials.Add(new Uri("http://123.123.123.123:8888/MobileAccessVersion.asmx"), "Basic", new NetworkCredential("ykyoon", "*****", "***"));
            webService.Credentials = webservCredentials;

 

상당히 편하게 구현이 가능한 방법

일부러 MD5로 압축하거나, Base64로 따로 인코딩을 할 필요도 없이 아주 산뜻하게 끝이 난다. ^^

Posted by Y2K
,

A cookie is stored on the client's machine by their web browser software. To set a cookie, we include information in an HttpResponse that instructs the browser to save a cookie on the client's system. Here's the basic code for writing a Cookie in ASP.NET 

Using System.Web;



Response.Cookies["BackgroundColor"].Value = "Red";




And to read the cookie back : 

Response.Write

(Request.Cookies["BackgroundColor"].Value);




Note that for security reasons you can only read a cookie that was set within the same domain name. 

Sometimes you may need a collection of stored items, such as user address details. In this case you could read in a cookie collection like this: 

HttpCookieCollection cookies = Request.Cookies;

for(int n=0;n<cookies.Count;n++)

{

    HttpCookie cookie = cookies[n];

    Response.Write("<hr/>Name: <b>" + cookie.Name + "</b><br />");

    Response.Write("Expiry: " + cookie.Expires + "<br />");

    Response.Write("Address1: " + cookie.Address1+ "<br />");

    Response.Write("Address2: " + cookie.Address2+ "<br />");

    Response.Write("City: " + cookie.City+ "<br />");

    Response.Write("Zip: " + cookie.Zip+ "<br />");

}


Posted by Y2K
,

this is ThreadAbort Exception in Response.Redirect because of Response.End() is not completed.

 

if use Response.Redirect in try..catch block, this exception is frequent.

and this exception(System.Threading.Thread.AbortThread) is especially exception. if you catch the exception in try.. catch block, this exception is re-thrown by .NET Framework. so application programmer cannot resolve this problem.

 

So, remove System.Threading.Thread.Abort is good reason for this case.

In Response.Redirect have 2 overloaded functions.

1. Response.Redirect(string url)

2. Response.Redirect(string url, bool endResponse)

 

Response.Redirect(string url) is equal with Response.Redirect(string url, true).

if endResponse is false, Response.End() event is not occured.

Posted by Y2K
,

Seven Segment

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

using System;
using System.Drawing;

namespace Chapter10_App
{
 /// <summary>
 /// SevenSegmentDisplay에 대한 요약 설명입니다.
 /// </summary>
 public class SevenSegmentDisplay
 {
  Graphics _grfx;
  static byte[,] bySegment = { {1, 1, 1, 0, 1, 1, 1},  //0
         {0, 0, 1, 0, 0, 1, 0},  //1
         {1, 0, 1, 1, 1, 0, 1},  //2
         {1, 0, 1, 1, 0, 1, 1},  //3
         {0, 1, 1, 1, 0, 1, 0},  //4
         {1, 1, 0, 1, 0, 1, 1},  //5
         {1, 1, 0, 1, 1, 1, 1},  //6
         {1, 0, 1, 0, 0, 1, 0},  //7
         {1, 1, 1, 1, 1, 1, 1},  //8
         {1, 1, 1, 1, 0, 1, 1} }; //9
  readonly Point[][] _apt = new Point[7][];
     

  public SevenSegmentDisplay(Graphics grfx)
  {
   _grfx = grfx;
   
   _apt[0] = new Point[]{new Point(3, 2), new Point(39, 2),
          new Point(31, 10), new Point(11, 10)};
   _apt[1] = new Point[]{new Point(2, 3), new Point(10, 11),
          new Point(10, 31), new Point(2, 35)};
   _apt[2] = new Point[]{new Point(40, 3), new Point(40, 35),
          new Point(32, 31), new Point(32, 11)};
   _apt[3] = new Point[]{new Point(3, 36), new Point(11, 32),
          new Point(31, 32), new Point(39, 36),
          new Point(31, 40), new Point(11, 40)};
   _apt[4] = new Point[]{new Point(2, 37), new Point(10, 41),
          new Point(10, 61), new Point(2, 69)};
   _apt[5] = new Point[]{new Point(40, 37), new Point(40, 69),
          new Point(32, 61), new Point(32, 41)};
   _apt[6] = new Point[]{new Point(11, 62), new Point(31, 62),
          new Point(39, 70), new Point(3, 70)};

  }

  public SizeF MeasureString(string str, Font font)
  {
   SizeF sizef = new SizeF(0, _grfx.DpiX * font.SizeInPoints / 72);

   for(int i = 0 ; i < str.Length ; i++)
   {
    if( (Char.IsDigit(str[i])) || (str[i] == '=>') )
    {
     sizef.Width += 42 * _grfx.DpiX * font.SizeInPoints / 72 / 72;
    }
   }

   return sizef;
  }
  
  void Fill(Point[] apt, Font font, Brush brush, float x, float y)
  {
   PointF[] aptf = new PointF[apt.Length];

   for(int i = 0 ; i < apt.Length ; i++)
   {
    aptf[i].X = x + apt[i].X * _grfx.DpiX * font.SizeInPoints / 72 / 72;
    aptf[i].Y = y + apt[i].Y * _grfx.DpiY * font.SizeInPoints / 72 / 72;
   }
   _grfx.FillPolygon(brush, aptf);
  }

  float Number(int num, Font font, Brush brush, float x, float y)
  {
   for(int i = 0 ; i < _apt.Length ; i++)
   {
    if(bySegment[num, i] == 1)
    {
     Fill(_apt[i], font, brush, x, y);
    }
   }

   return x + 42 * _grfx.DpiX * font.SizeInPoints / 72 / 72;
  }

  float Colon(Font font, Brush brush, float x, float y)
  {
   Point[][] apt = new Point[2][];

   apt[0] = new Point[]{ new Point(2, 21), new Point(6, 17),
         new Point(10, 21), new Point(6, 25)};
   apt[1] = new Point[]{ new Point(2, 51), new Point(6, 47),
         new Point(10, 51), new Point(6, 55)};

   for(int i = 0 ; i < apt.Length ; i++)
   {
    Fill(apt[i], font, brush, x, y);
   }

   return x + 12 * _grfx.DpiX * font.SizeInPoints / 72  / 72;
  }

  public void DrawString(string str, Font font, Brush brush, float x, float y)
  {
   for(int i = 0 ; i < str.Length ; i++)
   {
    if(Char.IsDigit(str[i]))
    {
     x = Number(str[i] - '0', font, brush, x, y);
    }
    else if(str[i] == '=>')
    {
     x = Colon(font, brush, x, y);
    }
   }
  }
 }
}

Posted by Y2K
,
  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
,