달력

52024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

MDI를 이용하여 프로그램을 짜다가 현재 활성화 된 자식폼의 함수를 호출하는 부분에 대한 문제가 발생했다.

MDI부모창에서 Child1 이라는 자식폼을 만든경우


child1 에서는 

public void 함수명()


Child1 child = (Child1)this.this.ActiveMdiChild;

child.함수명();


이라고 했으면 호출 되는게 당연하다.

MDI 에서 파일 저장하기를 하려고 하다가 문제가 발생했다.

자식폼이 하나가 아닌 것이다.. 자식폼이 여러개라면 ??

Child1인지 Child2 인지 모르기 때문에 child2 를 저장하는데 Child1을 선언했다면 오류가 날것이다.

그래서 인터넷을 뒤지다가 여러가지 정보를 모아서 성공!!!


우선 클래스 파일을 하나 만든다

MdiChildForm.cs 라고 하자.

public class MdiChildForm: Form   // fForm을 상속받자 (using System.Windows.Forms;)

    {

        public virtual void saveFile()   자식폼에서 호출될 함수 이름...  virtual로 선언.

        {

        }

    }


자식 폼에는 아래와 같이 함수를 추가 한다.


pubcli override void saveFile()

{

 .....내용 ....

}



MDI부모폼에서는 아래와 같이 사용한다.

private void Save_ToolStripMenuItem_Click(object sender, EventArgs e)

        {


            MdiChildFormchild = (MdiChildForm)this.ActiveMdiChild;

            child.saveFile();

        }


이로써 자식폼이 여러개일지라도 해당 자식폼의 함수를 호출 할 수 있게 되었다.




Posted by SadDev
|

서버와 클라이언트간의 데이터 전송을 하다보면 여러가지 일이 생긴다.

그중 보안적인 문제가 있는데 이를 위해 암호화를 시도!!

그 과정에서 만든 소스를 올려본다.


using System;

using System.IO;

using System.Security.Cryptography;


namespace DataCrypt

{

    public class Crypt

    {

        //Rijndael 암호화 

        private RijndaelManaged rmCrypt;

        private byte[] KEY;

        private byte[] IV;


        public Crypt()

        {

            rmCrypt = new RijndaelManaged();

        }


        /// <summary>

        /// 암호화 키

        /// </summary>

        public byte[] Key

        {

            get { return KEY; }

        }


        /// <summary>

        /// 암호화 벡터 값

        /// </summary>

        public byte[] Iv

        {

            get { return IV; }

        }

        

        /// <summary>

        /// 버퍼 데이터를 암호화 

        /// </summary>

        /// <param name="buffer">암호화할 데이터</param>

        /// <returns></returns>

        public byte[] Encrypt(byte[] buffer)

        {

            rmCrypt.GenerateKey();

            rmCrypt.GenerateIV();

            KEY = rmCrypt.Key;

            IV = rmCrypt.IV;

            return EncryptBytes(buffer);

        }


        /// <summary>

        /// 버퍼 데이터를 복호화

        /// </summary>

        /// <param name="buffer">복호화 할 데이터</param>

        /// <param name="key">암호화 키</param>

        /// <param name="iv">암호화 벡터 값</param>

        /// <returns></returns>

        public byte[] Decrypt(byte[] buffer, byte[] key, byte[] iv)

        {

            rmCrypt.Key = key;

            rmCrypt.IV = iv;

            return DecryptBytes(buffer);

        }

       

        /// <summary>

        /// 암호화 함수

        /// </summary>

        /// <param name="data">암호화 할 데이터</param>

        /// <returns></returns>

        private byte[] EncryptBytes(byte[] data)

        {

            if (data == null || data.Length == 0)

            {

                return data;

            }


            if (rmCrypt == null)

            {

                throw new ArgumentNullException("rmCrypt");

            }


            using (MemoryStream stream = new MemoryStream()) 

            using (ICryptoTransform encryptor = rmCrypt.CreateEncryptor())

            using (CryptoStream cryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))

            {

                cryptStream.Write(data, 0, data.Length);

                cryptStream.FlushFinalBlock();

                return stream.ToArray();

            }

        }


        /// <summary>

        /// 복호화 함수

        /// </summary>

        /// <param name="data">복호화 할 데이터</param>

        /// <returns></returns>

        private byte[] DecryptBytes(byte[] data)

        {

            if (data == null || data.Length == 0)

            {

                return data;

            }


            if (rmCrypt == null)

            {

                throw new ArgumentNullException("rmCrypt");

            }


            using (MemoryStream stream = new MemoryStream())

            using (ICryptoTransform decryptor = rmCrypt.CreateDecryptor())

            using (CryptoStream cryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))

            {

                cryptStream.Write(data, 0, data.Length);

                cryptStream.FlushFinalBlock();

                return stream.ToArray();

            }

        }        

    }

}



사용법은 간단하게

Crypt crypt = new Crypt();

byte[] buffer = crypt.Encrypt(tmpBuffer);

식으로 하면 암호화 된 데이터가 넘어온다..

복호화의 경우는  key와  iv가 필요하다.

byte[] buffer = crypt.Decrypt(tmpBuffer, key, iv);




Posted by SadDev
|

c 에서 사용하는 pointer 구조처럼 C#의 BinaryWriter에 사용하는법

MemoryStream ms = new MemoryStream();

BinaryWriter bw = new BinaryWriter(ms);

 

int a = 400;

bw.write(&a);

라는 형태로 메모리  pointer를 C#에서는 사용할수가 없다.

 

그래서 알아보니 bw.seek() 을 쓰면 된다고 해서 써봤다..

 

int a = 400;

int b = 500;

int c = 600;

int d = 999;

int e = 700;

bw.write(a);

long pointer = bw.BaseStream.position;

bw.write(b);

bw.write(c);

bw.seek((int)pointer, SeekOrigin.Begin);

bw.write(d);

bw.seek(0, SeekOrigin.End);

bw.write(e);

 

결과

400

999  //b가 500 이지만 pointer 위치를 다시 덮어 씌워서 d 를 넣었음로 999가 들어가게된다.

600

700

 

우선 이렇게 해서 해결!

Posted by SadDev
|

갤S2 HD LTE 를 사용하고 있다.

My Maket 어플을 이용하여 일본 지하철 노선도를 다운 받았다.

하지만 다운로드 완료 표시는 계속 나타나는데 설치는 되지 않는데.

더군다나 다운로드 완료 표시는 확인을 해도 조금 후면 다시 나타난다..

혹시나 하는 마음에 다시 다운로드를 받아봤는데.... 다운로드 완료 표시가 2개로 늘어났다 -ㅅ-

 

USB모드로 PC에 연결하여 다운받은 APK 파일을 지웠지만 결과는 동일....

 

하지만 의외로 쉽게 해결이 되었다.

내가 어플 다운로드를 실행한 My Market 어플의 데이터 삭제를 실행..(어플 삭제가 아니다)

환경설정 => 어플리케이션 관리 => 다운로드 어플(Play 스토어나 my Market) 의 데이터 삭제 를 하면 해결 되는 것 같다.

 

'기타' 카테고리의 다른 글

Sony Gold Wireless Stereo Headset  (0) 2014.08.05
[PSP] 윈도우7, IPTIME N150UA, 카이 설정하기.  (1) 2012.02.14
[음식] 과천 소담 한정식  (0) 2011.09.18
[키보드] RAZER BlackWidow  (0) 2011.09.01
누니 결혼식 동영상  (0) 2011.03.10
Posted by SadDev
|
index.php

$('#file_upload').uploadify({
   'uploader'  : './swf/uploadify.swf',
   'script'    : './common/uploadify.php',
   'cancelImg' : './images/cancel.png',
   'folder'    : './uploads<?=$path?>',
   'multi'     : true,
   'fileExt'   : '*.jpg;*.jpeg;*.png;*.gif',
   'onComplete'  : function(event, ID, fileObj, response, data) {
    var ret = response.toString().split('|');
    if(ret[0] != 0){
     alert("Err : " + ret[0] + "\n" + ret[1]);     // ret[0] = 오류 코드 ,  ret[1] = 파일명     uploadify.php 에서 받은 리턴값
    } else {
     $("#filename").val(ret[1]);
          $.ajax({
           url : './common/upload.php',
           type : 'POST',
           dataType : 'json',
           data : $('form').serialize(),
           timeout : 5000,
           error : function(xhr){
            alert('DB 저장 중 오류가 발생하였습니다.\n' + xhr.responseText);
           },
           success : function(xhr){
       getThumbnailList(pathid);
           }
          });
    } 
      }
  });



<form name="frmFile" id="frmFile" method="POST" action="common/upload.php">
    <input type="hidden" id="filename" name="filename" value="" />
    <input type="hidden" id="pathID" name="pathID" value="<?=$pathid?>" />
    <input type="hidden" id="pathDir" name="pathDir" value="uploads<?=$path?>" />
    <div id="uploadBtn_layer"><input type="button" id="btnStartUpload" value="업로드 시작"/></div>

    <input type="file" name="file_upload" id="file_upload" />
   </form>

pathid 나  pathDir 은 DB에서 읽어온 정보를 넣는 것이므로 개인적인 작업이라 무시하시고 수정해서 사용 가능

jquery.uploadify.xx.js 파일  에서
g.folder=escape(f.folder); 를 찾아서
g.folder=encodeURIComponent(f.folder);  로 수정


Uploadifiy.php

if (!empty($_FILES)) {
  $tempFile = $_FILES['Filedata']['tmp_name'];
  $targetPath = $_SERVER['DOCUMENT_ROOT'] . urldecode($_REQUEST['folder']) . '/';    ///* 폴더 명을 urldecode 로 받는다.  */;
  $filename = iconv("UTF-8", "EUC-KR", $_FILES['Filedata']['name']);    // /* 파일 명을 urldecode 로 받고  iconv 로 처리 */
  $targetFile =  str_replace('//','/',iconv("UTF-8", "EUC-KR", $targetPath)) . $filename;   // /* 폴더명도 iconv 처리  */
  
   if(file_exists($targetFile)){
   echo "-200|overlap file name. [".iconv("EUC-KR", "UTF-8", $filename)."]";    // 이미 파일이 존재할  경우 -200cjfl
  } else {
   move_uploaded_file($tempFile, $targetFile);
   echo "0|".iconv("EUC-KR", "UTF-8", $filename);     // 업로드 성공하면 0
  }
 }
 else
 {
  echo "-100|Uploaded file is empty.";      // 파일이 없으면 -100 처리
 }
uploadify.php 에서 성공 처리 되면  upload.php 를  호출해서 DB에 데이터를 넣는다 이때 중요한것은 uploadify.php 에서 리턴시 다시 iconv("EUC-KR", "UTF-8", $filename)로
반대로 인코딩 해서 보내야 정상적으로 처리된다.. serialize 자체가 encodeURIcomponent() 가 붙다보니.. 인코딩 디코딩 부분이 까다롭다.

Upload.php

$filename = urldecode($_REQUEST['filename']);   // file명은 꼭 urldecode로
 $pathId = $_REQUEST['pathID'];
 if($pathId == "") $pathId = 1;
  $fullpath = "gallery/uploads";
 $path_result = mysql_query("select * from path where pidx = $pathId") or die(mysql_error());
 while($path_row = mysql_fetch_array($path_result)){
  $fullpath = $path_row[FULLPATH];
 }
 
 $targetFile =  $_SERVER['DOCUMENT_ROOT'] . $lib->upload_dir . iconv("UTF-8", "EUC-KR", $fullpath) . iconv("UTF-8", "EUC-KR", $filename);   // 경로명은 DB에서 가져와서 iconv 만 했지만 파라미터로 받을 경우 urldecode 후 iconv
 $ext = substr(strrchr($targetFile, '.'), 1);
 $filesize = filesize($targetFile);
 $width = 0;
 $height = 0;
 if(strtolower($ext) == "jpg" || strtolower($ext) == "gif" || strtolower($ext) == "png") {
  list($width, $height) = getimagesize($targetFile);
 }
 $now = date("Y-m-d h:i:s", time());
 //$filename = iconv("EUC-KR", "UTF-8", $filename);
 $file_query = "insert into Files (filename, pidx, extension, width, height, filesize, regdate)
  values('$filename','$pathId','$ext','$width','$height','$filesize','$now')";
 
 mysql_query($file_query) or die(mysql_error());



대충 문제가 됐던 것은 php 에서 리턴받은 한글 파일을 다시 다른 페이지로 넘기는 과정에서 한글 문제가 있었다.
어쨋든 폴더명이 한글이던 파일명이 한글이던 잘 올라간다.





Posted by SadDev
|