728x90
300x250

[C#.NET] A 폼 닫고 B 폼 열기

Visual Basic 6을 사용해보신 분은 'hide'와 'show'만 가지고 자유자재로 컨트롤을 쉽게 제어할 수 있었습니다.
더불어 Application의 닫기 이벤트 또한 내부함수로 구성되어 있어서 사용하기에 편리했습니다.
C#은 문제를 도출하기 위해 다소 다른 방법을 사용합니다.
이 예제는 그러한 상황을 해결하기 위해 만들어졌습니다.


1. 인터페이스 설계

'Sample'이라는 제목을 가지고 있는 A 폼 입니다.
'Main'이라는 제목을 가지고 있는 B 폼 입니다.

 

 

 

 

 

 

 

그림 1) A 폼 닫고 B 폼 열기

솔루션 탐색기에서 'Program.cs'를 클릭합니다.


2. 구현

아래의 글 상자는 초기 소스 코드입니다.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace sample
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Login());
        }
    }
}

아래와 같이 신규 선언을 해줍니다.

            Application.Run(new Login());
            Main MainApp = new Main();
            Application.Run(MainApp);


Main은 이 예제의 실제 파일 이름입니다.
Application.Run()은 메인 폼 호출에서 도출해낸 아이디어입니다.



A폼으로 소스(Login.Designer.cs)를 엽니다.
초기 소스는 아래와 같이 선언되어 있음을 알수 있습니다.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace sample
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }
    }
}


폼을 아래와 같이 구성 합니다.



그리고 버튼을 더블 클릭합니다.

        private void sLogin_Btn_Click(object sender, EventArgs e)
        {
        }


위와 같은 소스가 추가 됨을 알 수가 있습니다.

        {
        }


사이에 소스 코드를 입력합니다.

            Main MainApp = new Main();
            MainApp.Show();

            this.Close();



그리고 B 폼을 신규 윈도우 폼 추가합니다. 폼 이름은 Main으로 설정합니다.

조금 여운을 남겨놓습니다.
Program.cs에 클래스를 활용한다면 A 폼을 종료할 때 B 폼이 강제적으로 실행되는 것을 막을 수 있습니다.

반응형
728x90
300x250

[ASP.NET] C# 환경에서 URL 호출 - HttpWebResponse, HttpWebRequset

 

System.Net을 이용하여 처리하는 방법도 있겠으며, External URL에 관한 처리 방법은 다양합니다.
Stream으로 외부 URL을 원격으로 호출하는 방법에 관해 소개하겠습니다.

 


1. 구현

 

Namespace 선언

System.Text;

System.IO;

System.Web;

 

대상 URL 선언

string TargetURL = http://외부주소/index.do;

 

HttpWebRequest의 선언

HttpWebRequest gomRequest = (HttpWebRequest)WebRequest.Create(TargetURL);

 

HttpWebResponse의 선언

HttpWebResponse ckResponse = (HttpWebResponse)gomRequest.GetResponse();

 

응용) C# 환경에서 URL을 호출하여 Stream으로 받는 예제

 

Java 환경에서 URLConnection 과 같은 기능을 구현해보게 되었다.

특정 URL로 POST 방식으로 호출을 한 후 응답을 String 받는 기능을 수행한다.

HttpWebResponse 객체를 이용하여 Java의 URLConnection 와 동일하게 이용한다.

 

 

StringBuilder postParams = new StringBuilder();

postParams.Append("id=" + "abcd");

postParams.Append("&pw=" + "1234");

 


Encoding encoding = Encoding.UTF8;

byte[] result = encoding.GetBytes(postParams.ToString());

 


// 타겟이 되는 웹페이지 URL

string Url = "http://localhost:8080/MavenEULI/index.do";    //~~~~/login.php;  //수정해주세요.

HttpWebRequest wReqFirst = (HttpWebRequest)WebRequest.Create(Url);

 // HttpWebRequest 오브젝트 설정

 


wReqFirst.Method = "POST";

wReqFirst.ContentType = "application/x-www-form-urlencoded";

wReqFirst.ContentLength = result.Length;

 

 

 

Stream postDataStream = wReqFirst.GetRequestStream();

postDataStream.Write(result, 0, result.Length);

postDataStream.Close();

HttpWebResponse wRespFirst = (HttpWebResponse)wReqFirst.GetResponse();

 


// Response의 결과를 스트림을 생성합니다.

Stream respPostStream = wRespFirst.GetResponseStream();

StreamReader readerPost = new StreamReader(respPostStream, Encoding.UTF8);

 


// 생성한 스트림으로부터 string으로 변환합니다.

string resultPost = readerPost.ReadToEnd();

 


txt1.Text = resultPost;

 

 


2. 참고자료(Reference)

 

1. MSDN - HttpWebResponse 클래스, http://msdn.microsoft.com/ko-kr/library/system.net.httpwebresponse(v=vs.110).aspx, 접속일자 2013-12-16

2. MSDN - HttpWebRequest - 클래스를 사용하여 데이터 전송, http://msdn.microsoft.com/ko-kr/library/debx8sh9(v=vs.110).aspx, 접속일자 2013-12-16

반응형
728x90
300x250

[C#.NET] DirectoryInfo - 디렉토리 내 파일 무시하고 강제 삭제

 

디렉토리 내 파일을 무시하고 강제로 삭제하는 방법에 대해서 소개합니다.


1. 구현

 

DirectoryInfo di = new DirectoryInfo(가상의 디렉토리);

di.Delete(부울 조건);

 

부울 조건 : true, false로 처리

 


2. 하위 디렉토리 내 폴더 및 파일 존재 여부 찾기

if(di.GetDirectories().Length != 0 || di.GetFiles().Length != 0)

 

이와 같은 조건으로 찾을 수 있습니다.

 

GetDirectories().Length

(폴더의 수를 의미합니다.)

GetFiles().Length

(파일의 수를 의미합니다.)

 


3. 참고자료(Reference)

 

1. http://msdn.microsoft.com/ko-kr/library/system.io.directoryinfo_methods(v=vs.110).aspx

반응형
728x90
300x250

[C#.NET] AES를 통한 파일 암호화 구현 예제

 

AES를 통한 파일을 암호화하는 방법에 관해 논해보겠습니다.

C#을 통해 파일을 암호화하는 방법입니다.

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

using System.Security; 

using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        // Rfc2898DeriveBytes constants:
        public readonly byte[] salt = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

      // Must be at least eight bytes.  MAKE THIS SALTIER!
      public const int iterations = 1042; // Recommendation is >= 1000.


        public static void Main(string[] args)
        {

 

        }

 

복호화(Encrypt)

 

public static void EncryptFile(string inputFile, string outputFile)
{

     try
     {
         string password = @"myKey123"; // Your Key Here
         UnicodeEncoding UE = new UnicodeEncoding();
         byte[] key = UE.GetBytes(password);

         string cryptFile = outputFile;
         FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

         RijndaelManaged RMCrypto = new RijndaelManaged();

         CryptoStream cs = new CryptoStream(fsCrypt,
         RMCrypto.CreateEncryptor(key, key),
         CryptoStreamMode.Write);

         FileStream fsIn = new FileStream(inputFile, FileMode.Open);

         int data;
         while ((data = fsIn.ReadByte()) != -1)
              cs.WriteByte((byte)data);


              fsIn.Close();
              cs.Close();
              fsCrypt.Close();
        }
     catch
     {

     }
}

 

부호화(Decrypt)

 

/// Decrypts a file using Rijndael algorithm.
///</summary>
///<param name="inputFile"></param>
///<param name="outputFile"></param>
public static void DecryptFile(string inputFile, string outputFile)
{

    {
        string password = @"myKey123"; // Your Key Here

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] key = UE.GetBytes(password);

        FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

        RijndaelManaged RMCrypto = new RijndaelManaged();

        CryptoStream cs = new CryptoStream(fsCrypt,
        RMCrypto.CreateDecryptor(key, key),
        CryptoStreamMode.Read);

        FileStream fsOut = new FileStream(outputFile, FileMode.Create);

    

        int data;
        while ((data = cs.ReadByte()) != -1)
             fsOut.WriteByte((byte)data);

             fsOut.Close();
             cs.Close();
             fsCrypt.Close();

        }
}

반응형
728x90
300x250
[ASP.NET] 문자열 일자 정보 날짜의 형태로 표시하기

2013-11-28 오전 12:00:00


이런 꼴로 문자열 날짜가 되어있을 때, 날짜의 형태를 yyyy-MM-dd 꼴로 바꾸는 방법에 대해 소개 하겠습니다.
이 글은 ASP.NET 4로 작성되었습니다.


1. 구현

string sValue = "2013-11-28 오전 12:00:00";
String.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(sValue));

 

이처럼 사용하면, 문자열 날짜 정보를 쉽게 다양한 날짜 형태로 나타낼 수 있습니다.

 

Convert.ToDateTime()이라는 명령어는 날짜형 자료로 변환해주는 기능을 수행하는 명령어입니다.

String은 문자 정의 함수를 의미하며 Format은 String의 형태를 바꿔주는 명령을 수행합니다.

반응형
728x90
300x250
[C#] 하드웨어 정보 가져오기 - 구현 방법

 

C#으로 하드웨어 정보 가져오기에 대한 구현 방법을 소개하고자 합니다.

 


1. 참조 라이브러리


솔루션 -> 참조 -> Microsoft.VisualBasic

 


2. 구현


using System.Management;

 

private void Form2_Load(object sender, EventArgs e)
{
            int i;

            /// 배치 장소
            c_area.Items.Add("본사");
            c_area.Items.Add("영업지사");
            c_area.Items.Add("개발");


            /// 배치 부서
            c_department.Items.Add("사무실");
            c_department.Items.Add("생산");
            c_department.Items.Add("설계");
            c_department.Items.Add("출하");
            c_department.Items.Add("회의실");
            c_department.Items.Add("사장실");


            /// 자산 구분
            c_asset.Items.Add("소유");
            c_asset.Items.Add("임대");


            /// 자산 형태
            c_type.Items.Add("데스크탑");
            c_type.Items.Add("노트북");
            c_type.Items.Add("넷북");
            c_type.Items.Add("타블렛노트");
           
            // 전산장비 정보 가져오기

            // 1. CPU 정보 가져오기
            ManagementObjectSearcher MS2 = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (ManagementObject MO in MS2.Get())
            {
                c_CPU.Text = MO["Name"].ToString();
            }
            // 2. RAM 정보 가져오기
            ulong a = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / 1024 / 1024;
            string b = a.ToString() + "MB";
            c_RAM.Text = b;
            // 3. M/B 정보 가져오기
            MS2 = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
            foreach (ManagementObject MO in MS2.Get())
            {
                c_MB.Text = MO["Product"].ToString();
            }
            // 4. VGA 정보 가져오기
            MS2 = new ManagementObjectSearcher("Select * from Win32_DisplayConfiguration");
            foreach (ManagementObject MO in MS2.Get())
            {
                c_VGA.Text = MO["Description"].ToString();
            }
            // 5. HDD 정보 가져오기

            List<HardDrive> hdCollection = new List<HardDrive>();
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

            foreach (ManagementObject wmi_HD in searcher.Get())
            { 
               HardDrive hd = new HardDrive();
               hd.Model = wmi_HD["Model"].ToString();
               hd.Type = wmi_HD["InterfaceType"].ToString();
               hdCollection.Add(hd);
            }
            searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
            int ii = 0;
            foreach (ManagementObject wmi_HD in searcher.Get())
            {
                if (ii >= hdCollection.Count)
                {
                    break;
                }
           
                HardDrive hd = (HardDrive)hdCollection[ii];
                // get the hardware serial no.

                if (wmi_HD["SerialNumber"] == null)
                    hd.SerialNo = "None";
                else
                    hd.SerialNo = wmi_HD["SerialNumber"].ToString().Trim();

                ++ii;
            }

            c_HDD_1.Text = hdCollection[0].Model.ToString();
            c_HDD_Type_1.Text = hdCollection[0].Type.ToString();
            if (hdCollection.Count < 1)
            {
                c_HDD_2.Text = hdCollection[1].Model.ToString();
                c_HDD_Type_2.Text = hdCollection[1].Type.ToString();
            }
        }

       

 

// 하드 정보담는 공간
        public class HardDrive
        {
            private string model = null;
            private string type = null;
            private string serialNo = null;
            public string Model
            {
                get { return model; }
                set { model = value; }
            }
            public string Type
            {
                get { return type; }
                set { type = value; }
            }
            public string SerialNo
            {
                get { return serialNo; }
                set { serialNo = value; }
            }
        }

 

 


3. 참고자료(Reference)


1. http://anothermsdn.com/?paged=13, Accessed by 2013-08-04

=> 현재 웹사이트 폐쇠됨.

 

반응형
728x90
300x250
[C#.NET] 소스 코드 요약하기 - #region

#region 이름

#endregion 

#region ~ #endregion 명령어에 감사하다는 생각을 자주 한다.
-> 이거 사용하면 의외로 편함.

반응형
728x90
300x250

[ASP.NET] 경고 없이 열린 창 닫기



Fig 1) 알림창, 지금 보고 있는 웹 페이지 창 닫기

Javascript의 window.close() 명령을 사용하면 보통 위의 그림과 같이 경고 문구가 실행됩니다.
이와 같은 것을 방지하고 종료가 될 수 있도록 하는 방법을 소개하고자 합니다.


1. 결과물

 

 


2. 구현

1. 링크 버튼 하나를 만듭니다.

2. 소스 코드

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            ClientScriptManager sm = Page.ClientScript;
          string script = "<script>window.opener='nothing';window.open('','_parent','');window.close();</script>";
            sm.RegisterStartupScript(this.GetType(), "sm", script);
        }


* (참고) Javascript 코드

<script>
    window.opener = 'nothing';
    window.open('', '_parent', '');
    window.close();
</script>

이와 구현하면 경고 창 없이 C#에서 현재 창을 종료할 수 있습니다.

반응형

+ Recent posts