Common C#/C# BEST TIP2009. 10. 6. 10:06

뭐 간단한 -_- 거지만 몇번 포트인지 모르는 분들이 제법 계셔서 함 올려봅니다.
 ITS 의 경우 13번 포트가 사용 됩니다.
 표준 시간을 얻어서 적용해야되는 경우 아래와 같이 타임 서버에서 값을 얻어서 쓸 수 있습죠. 

 

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Net.Sockets;

 

namespace NTP_CLIENT

{

    class Program

    {

        static void Main(string[] args)

        {

            TcpClient tsc = new TcpClient("time-a.nist.gov", 13);

 

            if (tsc.Connected)

            {

                    NetworkStream ns = tsc.GetStream();

                    StreamReader sr = new StreamReader(ns);

                    string sResult = sr.ReadToEnd().Trim();

 

                    Console.WriteLine(sResult); //서버에서 받은 결과

 

                    //공백으로 결과값을 나눠서 배열에 넣음.

                    string[] saResult = sResult.Split(' ');

 

                    foreach (string s in saResult)

                    {

                        Console.WriteLine(s);

                    }

            }

            else

            {

                Console.WriteLine("-_-; 연결 안됨");

            }

        }

    }

}



 결과

 

 일단 ITS 의 경우 시간/날짜는  tcp 13 번 포트를 이용해서 접속이 가능합니다.
NTP 기반일 경우 UDP 123 이나 텔넷 37 번이구요. 
위의 형태로 받은 결과물을 소스처럼 공백으로 잘라내면 원하는 항목을 얻을 수 있습니다.
변수에 저장해서 클라이언트 쪽 시간/날짜 값 변경에 사용하시면 되겠죠.

 즐프하세요.

 ITS 리스트 : http://tf.nist.gov/tf-cgi/servers.cgi

Posted by penguindori
Common C#/C# BEST TIP2009. 6. 20. 19:24

1. DateTime.DaysInMonth(int Year , int Month)

2.
string DateString = "2007-12-26 11:29:34.537";
        DateTime nt = DateTime.Parse(DateString.Substring(0,7) + "-01");
        nt = nt.AddMonths(1).AddDays(-1);         
        this.Text = nt.ToString("yyyy-MM-dd");

Posted by penguindori
Common C#/C# BEST TIP2009. 5. 20. 15:20

frm.ShowDialog를 하시기 전에
frm.FormClosing  이나 frm.FormClosed 이벤트 핸들러를 등록하시면
폼이 닫히는것을 감지하여 핸들러 메소드가 실행되게 됩니다.
이런식이 되겠네요

public Form1()

{

    InitializeComponent();

 

    Form2 frm = new Form2();

    frm.FormClosing += new FormClosingEventHandler(frm_FormClosing);

    frm.ShowDialog();

}

 

void frm_FormClosing(object sender, FormClosingEventArgs e)

{

    // 실행할 메소드 호출

    Temp();

}

 

void Temp()

{

    MessageBox.Show(" 닫혔음");

}


Posted by penguindori
Common C#/C# BEST TIP2009. 5. 19. 15:44

1. 해당 달의 첫날을 DateTime형 변수에 넣고. Date.AddMonths(1) 한후 Date.AddDay(-1) 하면 되요

2. msdn보니 방법이 있네여 System.DateTime.DaysInMonth(년도,월); 답변감사 드립니다.

3. 날짜 계산 하기
1)

TimeSpan timeSpan = Convert.ToDateTime(retDay) - Convert.ToDateTime(toDay);
=> 12.00:00:00
2)
DateTime d1 = DateTime.Today;  //오늘날자
DateTime d2 = DateTime.Today.AddDays(8);  //8일을 더한다
TimeSpan sp = d2.Subtract(d1); //두날자를 뺀다
label1.Text = sp.TotalDays.ToString(); //타입스팬을 날자로 변겨한다
3)
DateTime d1 = DateTime.Today;  //오늘날자
DateTime d2 = DateTime.Today.AddDays(8);  //8일을 더한다
TimeSpan sp = d2.Subtract(d1); //두날자를 뺀다

label1.Text = sp.TotalDays.ToString(); //타입스팬을 날자로 변겨한다
=> 이렇게 했을 때는 소수점까지 나올수 있습니다. 시간차이를 날짜수로 바꿔서 표현하기 때문입니다.

시간이하의 값을 무시할 경우에는
sp.Days.ToStirng() 처리하면 됩니다.
만약 2.11:20:30 라면
TotalDays를 사용할 경우 2.**** 식으로 표현되고. (double형)
Days를 쓰면 2가 되는 것이죠.(int형)

Posted by penguindori
Common C#/C# BEST TIP2009. 5. 15. 15:24
Assembly assembly = Assembly.GetExecutingAssembly();
Version ver = assembly.GetName().Version; <-버전 클래스

------ 꼽사리 ------ powerPoint
using System;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;

namespace ExtractImage
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: {0} powerpoint.ppt", System.Windows.Forms.Application.ExecutablePath);
                return;
            }

            string fileName = args[0];
            FileInfo info = new FileInfo(fileName);
            ExtractImage(info.FullName);
        }

        static void ExtractImage(string fileName)
        {
            ApplicationClass app = new ApplicationClass();
            Presentation ppt =
               app.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);

            Regex re = new Regex(@".ppt$", RegexOptions.IgnoreCase);
            string imgFile = re.Replace(fileName, "");

            for (int i = 0; i < ppt.Slides.Count; ++i)
            {
                ppt.Slides[i + 1].Export(imgFile + i + ".png", "PNG", 960, 720);
            }

            ppt.Close();
            app.Quit();
        }
    }
}
Posted by penguindori
Common C#/C# BEST TIP2009. 4. 30. 13:59
 사연 : C# 으로 Mail 발송 부분을 구현 하고 ->
         해당 C#의 DLL을 파워빌더에서 사용 하기 위한 작업 이다.

1. C# DLL을 C++에서 사용 해보자. (ㅡ,.ㅡ 허접한 메일 보내기 라이브러리)

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.Mail;

namespace SMTPClient
{
    [Guid("11116a57-63a0-4694-aab3-11111e4152f9")]
    public interface InetSmtp
    {
        int prints(string str);
        void smtpServer(string host, int port);
        void address(string from, string to);
        string Subject { get;set;}
        string Body { get;set;}
        void FileAppend(string file);
        void smtpSend();
    }
    [Guid("13316a57-63c0-9694-ccb3-14441e4152f9")]
    public class NetSmtpLibrary : InetSmtp
    {
        public int prints(string str)
        {
            System.Windows.Forms.MessageBox.Show(str);
            return 33;
        }
        #region Field
        SmtpClient smtp;
        MailMessage msg;
        #endregion

        #region Server 설정                      #1
        public void smtpServer(string host, int port)
        {
            smtp = new SmtpClient(host, port);
            System.Windows.Forms.MessageBox.Show(smtp.Port.ToString());
        }
        #endregion

        #region mail 발송주소, 받는주소 지정     #2
        public void address(string from, string to)
        {
            MailAddress _from = new MailAddress(from);
            MailAddress _to = new MailAddress(to);
            mailDesignate(_from, _to);
        }

        private void mailDesignate(MailAddress from, MailAddress to)
        {
            msg = new MailMessage(from, to);
        }
        #endregion

        #region 제목, 내용을 설정 합니다.        #3
        public string Subject
        {
            get { return msg.Subject; }
            set { msg.Subject = value; }
        }

        public string Body
        {
            get { return msg.Body; }
            set
            {
                msg.Body = value;
                msg.BodyEncoding = Encoding.Default;
            }
        }
        #endregion

        #region 첨부파일                         #4
        public void FileAppend(string file)
        {
            try
            {
                Attachment attach = new Attachment(file);
                msg.Attachments.Add(attach);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.
                    MessageBox.Show("FileAppend() : " + ex.Message.ToString());
            }

        }
        #endregion

        #region mail 보내기 시작                 #5
        public void smtpSend()
        {
            try
            {
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                smtp.Send(msg);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.
                    MessageBox.Show("smtpSend() : " + ex.Message.ToString());
            }
        }
        #endregion

    }
}


해당 내용을 클래스 라이브 러리로 만듭니다. 또한 사용할 Method는 Interface에서 선언을 해주어야 가따가 쓸 수 있습니다.

속성 -> 응용 프로그램 -> 어셈블리정보에서
 
어셈블리를 COM에 노출을 클릭 해야 한다.
Posted by penguindori
Common C#/C# BEST TIP2009. 4. 7. 14:01
using System.Drawing;
using System.Windows.Forms;
Screen.PrimaryScreen.Bounds.Width
Screen.PrimaryScreen.Bounds.Height

윈도우 모바일, 윈도우 윈폼 모두 사용이 가능 합니다.
: 바탕화면의 크기를 확인 할 수 있습니다.
  전체 폼의 크기를 조정 할 때 유용하게 이용이 될 듯 합니다.




Posted by penguindori