시스템을 구현할때 프로그램에 현재시간을 표기해야 하는 경우가 발생하는데
이를 로컬PC시간이 아닌 서버시간을 표현할라치면 매법 타이머 돌때마다 서버시간 쿼리를 불러 처리하려다보면
당근 부하가 차리라는 생각이 든다.
이전 프로젝트 할때 사용했던 방법으로 최초 DB시간을 불러와 현재의 로컬PC시간과의 차이를 구해 처리하는 방법으로 나타냈다.
중간 중간 시간이 맞는지 1시간 마다 또는 필요할 때 마다 동기화 처리를 다시해서 표현하는 방법을 쓰면 유용하리라 본다.
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace _CS__DB시간매칭
{
    public partial class Form1 : Form
    {
        private TimeSpan span;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // DB의 현재시간을 구해오는 쿼리
            DataTable dt = ServiceAgent.Request("SYS", "DF_CERTUSER", "1", "2", "3").Tables[0];   // 이건 각자 해보시길...^^

            if (dt.Rows.Count > 0)
            {
                DateTime sysDate = Convert.ToDateTime(dt.Rows[0][0].ToString());
                DateTime now = DateTime.Now;
                this.span = sysDate.Subtract(now);
            }
        }

        public DateTime GetSysDateTime
        {
            get
            {
                return DateTime.Now.Add(this.span);
            }
        }

        //서버일자와 현재일자에서 오차를 더하면 결국 서버일자이므로 서버일자 반환
        public string GetSysDate
        {
            get
            {
                return DateTime.Now.Add(this.span).ToString("yyyy-MM-dd");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = GetSysDateTime.ToString();
        }
    }
}


WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,

오늘 문득 파일 다운로드를 어떻게 할지 고민해봤다.
뭐 간단히 네이X 한테서 그 해답을 찾았다.
모르는게 없다... 눼이X...


using System.Net;

            WebClient WClient = new WebClient();
            WClient.DownloadFile("http://static.naver.com/www/u/2010/0611/nmms_215646753.gif", "c:\\neyinyuen.gif");


WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,

using System.Net;


            string strHostName = Dns.GetHostName();

            IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
            IPAddress[] addr = ipEntry.AddressList;

            for (int i = 0; i < addr.Length; i++)
            {
                Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
            } 


WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,

// getset.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace _CS__GetSet
{
    class getset
    {
        private string strTitle;

        public string Title
        {
            get
            {
                return strTitle;
            }
            set
            {
                strTitle = value;
            }
        }

    }
}

// Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace _CS__GetSet
{
    public partial class Form1 : Form
    {
        getset gs = new getset();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            gs.Title = "call_getset";

            string str = call_getset();
            MessageBox.Show(str);
        }

        private string call_getset()
        {
            return gs.Title;
        }

    }
}

'020. Prigraming > 01. C#' 카테고리의 다른 글

[C#] 웹상의 파일 다운로드 하기  (0) 2010.07.23
[C#] 사용자 IP 구하기  (0) 2010.06.04
[C#] 암호화 / 복호화 알아보자  (0) 2010.05.12
[C#] Convert.ToByte  (0) 2010.05.11
[C#] .net 3.0 LINQ  (0) 2010.05.03

WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,


using System.Security.Cryptography;
using System.IO;

        private static string EncryptString(string InputText, string Password)
        {

            // Rihndael class를 선언하고, 초기화 합니다
            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            //// 입력받은 문자열을 바이트 배열로 변환
            byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);

            // 딕셔너리 공격을 대비해서 키를 더더 풀기 어렵게 만들기 위해서
            //// Salt를 사용합니다.
            byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());

            // PasswordDeriveBytes 클래스를 사용해서 SecretKey를 얻습니다.
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);

            //// Create a encryptor from the existing SecretKey bytes.
            // encryptor 객체를 SecretKey로부터 만듭니다.
            // Secret Key에는 32바이트
            // (Rijndael의 디폴트인 256bit가 바로 32바이트입니다)를 사용하고,
            // Initialization Vector로 16바이트
            // (역시 디폴트인 128비트가 바로 16바이트입니다)를 사용합니다
            ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

            // 메모리스트림 객체를 선언,초기화
            MemoryStream memoryStream = new MemoryStream();

            // CryptoStream객체를 암호화된 데이터를 쓰기 위한위한 용도로 선언
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);

            // 암호화 프로세스가 진행됩니다.
            cryptoStream.Write(PlainText, 0, PlainText.Length);

            // 암호화 종료
            cryptoStream.FlushFinalBlock();

            // 암호화된 데이터를 바이트 배열로 담습니다.
            byte[] CipherBytes = memoryStream.ToArray();

            //// 스트림 해제
            memoryStream.Close();
            cryptoStream.Close();

            // 암호화된 데이터를 Base64 인코딩된 문자열로 변환합니다.
            string EncryptedData = Convert.ToBase64String(CipherBytes);

            //// 최종 결과를 리턴
            return EncryptedData;

        }

        private static string DecryptString(string InputText, string Password)
        {

            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            byte[] EncryptedData = Convert.FromBase64String(InputText);
            byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());


            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);

            // Decryptor 객체를 만듭니다.
            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

            MemoryStream memoryStream = new MemoryStream(EncryptedData);

            // 데이터 읽기(복호화이므로) 용도로 cryptoStream객체를 선언,선언, 초기화
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

            // 복호화된 데이터를 담을 바이트 배열을 선언합니다.선언합니다.
            // 길이는 알 수 없지만,없지만, 일단 복호화되기 전의 데이터의 길이보다는
            // 길지 않을 것이기 때문에 그 길이로 선언합니다
            byte[] PlainText = new byte[EncryptedData.Length];

            // 복호화 시작
            int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);

            memoryStream.Close(); memoryStream.Close();
            cryptoStream.Close();

            // 복호화된 데이터를데이터를 문자열로 바꿉니다.
            string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);

            // 최종 결과 리턴리턴
            return DecryptedData;

        }


[출처] http://blog.naver.com/yun4604?Redirect=Log&logNo=10075424101
오타는 좀 많더라... 수정은 해놨지만...

'020. Prigraming > 01. C#' 카테고리의 다른 글

[C#] 사용자 IP 구하기  (0) 2010.06.04
[C#] get과 set에 대하여 알아보자  (0) 2010.06.03
[C#] Convert.ToByte  (0) 2010.05.11
[C#] .net 3.0 LINQ  (0) 2010.05.03
[C#] 프로시저 호출 방법  (0) 2010.04.27

WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,


            //##Command 1 byte: 00: Read bit; 01: Read word; 02: Write bit; 03: Write Word
            sendBuffer[0] = Convert.ToByte(0x01);
            //##PC Number 1 byte: &HFF
            sendBuffer[1] = Convert.ToByte(0xFF);

            //##ACPU monitoring timer 2 bytes &H0A00 (10)
            sendBuffer[2] = Convert.ToByte(0x0A);
            sendBuffer[3] = Convert.ToByte(0x00);
...

PLC통신할때 유용하게 사용하자

//////////////////////

 // Make Header
 lpCommand[0] = 0x00;      // bit 단위읽기에 대한 sub header
 lpCommand[1] = (unsigned char)0xFF;   // PLC 번호
 lpCommand[2] = 0x0A;      // MCPU 감시 타이머
 lpCommand[3] = 0x00;
 memcpy( &(lpCommand[4]), &DeviceNum, 2 ); // 선두 디바이스 번호
 lpCommand[6] = 0x00;
 lpCommand[7] = 0x00;
 lpCommand[8] = LowDeviceCode;    // row device code
 lpCommand[9] = HighDeviceCode;    // high device code

 if( ( nBitCount % 2 ) == 1 ) {
  // 홀수 이면
  nBitCount++;
 }
 // 디바이스 점수
 if( nBitCount == 256 ) {
  lpCommand[10] = 0;
 } else {
  lpCommand[10] = nBitCount;
 }
 lpCommand[11] = 0x00;

이것도 참조하자

'020. Prigraming > 01. C#' 카테고리의 다른 글

[C#] get과 set에 대하여 알아보자  (0) 2010.06.03
[C#] 암호화 / 복호화 알아보자  (0) 2010.05.12
[C#] .net 3.0 LINQ  (0) 2010.05.03
[C#] 프로시저 호출 방법  (0) 2010.04.27
[C#] 웹에서 이미지 다운받기  (1) 2010.04.13

WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,


            string[] names = { "Alpha", "Brian", "Connie", "David", "Frank", "George", "Harry", "Inigo" };
           
            IEnumerable expr = from s in names

                               where s.Length == 5

                               orderby s

                               select s.ToUpper();

            foreach (string item in expr)
                MessageBox.Show(item);

뭐 대충 이런 건 가보다... DB에서 읽어와 적적할게 활용하면 괜찮을 듯 해 보입니다.


WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,

1.
/**************************************************************************************************
* Stored Procedure에서 OUTPUT 변수 미선언
* SqlDataReader 객체 사용하여 SELECT 된 데이타 얻어옴.
* SqlCommand.ExecuteScalar 를 활용해도 좋을듯.
**************************************************************************************************/
[WebMethod]
public int UserConfirm(string sabun, string pass)
{
 try
 {
  dbConn = new SqlConnection("server=localhost;uid=sa;pwd=xxxx;database=xxxx");
  dbConn.Open();

  SqlCommand cmd = new SqlCommand();
  cmd.Connection = dbConn;
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.CommandText = "dbo.SP_MEMBER_CONFIRM";    
  
  cmd.Parameters.Add("@sabun", SqlDbType.VarChar, 10);
  cmd.Parameters.Add("@pass", SqlDbType.VarChar, 8);

  cmd.Parameters["@sabun"].Value = sabun;
  cmd.Parameters["@pass"].Value = pass;

  int result_value = 0 ;
  SqlDataReader reader = cmd.ExecuteReader();
  if(reader.Read())
   result_value = reader.GetInt32(0);
  
  reader.Close();
  return result_value;
 }
 catch(Exception e)
 {
  System.Console.WriteLine(e.Message);
  return 4;
 }
 finally
 {
  dbConn.Close();
 }
}

####################################################################################################

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

ALTER  PROC SP_MEMBER_CONFIRM
    @sabun varchar(10),  /* Client 사번 */
    @pass  varchar(8)    /* Client 비밀번호 */
AS 
    BEGIN
 DECLARE @chk_sabun varchar(10)
 DECLARE @chk_pass  varchar(8)
 DECLARE @tot_cnt NUMERIC
 DECLARE @opt int /* return 값 */

 SET @chk_sabun = (SELECT SABUN FROM MEMBER WHERE SABUN = @sabun)
 
 if @chk_sabun is not null /* 사번이 있는경우 */
     BEGIN
  set @chk_pass = (SELECT PASS FROM MEMBER WHERE SABUN = @sabun and PASS = @pass)

  IF @chk_pass is not null /* 계정 일치 */
    BEGIN
   UPDATE MEMBER SET LAST_DATE = REPLACE(CONVERT(VARCHAR(10),GETDATE(),120),'-',''), FAIL_CNT = 0
   WHERE SABUN = @sabun and PASS = @pass
   SET @opt = 1
    END
  ELSE /* 비밀번호 인증오류 */
    BEGIN
   set @tot_cnt = (SELECT FAIL_CNT FROM MEMBER WHERE SABUN = @sabun)
   UPDATE MEMBER SET FAIL_CNT=(@tot_cnt + 1) WHERE SABUN = @sabun
   SET @opt = 3
    END
     END
 ELSE /* 사번이 없는경우 */
  SET @opt = 2

 SELECT @opt AS OPT
    END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


2.
/**************************************************************************************************
* Stored Procedure에서 OUTPUT 변수 선언
* 파라메터에 저장된 값을 얻어옴.
* SP 뿐 아니라 C# 코드에서도 OUTPUT TYPE을 명시해줘야함.
* OUTPUT 변수에 값만 SET해주면 되고 별도로 RETURN 이나 SELECT가 필요없다.
**************************************************************************************************/

[WebMethod]
public int UserConfirm(string sabun, string pass)
{
 try
 {
  dbConn = new SqlConnection("server=localhost;uid=sa;pwd=xxxx;database=xxxx");
  dbConn.Open();

  SqlCommand cmd = new SqlCommand();
  cmd.Connection = dbConn;
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.CommandText = "dbo.SP_MEMBER_CONFIRM";    
  
  cmd.Parameters.Add("@sabun", SqlDbType.VarChar, 10);
  cmd.Parameters.Add("@pass", SqlDbType.VarChar, 8);

  cmd.Parameters["@sabun"].Value = sabun;
  cmd.Parameters["@pass"].Value = pass;

  SqlParameter myParameter = cmd.Parameters.Add("@opt", SqlDbType.Int);
  myParameter.Direction = ParameterDirection.Output;

  cmd.ExecuteNonQuery();

  int result_value = 0 ;
  result_value = Convert.ToInt32(cmd.Parameters["@opt"].Value);
  
  return result_value;
 }
 catch(Exception e)
 {
  System.Console.WriteLine(e.Message);
  return 4;
 }
 finally
 {
  dbConn.Close();
 }
}


####################################################################################################

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

ALTER  PROC SP_MEMBER_CONFIRM
    @sabun varchar(10),  /* Client 사번 */
    @pass  varchar(8),    /* Client 비밀번호 */
    @opt int OUTPUT       /* return 값 */
AS 
    BEGIN
 DECLARE @chk_sabun varchar(10)
 DECLARE @chk_pass  varchar(8)
 DECLARE @tot_cnt NUMERIC

 SET @chk_sabun = (SELECT SABUN FROM MEMBER WHERE SABUN = @sabun)
 
 if @chk_sabun is not null /* 사번이 있는경우 */
     BEGIN
  set @chk_pass = (SELECT PASS FROM MEMBER WHERE SABUN = @sabun and PASS = @pass)

  IF @chk_pass is not null /* 계정 일치 */
    BEGIN
   UPDATE MEMBER SET LAST_DATE = REPLACE(CONVERT(VARCHAR(10),GETDATE(),120),'-',''), FAIL_CNT = 0 WHERE SABUN = @sabun and PASS = @pass
   SET @opt = 1
    END
  ELSE /* 비밀번호 인증오류 */
    BEGIN
   set @tot_cnt = (SELECT FAIL_CNT FROM MEMBER WHERE SABUN = @sabun)
   UPDATE MEMBER SET FAIL_CNT=(@tot_cnt + 1) WHERE SABUN = @sabun
   SET @opt = 3
    END
     END
 ELSE /* 사번이 없는경우 */
  SET @opt = 2
    END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


////////////////////////////
데브피아에서 퍼왔는데 정확히 위치를 모르겠네...


WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,


                try
                {
                    System.Net.WebRequest request =
                        System.Net.WebRequest.Create(
                        "http://www.웹주소.com/logo.jpg");
                    System.Net.WebResponse response = request.GetResponse();
                    System.IO.Stream responseStream =
                        response.GetResponseStream();
                    Bitmap bitmap2 = new Bitmap(responseStream);

                    g.DrawImage(bitmap2, _x, _y, 140, 21);

                }
                catch (System.Net.WebException)
                {
                    Set_Values(g, 9, _x, _y, 140, 21, "NO IMAGE");
                    MessageBox.Show("There was an error opening the image file."
                       + "Check the URL");
                }


WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,

서대리한테 좋은 팁 하나 배웠다.
소스 보면 대충 아래의 버튼이 무슨 기능을 하는지 알 수 있을테다.

        private void btnHidden1_Click(object sender, EventArgs e)
        {
            Panel pnl = new Panel();
            if (((DsButton)sender).Name == "btnHidden1")
            {
                pnl = pnlLOTList;
            }
            else if (((DsButton)sender).Name == "btnHidden2")
            {
                pnl = pnlIssue;
            }

            if (((DsButton)sender).Text == "숨기기")
            {
                pnl.Visible = false;
                ((DsButton)sender).Text = "보이기";
            }
            else
            {
                pnl.Visible = true;
                ((DsButton)sender).Text = "숨기기";
            }
        }


WRITTEN BY
테네시왈츠
항상 겸손하게 항상 새롭게 항상 진실하게

,