codeigniter 2.X 대 에서 IE 9 에서 세션이 제대로 작동하지 않는 버그


다른 브라우져에서는 문제가 없는데, IE9 에서 세션 쿠키 명에 언더바를 지원하지 않는다.



/application/config.php 파일에서 세션 이름을 변경해주면 해결 가능~!


$config['sess_cookie_name'] = 'XXX_XXXXX';

위처럼 되어있는것을 아래 처럼 _ 를 제거한 형태로 변경해주면 해결가능

$config['sess_cookie_name']  = 'XXXXXXXX';


 

CodeIgniter + uploadify + Session Cookie (Flash)


The solution:
This guide has been written for CI 2.1.0, it can easily be edited for prior versions.

EDIT
-In later versions of uploadify post_params in JavaScript may be replaced by formData

1. Extend CI_Session
Create a MY_Session.php under /application/libraries or extend your own one. Copy the whole sess_read() function from /system/libraries/Session.php and paste it into your newly created MY_Session.php.

Replace:

$session $this->CI->input->cookie($this->sess_cookie_name); 

With:

if (isset($_POST['browser_cookie']))
  
{
   $_cookie 
$this->CI->input->post('browser_cookie');
   
$enc_key $this->CI->config->item('encryption_key');
   
$session trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256$enc_keybase64_decode($_cookie), MCRYPT_MODE_ECBmcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256MCRYPT_MODE_ECB), MCRYPT_RAND)));
  
else {
   $session 
$this->CI->input->cookie($this->sess_cookie_name);
  

2. Session Library Setup
Setup your Session Library properly (add an encryption_key in your config.php) and enable table based sessions as well as disable sess_match_useragent in config.php (important!)

3. In your view where uploadify is embedded, you will have to append post params to your upload function. Here is a sample code:

$('#do_upload').uploadify({
  swf
'/js/uploadify/uploadify.swf',
  
uploader'/objects/upload_images/' object_id,
  
post_params{"browser_cookie""<?= trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->config->item('encryption_key'), $_COOKIE[$this->config->item('sess_cookie_name')], MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); ?>"},
  
cancelImage'/js/uploadify/uploadify-cancel.png',
  
checkExistingfalse,
  
multitrue,
  
autotrue,
  
onUploadSuccess: function(filedataresult){
     
//do something useful
  
}
 }
); 

This has to be parsed by your PHP parser in order to fill the values. You could also just declare a variable like

var browser_cookie = “<?= trim…....... ?>”

and just load this global variable in your upload function.

4. How does it work?
Basically it generates an encrypted version of your session cookie and posts it to your server. As you have already modified the session class, it recognizes that your session cookie has been sent via post and is using this instead. Basically it’s just a simulation of what the browser would do if it wasn’t Flash.

5. Conclusion and caveats
If CI Basis is updated, don’t forget to update your MY_Session as well. It is just ensuring that.

Make sure that your cookie is valid before sending the files to your server. Otherwise you could raise the value of “sess_time_to_update” in your config.php.



출처 : https://ellislab.com/forums/viewthread/216227/#999189

 

jqueryUI tab 안에 구글 맵을 삽입하면 이상하게도 가로 사이즈가 특정 부분부터 짤려서 늘어나질 않는다 -ㅅ-;;;

원인은 맵 초기화 함수의 호출 위치~!

보통 body onload 나 $(function(){}); 안에 위치시키는 구글맵 초기화 함수를

tab load 혹은 show 되어 질때 호출 하면 문제는 깔끔하게 해결된다.


[code]
$("#google-map-tab").tabs({
    show: function(event, ui) {
   google_map_initialize(); //map initialize   
    }
});
[/code]

참조 :

Google Maps JavaScript API V3 : 데스크톱 및 휴대기기용 지도 애플리케이션을 위한 솔루션
http://code.google.com/intl/ko-KR/apis/maps/documentation/javascript/

jQueryUI : jquery ui
http://jqueryui.com/

 

PHP 5.1.2 업데이트

저자: Christopher Jones, Consulting Technical Staff, Oracle Corporation
업데이트일: 2006년 1월

Oracle 10g Instant Client (무료로 다운로드가 가능합니다)는 PHP를 원격 오라클 데이터베이스에 연결하기 위한 가장 손쉬운 방법으로, 3 개의 라이브러리만 설치하면 사용이 가능합니다.

PHP에서 Oracle API의 액세스에 사용되는 Instant Client 라이브러리는 OCI8이라는 이름으로 불립니다 (이 이름은 Oracle8 버전에서 최초로 개발되면서 붙여진 것입니다). PHP Oracle 8 함수 를 이용하여 Oracle 8.1.7, 9.x, 10.x를 직접 호출할 수 있고, 또는 PEAR MDB2ADOdb 등의 추상화 클래스(abstraction class)를 함께 이용할 수도 있습니다.

구 버전의 PHP “oracle” 익스텐션을 Instant Client에서 이용하는 것도 가능하지만, 이 경우에는 (오라클에 의해 더 이상 지원되지 않는) 구 버전의 Oracle API가 사용됩니다. 이러한 이유로, PHP 커뮤니티와 오라클은 새로운 개발작업에서 이 익스텐션을 사용하는 것을 권장하지 않고 있습니다.

Apache 환경에서 PHP 4 또는 PHP 5와 함께 Instant Client를 사용하기 위한 방법이 아래에 설명되어 있습니다. (5.1.2와 OCI8 익스텐션에 관련한 상세한 정보는 이 섹션을 참고하시기 바랍니다.) Instant Client에는 오라클 데이터베이스가 포함되어 있지 않으므로, 별도의 데이터베이스 환경이 미리 구축되어 있어야 합니다.

일반적으로 데이터베이스는 다른 머신에서 운영됩니다. 데이터베이스가 로컬에 설치된 경우에는, 필요한 오라클 컴포넌트가 이미 사용 가능하므로, Instant Client를 따로 설치할 필요가 없습니다.

소프트웨어 요구사항:

소프트웨어 참고
Oracle Instant Client "Instant Client Package - Basic"을 다운로드합니다. Linux 환경의 경우, "Instant Client Package - SDK"를 함께 다운로드합니다.
Apache HTTPD Server PHP 커뮤니티는 Apache 1.3을 권장하고 있습니다.
PHP - PHP Hypertext Processor Version 4.3 또는 이후 버전

Windows 환경에서 PHP OCI8 Extension 활성화하기

Instant Client 바이너리는 PHP에 포함된 Windows용 바이너리를 보완하는 역할을 담당하게 됩니다.

  1. (installer build가 아닌) PHP 바이너리 zip 파일과 Apache를 다운로드합니다. PHP 매뉴얼의 Windows 시스템 설치 가이드를 참고하여 설치 작업을 수행합니다. OTN의 오픈 소스 개발자 센터에서 "Oracle, PHP, and Apache on Windows 2000/XP 환경의 Oracle, PHP, Apache 설치,"와 같은 유용한 기술정보를 참고하실 수 있습니다. 이 문서에는 Oracle 10g를 전체 설치하는 방법이 설명되어 있습니다 (Instant Client 설치 시에는 이 작업이 필요하지 않습니다).

    다음 단계로 진행하기 전에 PHP가 제대로 동작하는지 확인합니다. 이 단계에서는 오라클 연동 기능은 지원되지 않습니다.

  2. OTN의 Instant Client 페이지에서 Instant Client Basic package for Windows를 다운로드합니다. zip 파일의 사이즈는 대략 30 MB 정도 됩니다.

  3. 서브디렉토리(예: c:\instantclient10_1)를 생성하고 zip 파일로부터 아래 라이브러리를 복사합니다:

    • oraociei10.dll
    • orannzsbb10.dll
    • oci.dll

    3개 파일의 총 용량은 약 80MB 정도 됩니다.

    PHP의 구 버전 oracle extension을 사용하려는 경우, oci.dll 대신 ociw32.dll을 복사합니다 (이 익스텐션을 활성화하려면 php.ini 파일에서 "extension=php_oracle.dll"로 설정합니다.)

  4. PATH 환경변수를 편집하여 “c:\instantclient10_1”가 다른 오라클 디렉토리의 앞에 위치하게 합니다.

    Windows 2000의 경우, 시작 -> 설정 -> 제어판 -> 시스템 -> 고급 -> 환경 변수로 이동하여 시스템 변수 목록의 PATH를 편집합니다.

    tnsnames.ora 파일을 이용하여 Oracle Net 서비스 네임을 정의한 경우, tnsnames.ora를 c:\instantclient10_1로 복사하고 사용자 환경변수 TNS_ADMIN을 c:\instantclient10_1로 복사합니다. 디폴트 서비스 네임은 사용자 환경변수 LOCAL에 추가로 설정할 수 있습니다.

    NLS_LANG과 같은 Oracle globalization language 환경변수를 필요에 따라 설정합니다. 아무것도 설정되지 않은 경우, 디폴트 로컬 환경이 그대로 사용됩니다. 자세한 정보는 An Overview on Globalizing Oracle PHP Applications 문서를 참고하십시오.

    Unset unnecessary Oracle variables such as ORACLE_HOME and ORACLE_SID.

  5. php.ini를 편집하고 OCI8 익스텐션의 커멘트 기호를 삭제합니다:

    extension=php_oci8.dll
    

    extension_dir 항목에 PHP 익스텐션 DLL의 전체 경로를 설정합니다. PHP4의 경우 DLL은 PHP 소프트웨어의 “extensions” 서브디렉토리에 위치합니다. PHP5에서는 “ext” 서브디렉토리에 위치합니다.

  6. Apache를 재시작합니다.

익스텐션이 설정되었음을 확인했다면, 웹 서버에서 접근할 수 있는 위치에 간단한 PHP 스크립트(phpinfo.php)를 생성합니다.

<?php
  phpinfo();
?>

"http://" URL을 사용하여 브라우저에서 스크립트를 로드합니다. 브라우저 페이지의 "oci8" 섹션에서 "OCI8 Support enabled"라는 문구를 확인할 수 있어야 합니다.

Linux에서 PHP OCI8 Extension 활성화하기

Linux 환경에서 오라클 연결을 추가하려면, 먼저 PHP를 다시 컴파일해야 합니다.

OTN의 오픈 소스 개발자 센터에서 " Linux에서 Oracle, PHP, Apache 설치하기",와 같은 유용한 기술정보를 참고하실 수 있습니다. 이 문서에는 Oracle 10g를 전체 설치하는 방법이 설명되어 있습니다 (Instant Client 설치 시에는 이 작업이 필요하지 않습니다.

  1. Apache를 다운로드하여 설치합니다. 사용자의 홈 디렉토리에 Apache를 설치하는 예가 아래와 같습니다:
    cd apache_1.3.31
    ./configure --enable-module=so --prefix=$HOME/apache --with-port=8888
    make
    make install
    

    $HOME/apache/conf/httpd.con을 편집하여 아래 항목을 추가합니다:

    AddType application/x-httpd-php        .php
    AddType application/x-httpd-php-source .phps
    
  2. PHP를 다운로드하여 tar 압축을 풉니다.
  3. OTN의 Instant Client 페이지에서 Basic/SDK Instant Client Package를 다운로드합니다. 두 RPM의 전체 크기는 약 30MB 가량 됩니다.
  4. root 사용자로 RPM을 설치합니다.
    rpm -Uvh oracle-instantclient-basic-10.1.0.3-1.i386.rpm
    rpm -Uvh oracle-instantclient-devel-10.1.0.3-1.i386.rpm
    

    첫 번째 RPM은 오라클 라이브러리를 /usr/lib/oracle/10.1.0.3/client/lib에 설치하고, 두 번째 RPM은 /usr/include/oracle/10.1.0.3/client에 헤더를 생성합니다.

  5. 백업 후 이 패치를 PHP의 ext/oci8/config.m4에 적용합니다. 패치 라인 넘버는 PHP 4.3.9를 기준으로 하고 있습니다. (PHP 4.3.11와 5.0.4의 경우처럼) PHP bug 31084가 해결되었다면 이 패치를 적용할 필요는 없습니다.

    PHP 4.3.9 또는 4.3.10을 사용하는 경우에는 이 패치를 파일(예: php_oci8ic_buildpatch)에 저장한 후 아래와 같이 설치합니다:

    patch -u config.m4 php_oci8ic_buildpatch
    

    위 패치를 실행하면 새로운 PHP 설정 매개변수 --with-oci8-instant-client[=DIR]이 생성됩니다. Linux 운영체제는 기본적으로 RPM을 통해 설치된 Instant Client의 최신 버전을 사용합니다. 오라클 라이브러리의 경로를 지정함으로써 다른 버전을 사용하도록 할 수도 있습니다. 어떤 경우든 버전에 맞는 SDK 헤더가 자동적으로 적용됩니다.

    새로운 매개변수는 기존의 --with-oci8 매개변수를 대체합니다.

    참고: Linux 이외의 운영체제에서는, 사용자가 선택한 디렉토리에 Instant Client 패키지의 압축을 풀게 됩니다. --with-oci8-instant-client 매개변수를 사용하려면 이 디렉토리를 명시적으로 지정해 주어야 합니다 (예: --with-oci8-instant-client=/home/instantclient10_1) Instant Client SDK는 Basic Package와 같은 디렉토리에 압축을 풀어야만, 재구성된 configure 스크립트에서 헤더 파일의 서브디렉토리를 정확하게 찾을 수 있습니다.

  6. “configure” 스크립트를 최상위 PHP 디렉토리에서 rebuild 합니다.
    cd php-4.3.9
    rm -rf autom4te.cache config.cache
    ./buildconf --force
    
  7. 새로운 옵션을 이용하여 configure를 실행합니다. 홈 디렉토리에 Apache를 설치한 환경에서의 실행 예가 아래와 같습니다.
       ./configure \
          --with-oci8-instant-client \
          --prefix=$HOME/php --with-apxs=$HOME/apache/bin/apxs \
          --enable-sigchild --with-config-file-path=$HOME/apache/conf
    
  8. PHP를 rebuild합니다.
    make
    make install
    
  9. php.ini 파일을 --with-config-file-path에서 지정된 위치에 복사합니다.
    cp php.ini-recommended $HOME/apache/conf/php.ini
    
  10. LD_LIBRARY_PATH를 /usr/lib/oracle/10.1.0.3/client/lib으로 설정하고 Apache를 재시작합니다.

    tnsnames.ora 파일을 이용하여 Oracle Net 서비스 네임을 정의한 경우, TNS_ADMIN을 파일이 위치한 디렉토리로 설정해 줍니다.

    Apache를 시작하기 전에 모든 오라클 환경 변수를 설정해 주는 것이 중요합니다. 스크립트의 예가 아래와 같습니다:

    #!/bin/sh
    
    APACHEHOME=/home/apache
    
    LD_LIBRARY_PATH=/usr/lib/oracle/10.1.0.3/client/lib:${LD_LIBRARY_PATH}
    TNS_ADMIN=/home
    export LD_LIBRARY_PATH TNS_ADMIN
    
    echo Starting Apache 
    $APACHEHOME/apachectl start
    
익스텐션의 설정을 확인한 후, 웹 서버가 접근할 수 있는 위치에 간단한 PHP 스크립트(phpinfo.php)를 생성합니다.
<?php
  phpinfo();
?>

URL("http://localhost:8888/<path>/phpinfo.php”)을 사용하여 스크립트를 브라우저에 로드합니다. 브라우저 페이지의 "oci8" 섹션에서 "OCI8 Support enabled"라는 문구를 확인할 수 있어야 합니다.

오라클로의 연결

오라클 연결을 생성하려면 먼저 오라클 연결 정보를 OCILogon()에 전달해 주어야 합니다. Instant Client와 관련된 모든 툴은 데이터베이스 서버의 “원격”에 위치하며, 따라서 사용자 이름, 암호와 함께 Oracle Net connection identifier가 사용되어야 합니다. 기존에 구성된 오라클 데이터베이스에 대한 연결 정보는 외부에서 “well-known” 정보로 확인이 가능합니다. 새로 구성된 시스템에서는 데이터베이스 셋업 과정에서 오라클 설치 프로그램에 의해 설정됩니다. 인스톨러는 Oracle Net 설정 및 서비스 네임 생성 작업을 수행합니다.

새로운 데이터베이스에서 HR와 같은 샘플 스키마를 사용하려면 unlock 작업을 수행하고 암호를 입력해야 할 수 있습니다. 이를 위해 SQL*Plus에서 SYSTEM 사용자로 연결한 뒤 아래와 같이 실행해 줍니다:

ALTER USER username IDENTIFIED BY new_password ACCOUNT UNLOCK;
연결 정보를 PHP에 전달하는 방법에는 여러 가지가 있습니다. 먼저 Oracle 10g의 Easy Connect 신택스를 이용하여 mymachine에서 실행 중인 the MYDB 데이터베이스 서비스의 HR 스키마에 연결하는 방법이 아래와 같습니다. 이 경우 tnsnames.ora 또는 다른 Oracle Network 파일이 필요하지 않습니다:
$c = OCILogon('hr', 'hr_password', '//mymachine.mydomain/MYDB');

Easy Connect 신택스 관련 오라클 문서(Using the Easy Connect Naming Method)를 참고하시기 바랍니다.

또는, /home/tnsnames.ora에 다음과 같은 내용이 포함된 경우:
MYDB =
 (DESCRIPTION =
   (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.mydomain)(PORT = 1521))
   (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = MYDB)
    )
  )

그리고 TNS_ADMIN 환경변수가 (Apache 시작 이전에) /home으로 설정된 경우, 연결 문자열을 아래와 같이 설정할 수 있습니다:

$c = OCILogon('hr', 'hr_password', 'MYDB');

      
환경변수 LOCAL(Windows) 또는 TWO_TASK(Linux)가 MYDB로 설정된 경우, MYDB로의 연결을 위한 문자열이 다음과 같습니다:
$c = OCILogon('hr', 'hr_password');

Oracle의 사용

기본적인 연결에 성공했다면, 간단한 스크립트(testoci.php)를 테스트해 볼 차례입니다. 사용자의 데이터베이스 환경에 맞게 연결 설정을 수정한 후 브라우저에서 스크립트를 로드합니다. HR 사용자가 소유한 모든 테이블의 목록을 표시하는 스크립트 예가 아래와 같습니다:

<?php

$conn = OCILogon("hr", "hr_password", '//mymachine.mydomain:port/MYDB);

$query = 'select table_name from user_tables';

$stid = OCIParse($conn, $query);
OCIExecute($stid, OCI_DEFAULT);
 while ($succ = OCIFetchInto($stid, $row)) {
    foreach ($row as $item) {
      echo $item." ";
    }
    echo "<br>\n";
 }

 OCILogoff($conn);

 ?>
트러블슈팅

Oracle PHP Troubleshooting FAQ에서 오라클 연결에 관련한 유용한 정보를 확인하실 수 있습니다.

오라클의 SQL*Plus 커맨드라인 툴을 Instant Client 페이지에서 다운로드하여 환경 및 연결 문제를 해결하는데 이용할 수 있습니다. SQL*Plus Instant Client Release Notes를 참고하시기 바랍니다.

SQL*Plus를 이용하여 환경을 점검하는 방법은 phpino.php 스크립트의 예와 동일합니다.

Windows 도움말

phpinfo.php 스크립트를 실행했을 때 “oci8” 섹션에서 "OCI8 Support enabled" 메시지를 확인할 수 없다면, php.ini 파일에서 "extension=php_oci8.dll" 항목의 주석 처리가 해제되었는지 점검합니다.

PATH가 잘못 설정되어 있거나 오라클 라이브러리를 찾을 수 없는 경우, Apache 시작 시 다음과 같은 경고 메시지가 표시됩니다: "The dynamic link library OCI.dll could not be found in the specified path." phpinfo() 페이지의 Environment 섹션에서, PHP에 의해 실제로 사용되는 PATH와 Oracle 변수의 값을 확인할 수 있습니다.

php.ini에 extension_dir 매개변수가 올바르게 설정되지 않은 경우 Apache 시작 시 다음과 같은 경고 메시지가 표시됩니다: "PHP Startup: Unable to load dynamic library php_oci8.dll."

Linux 도움말

config.m4가 올바르게 패치되었는지 확인합니다. “configure”의 실행에 실패한 경우, config.log 파일을 점검합니다. config.m4를 이전 상태로 되돌리고 캐시 파일을 제거한 후 “./buildconf --force and configure”를 실행한 다음, 발생한 문제가 패치 작업과 관련된 것인지 확인합니다.

“configure”의 타임스탬프가 현재 시점으로 설정되어 있는지 확인합니다. 캐시 파일을 모두 제거하고 필요한 경우 rebuild 작업을 수행합니다.

Apache를 시작하는 쉘에서 필요한 모든 Oracle 환경변수를 설정해 줍니다.

PHP 5.1.2 및 이후 버전

“re-factored” OCI8 익스텐션은 Instant Client를 위한 새로운 신택스를 지원합니다. re-factored 익스텐션은 PHP 5.1.2에 처음으로 포함되었으며, 이전 버전의 PHP의 경우pecl.php.net/package/oci8, pecl4win.php.net/ext.php/php_oci8.dll에서 다운로드할 수 있습니다.

Technical Note에 명시된 대로 Instant Client RPM을 설치했다면, PHP를 아래와 같이 설정해 줍니다:

./configure \
    --with-oci8=instantclient,/usr/lib/oracle/10.1.0.3/client/lib \
    --prefix=$HOME/php --with-apxs=$HOME/apache/bin/a
	pxs \
    --enable-sigchild --with-config-file-path=$HOME/apache/conf
Instant Client Basic, SDK zip 파일을 사용하는 경우, 압축을 푼 디렉토리의 --with-oci8 옵션을 변경해 줍니다. 그 예가 아래와 같습니다:
--with-oci8=instantclient,$HOME/instantclient10_1 
re-factored 버전이 올바르게 설치되었는지 점검하려면 phpinfo() 실행 결과를 확인하면 됩니다. “oci8.” 접두어로 시작되는 7가지 매개변수를 확인할 수 있을 것입니다 (이전 버전에서는 이 매개변수가 존재하지 않습니다).

결론

이 문서가 여러분에게 도움이 되었기를 바랍니다. 질문이나 의견은 OTN Instant Client 또는 PHP 포럼에 올려 주시기 바랍니다.

출처 : http://www.oracle.com/technology/global/kr/pub/notes/technote_php_instant.html

'프로그래밍' 카테고리의 다른 글

jqueryUI tab에 구글맵 삽입시 유의점  (0) 2010.12.30
아이폰에서 메일이 깨져 보인다!!  (0) 2010.08.19
Windows Script Host  (0) 2009.09.18

 

스마트폰의 강세로 스마트폰 자체에서 제공하는 메일 클라이언트를 사용하는사람들이 많아졌다.
나도 아이폰 메일을 자주 쓰고 있는데, 문제는 euc-kr 인코딩상태에서 메일을 발송하는경우 메일 내용 의 헤더부분의 인코딩만 euc-kr로 선언되고, 메일 제목, 보내는사람 이름 등은 인코딩 선언이 빠져있어, utf-8 기본인 아이폰 메일함에서는 제목과 이름 부분이 ???? 등으로 깨져서 보인다.

지금 까지 확인된바로는~ 옥션의 보내는사람 이름 도 깨지고있고, 몇몇 사이트들의 메일 제목 / 이름등이 깨져있다. 각 업체들이 다 신경을 조금만 써준다면 받아보는 입장에서 편하련만~~

우리회사 메일발송부분이야 내가 수정을 했다지만 다른 업체들도 어서 빨리 수정해줬으면하는 맘이다.

- 메일 발송 하는부분의 상세 헤더를 작성하는 경우 한글이 들어가는부분을  아래와 같이 수정만 해주면 문제는 해결된다.

물론 적절한 메일헤더의 인코딩을 상단에서 작성하면 되지 않나 싶지만, 이는 utf-8 기본인 메일 클라이언트에서 from, to 등의 부분에 한글은 깨질가능성이 있으므로 (각 메일서버마다 설정이 제각각이므로-특히나 우리나라처럼 utf-8 기반을 무시하던 환경이라면 더더욱) 각 항목에 따로 인코딩을 걸어준다.
(예를 들어 gmail을 아이폰 메일클라인트로 받아보는경우)
(작성하는 부분의 인코딩과 메일헤더의 기본 인코딩은 당연히 맞춰서 작업한다는 가정하에)

- php

$temp = "=?ks_c_5601-1987?b?".base64_encode($temp)."?=";

여기서 인코딩으로 선택한 ks_c_5601-1987 는 ecu-kr 로 대체해도 무방하나, euc-kr 은 완성형 한글 이여서 완성형 한글이 아닌경우 깨져 보이고,
ks_c_5601-1987 의 경우 모질라계열 브라우저에서 바탕체가 기본으로 선택되어 지므로 원하는 것으로 선택하여 설정한다.


대형 업체들 또한 깨지고 있다니 참... 우리가 얼마나 UTF-8 환경을 무시했는지 알수있겠다.
(검정색 네모 박스는 개인정보라 직접 가린겁니다)

사용자 삽입 이미지 사용자 삽입 이미지 사용자 삽입 이미지


옥션/KT/다음 모두에게 제안하기 코너에 상세한 내용을 적어 보냈다.. 과연 인정하고 수정해주실것인가 ㅋ 무시해주실것인가 ㅋ



------------------------------------------------------------------------------------------------------
옥션측의 답변이 먼저 왔다...2010-08-25
하지만 답변은 보낸 내용을 전혀 읽어보지도 않고 제목만 보고 답변을 다셨나;;
우리나라의 현실인가 싶어 씁쓸하다~
--[옥션측 답변 전문]------------------------------------------------------------------------------
고객님의 소중한 문의사항을 확인 후 도움을 드리고자 안내 드립니다.
 
수신 메일이 깨져보이는 현상은 한글 메일이 인코딩 설정되어 있지 않은  경우입니다. 
 
[브라우져]>[보기(V)]>[인코딩]을 [한글]로 설정해 주신 후 [새로고침]버튼을 눌러 주시기 바랍니다. 
 
위의 사항으로도  해결이 되지 않을 경우 아래 url 의 깨진파일 복구프로그램을 다운받아 설치해야 합니다.
 
 
http://nongae.gsnu.ac.kr/~gsnucc/pub/broken-mail/cvt8.exe
 
심려를 끼쳐드려 정말 죄송합니다. (_ _)
소중한 고객님의 불편사항을 밑바탕으로 하여 보다 만족스러운 사이트가 될 수 있도록 최선의 노력을 다하겠습니다.

항상 신속하고 성실한 답변으로 최선을 다하겠습니다.
감사합니다.
------------------------------------------------------------------------------------------------------

'프로그래밍' 카테고리의 다른 글

Linux 및 Windows 환경을 위한 PHP, Oracle 10g Instant Client 설치  (0) 2010.09.27
Windows Script Host  (0) 2009.09.18
FCKeditor JavaScript API  (0) 2009.06.10

 

 

* Windows Script Host Object Model *


[WScript]

┣<WshShell>
┃ ┃
┃ ┠ WshShortcut
┃ ┃
┃ ┠ WshUrlShortcut
┃ ┃
┃ ┠ WshEnvironment
┃ ┃
┃ ┠ WshSpecialFolders
┃ ┃
┃ ┖ WshScriptExec


┣<WshArguments>
┃  ┃
┃  ┠ WshNamed
┃  ┃
┃  ┖ WshUnnamed


┣<WshController>
┃  ┃
┃  ┠ WshRemote
┃  ┃
┃  ┖ WshRemoteError


┗<WshNetwork>


* WSH Objects *

WSH 관련 작업은 한마디로 개체(object)를 생성하여 그 개체에서 사용가능한

Method 와 Property를 이용하는 것이라고 할 수 있다.

따라서 작업을 하려면 먼저 개체를 생성해야 하고, 가장 상위의 4개 개체는

주개체(Main Object)인 Wscript 개체를 통해 생성된다.

주개체는 기본적으로 생성되는 것으로 따로 생성하고 할 필요가 없다.

(다른 스크립트들과는 달리 WSH에서는 개체의 종류와 생성방법 등이 몇 개로 특정되어 있어

사용하기가 편하다.)

개체도 변수의 일종이므로 개체 생성방법 역시 변수처럼 Dim 으로 변수 선언 후 해당 변수에

CreateObject 로 할당하면 된다.

다만 개체는 변수가 개체변수라는걸 알리기위해 앞에 Set 을 해준다.

 

Wscript

   WSH의 메인 개체(오브젝트)

WshShell
   Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")

WshShortcut
   Dim Link : Set Link = WshShell.CreateShortcut(DeskTop & "\test.lnk")
WshSpecialfolders
   Access any of the Windows Special Folders

   Dim DeskTop : DeskTop = WshShell.SpecialFolders("Desktop") ' or AllUsersDesktop

WshURLShortcut
   Dim URL : Set URL = WshShell.CreateShortcut(DeskTop & "\Go Naver.url")
WshEnvironment
   Dim WshEnv : Set WshEnv = WshShell.Environment("Process")
WshScriptExec
   Dim oExec : Set oExec = WshShell.Exec("calc")
WshArguments
   Dim objArgs : Set objArgs = WScript.Arguments
WshNamed
WshUnnamed
WshNetwork
   Dim Net : Set Net = WScript.CreateObject ("WScript.Network")

WshController
   Dim Controller : Set Controller = WScript.CreateObject("WSHController")

WshRemote
WshRemoteError

 

메인 오브젝트(WScript)의 하위 오브젝트들인 WshShell,WshArguments,WshNetwork,

WshController,WshRemote 등은 메인 오브젝트(WScript)의 method 인 CreateObject 를

통해 생성되고, 각 오브젝트의 하위 오브젝트는 각 오브젝트에서 사용 가능한 적절한

method와 property 의 사용을 통해 생성된다.

 

- WScript : Windows 용

- CScript : cmd 용

 

* CScript 명령줄 사용예 *

 

CScript [host options...][script name][options and parameters]
CScript //nologo C:\Scripts\Qbackup.vbs
 

//?

 

//I               ;  Interactive mode(default). (대화창이나 에러메시지가 윈도에 표시된다)

//B              ;  Batch mode. ( 대화창이나 에러 메시지가 모두 프롬프트창에 표시된다.)


//T:nn          ; 타임아웃(일정시간이 지나면 스크립트 실행 중지. 초단위. 기본값은 무제한)


//NOLOGO   ; 배너 표시안함(기본값은 표시 ->  //LOGO )


//H:CScript   ; CScript.exe 를 스크립트 실행을 위한 기본 호스트로 지정.
//H:WScript   ; WScript.exe 를 스크립트 실행을 위한 기본 호스트로 지정.

; WSH의 기본 스크립트는 레지스트리값을 통해 확인할 수 있다.

; => HKEY_CURRENT_USER\Software\Microsoft\Windows Scripting Host\Settings


//S              ; Current User를 위해 현재 명령줄 옵션을 저장.

//E:engine   ; 스크립트를 지정된 스크립트엔진으로 실행.

                    (파일확장자가 달라도 스크립트 실행이 가능)
//D             ; 디버깅 중지.
//X             ; 디버깅하면서 스크립트 실행.
//JOB:<JobID>   ; .wsf 파일의 특정 JobID 를 실행.
//U             ; Enables you to use Unicode for redirected input/output (I/O) from the console.


- Object와 각 Object에 따른 Property -

 

* WScript object's Properties *


WScript.Name             '  Windows Script Host
WScript.FullName        '  C:\WINDOWS\System32\wscript.exe
WScript.Version           '  5.6
WScript.BuildVersion    '  8827
WScript.Path                '  CScript.exe or WScript.exe 파일의 경로 -> C:\WINDOWS\system32
WScript.ScriptFullName   '  현재 실행중인 파일의 full path & name -> C:\TEMP\test.vbs
WScript.ScriptName        '  현재 실행중인 파일의 이름 -> test.vbs

WScript.Interactive     ' 모드(interactive or batch) 표시. -> 1  or True

WScript.Interactive = False ' 배치모드로 전환된다.


WScript.StdErr
WScript.StdIn
WScript.StdOut

cf, StdIn, StdOut, and StdErr streams 는 CScript.exe 를 통해서만 액세스할 수 있다.


WScript.Arguments

WScript.Arguments.Named

WScript.Arguments.Unnamed

WScript.Arguments.Named.Item(이름)

WScript.Arguments.Unnamed.Item(순서)

 

myScript.vbs /c:arg1 /d:arg2

WScript.Arguments.Named.Item("c")   ' ->  arg1

myScript.vbs arg1 arg2

WScript.Arguments.Unnamed.Item(0)   ' ->  arg1  (zero-based index )

 

WScript Object는 기본적으로 생성되는 Object이므로 각 속성들 또한 아무곳에서나 사용가능..

 

* Shortcut object's Properties *

Shortcut Object는 WshShell Object의 CreateShortcut 메서드를 이용해 생성

Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")
Dim Desktop : Desktop = WshShell.SpecialFolders("Desktop")
Dim objLink : Set objLink = WshShell.CreateShortcut(Desktop & "\ScriptsFolder.lnk")

objLink.TargetPath = WScript.ScriptFullName
objLink.RelativePath = "C:\Scripts\"
objLink.WindowStyle = 1                   ' 1  ->  Activates and displays a window
objLink.Hotkey = "Ctrl+Alt+C"
objLink.IconLocation = "notepad.exe, 0"
objLink.Description = "Shortcut to Script Working Directory"
objLink.WorkingDirectory = Desktop
objLink.Arguments = "C:\myFile.txt"
objLink.Save
WScript.Echo objLink.FullName


* TextStream object's Properties *

FSO의 CreateTextFile, OpenTextFile, OpenAsTextStream 등의 Method를 이용해서 생성

AtEndOfLine

AtEndOfStream

Column

Line

Set FSO = CreateObject("Scripting.FileSystemObject")

Set f = FSO.OpenTextFile("c:\testfile.txt", ForReading)

do while f.AtEndOfStream <> True
    Wscript.Echo f.ReadLine
loop


* WshRemote object's Properties *


Dim Controller : Set Controller = WScript.CreateObject("WSHController")
Dim RemoteScript : Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
RemoteScript.Execute
Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

' Staus value :

' 0 : 원격스크립트 생성됨,but 아직 실행안됨

. 1 : 원격스크립트 실행중

' 2 : 원격스크립트 실행 끝남


* WshRemoteError object's Properties *


Dim RemoteError : Set RemoteError = RemoteScript.Error

RemoteError.Number
RemoteError.Line
RemoteError.Character
RemoteError.Description
RemoteError.Source
RemoteError.SourceText


* WshShell object's Properties *


Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo WshShell.CurrentDirectory       '  C:\Temp


Dim WshEnv : Set WshEnv = WshShell.Environment("PROCESS")

WScript.Echo WshEnv("NUMBER_OF_PROCESSORS")


NUMBER_OF_PROCESSORS
PROCESSOR_ARCHITECTURE
PROCESSOR_IDENTIFIER
PROCESSOR_LEVEL
PROCESSOR_REVISION
OS
COMSPEC
HOMEDRIVE
HOMEPATH
PATH
PATHEXT
PROMPT
SYSTEMDRIVE
SYSTEMROOT
WINDIR
TEMP
TMP


Dim Desktop : Desktop = WshShell.SpecialFolders("Desktop")

AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop
Favorites
Fonts
MyDocuments
NetHood
PrintHood
Programs
Recent
SendTo
StartMenu
Startup
Templates


cf, Environment 나 SpecialFolders property 에 의해 반환되는 객체는 컬렉션 객체이다.

따라서 Itme , count (number of items) 등을 이용할 수 있다.


WScript.Echo WshShell.SpecialFolders.Item("Programs")
' ->  C:\Documents and Settings\USER_ID\시작 메뉴\프로그램


* WshScriptExec object's Properties *

 

Dim oExec : Set oExec = WshShell.Exec("%comspec% /c dire")

If oExec.ExitCode <> 0 Then
     WScript.Echo "Warning: Non-zero exit code"
End If

' ExitCode : 대상 프로그램이 끝나지 않았으면 0, 끝나면 프로그램에서 반환된 값

 

* WshNetwork object's Properties *

 

Dim Net : Set Net = WScript.CreateObject("WScript.Network")
WScript.Echo "Domain = " & Net.UserDomain
WScript.Echo "Computer Name = " & Net.ComputerName
WScript.Echo "User Name = " & Net.UserName

 

 

Object의 종류와 그에 따른 속성들이 몇 개 안되므로 사용하기 편하다.


* WSH Methods index *

 

각 Method 에 대한 자세한 설명은 이 후 예문이 나올 때..


AddPrinterConnection
AddWindowsPrinterConnection
AppActivate
Close
ConnectObject
Count
CreateObject
CreateScript
CreateShortcut
DisconnectObject
Echo
EnumNetworkDrives
EnumPrinterConnections
Exec
Execute
Exists
ExpandEnvironmentStrings
GetObject
getResource
LogEvent
MapNetworkDrive
Popup
Quit
Read
ReadAll
ReadLine
RegDelete
RegRead
RegWrite
Remove
RemoveNetworkDrive
RemovePrinterConnection
Run
Save
SendKeys
SetDefaultPrinter
ShowUsage
Sign
SignFile
Skip
SkipLine
Sleep
Terminate  (WshScriptExec)
Verify
VerifyFile
Write
WriteBlankLines
WriteLine


아래 상수들은 VBScript에 들어 있으므로 사용하기 전에 정의하지 않아도 된다.

(Value 입력시 Value 대신 Constant 를 바로 사용가능하다는 뜻)

단, MsgBox 반환값은 코드에 명시적으로 상수로 선언해야 사용 가능.

* String Constants *

Constant     Value           Description
vbCr           Chr(13)        캐리지 리턴 (Carriage return)
vbLf            Chr(10)        라인 피드 (linefeed)
vbCrLf         Chr(13) & Chr(10)    캐리지 리턴-라인 피드 조합

vbNewLine  Chr(13) & Chr(10) 또는 Chr(10) 각 플랫폼 특정의 줄 바꿈 문자
vbNullChar   Chr(0)          값이 0인 문자 (Character having the value 0)
vbNullString  값이 0인 문자열.       길이가 0인 문자열("")과 다르며, 외부 프로시저 호출에 사용.
vbTab          Chr(9)        수평 탭 (Horizontal tab)

vbFormFeed    Chr(12)    폼 피드. Microsoft Windows에서는 사용되지 않습니다.
vbVerticalTab  Chr(11)    수직 탭. Microsoft Windows에서는 사용되지 않습니다.

* space(11) : 빈칸 11 개

* 줄바꿈 :
캐리지 리턴 Chr(13), 라인 피드 문자 Chr(10) 또는

캐리지 리턴-라인 피드 문자의 조합 Chr(13) & Chr(10) 을 사용하여 줄을 구분할 수 있다.
Msgbox "첫째 줄입니다. " & Chr(13) & Chr(10) & "둘째 줄입니다"

* 쌍따옴표(double quotation marks) 넣기 : Chr(34) 로 감싸기 or 쌍따옴표 두쌍으로 감싸기
내 이름은 "김팔봉"   ->  "내이름은 " & Chr(34) & "김팔봉" & Chr(34)
내 이름은 "김팔봉"   ->  "내이름은 " & """김팔봉"""

============================

* Tristate Constants *

Constant       Value  Description

vbUseDefault   -2     Use default from computer's regional settings.
vbTrue            -1     True
vbFalse           0      False

============================

* Color Constants *

Constant      Value        Description

vbBlack        &h00         Black
vbRed          &hFF         Red
vbGreen       &hFF00      Green
vbYellow      &hFFFF     Yellow
vbBlue         &hFF0000   Blue
vbMagenta   &hFF00FF   Magenta
vbCyan        &hFFFF00   Cyan
vbWhite        &hFFFFFF  White

============================

* Date and Time Constants *

Constant      Value  Description
vbSunday        1     Sunday
vbMonday       2     Monday
vbTuesday      3     Tuesday
vbWednesday  4     Wednesday
vbThursday     5     Thursday
vbFriday          6     Friday
vbSaturday      7     Saturday

vbUseSystemDayOfWeek 0

Use the day of the week specified in your system settings for the first day of the week.
vbFirstJan1        1  Use the week in which January 1 occurs (default).
vbFirstFourDays 2  Use the first week that has at least four days in the new year.
vbFirstFullWeek  3  Use the first full week of the year.

============================

* Date Format Constants *

Constant      Value  Description
vbGeneralDate  0  Display a date and/or time. ..determined by user system settings.
vbLongDate      1  long date format (specified in user computer's regional settings).
vbShortDate     2  short date format (specified in user computer's regional settings).
vbLongTime     3  long time format (specified in user computer's regional settings).
vbShortTime     4  short time format (specified in user computer's regional settings).

============================

* VarType Constants *

Constant     Value   Description

vbEmpty           0     Uninitialized (default)
vbNull              1     Contains no valid data
vbInteger          2     Integer subtype
vbLong            3     Long subtype
vbSingle          4     Single subtype
vbSingle          5     Double subtype
vbCurrency      6     Currency subtype
vbDate            7      Date subtype
vbString           8     String subtype
vbObject          9     Object
vbError           10     Error subtype
vbBoolean      11     Boolean subtype
vbVariant       12     Variant (used only for arrays of variants)
vbDataObject  13     Data access object
vbDecimal      14     Decimal subtype
vbByte           17     Byte subtype
vbArray       8192     Array

============================

* MsgBox Constants *

Constant              Value   Description
vbOKOnly                 0      Display OK button only.
vbOKCancel             1      Display OK and Cancel buttons.
vbAbortRetryIgnore    2      Display Abort, Retry, and Ignore buttons.
vbYesNoCancel        3      Display Yes, No, and Cancel buttons.
vbYesNo                  4      Display Yes and No buttons.
vbRetryCancel          5      Display Retry and Cancel buttons.
vbCritical                16      Display Critical Message icon.
vbQuestion             32      Display Warning Query icon.
vbExclamation         48      Display Warning Message icon.
vbInformation           64      Display Information Message icon.
vbDefaultButton1        0      First button is the default.
vbDefaultButton2     256      Second button is the default.
vbDefaultButton3     512      Third button is the default.
vbDefaultButton4     768      Fourth button is the default.
vbApplicationModal   0      Application modal.(응답해야 현재 프로그램 계속 실행 가능 )
vbSystemModal     4096     System modal.

cf, 조합이 가능하다

두개버튼(Yes,No) + 물음표 아이콘 + 선택커스의 기본위치가 두번째버튼(No) 인 경우

=> MsgBox "예,아니오 중 선택하세요", vbYesNo + vbQuestion + vbDefaultButton2

=> MsgBox "예,아니오 중 선택하세요", 4 + 32 + 256

=> MsgBox "예,아니오 중 선택하세요", 292


<반환값>

Constant  Value  Description

vbOK          1      OK button was clicked.
vbCancel    2      Cancel button was clicked.
vbAbort       3      Abort button was clicked.
vbRetry       4      Retry button was clicked.
vbIgnore     5      Ignore button was clicked.
vbYes        6      Yes button was clicked.
vbNo          7      No button was clicked.

cf, VBScript 에서 응답값(반환값)은 명시적으로 선언해야 문자열을 상수값으로 사용할 수 있다.

 

intButton = object.Popup (strText,[nSecondsToWait],[strTitle],[nType])

' [] 로 둘러싸인 부분은 옵션이다. (있어도 그만, 없어도 그만)
' cf. 반환값 없이 단독으로 쓰일 때는 괄호를 사용할 수 없다.
' Shell.Popup("안녕하세요", 0, "Hello", vbOkOnly)      =>   괄호로 둘러싸면 에러남..  


   - object : WshShell object.

   - strText : 메시지.

   - nSecondsToWait : Optional. 응답 기다릴 시간(second). (생략시 기본값은 0 ,무한정 기다림)
     지정되고 nSecond 동안 응답 없으면..  -> 메시지박스 사라지면서 -1 을 반환한다.

   - strTitle : Optional. 메시지박스 타이틀바에 나타낼 제목.(생략시 "Windows Script Host" )

   - nType : Optional. 버튼과 아이콘 타입.( 생략시 버튼타입은 0 -> vbOkOnly )

   - IntButton : 메시지박스 버튼 클릭시 반환되는 정수값.

=====================================================

 intButton = MsgBox (prompt [, button][, title][, helpfile, context])

 

   - title : 대화 상자의 제목 표시줄에 나타나는 문자식. (생략시 응용 프로그램 이름이 나타남)

   - helpfile, context : 대화상자에 도움말 제공하기위한 도움말 파일들.

      helpfile 이 지정되었다면 context 도 지정되어야 한다.(16bit 에서 사용불가)

 =====================================================

strReturn = InputBox ( prompt[, [title], [default], [xpos], [ypos]])


   - cf, 취소 버튼을 클릭하면 zero-length string("") 이 반환된다.

   - MsgBox, InputBox : VBScript 도구로 객체(object) 생성없이 단독으로 바로바로 사용 가능.

=====================================================

 

* Button Types *
Value     Description                             Constants
0           OK                                          vbOkOnly
1           OK, Cancel                              vbOkCancel
2           Abort, Retry, Ignore                   vbAbortRetryIgNore
3           Yes, No, Cancel                       vbYesNoCancel
4           Yes, No                                   vbYesNo
5           Retry, Cancel                           vbRetryCancel


* Icon Types *
Value      Description                              Constants
16          Show "Stop Mark" icon.              vbCritical
32          Show "Question Mark" icon.        vbQuestion
48          Show "Exclamation Mark" icon.   vbExclamation
64          Show "Information Mark" icon.     vbInformation


* Return value *
Value       Description
-1  <-       timeout(응답시간내 응답 없으면 반환되는 값)
1    <-       OK
2    <-       Cancel
3    <-       Abort
4    <-       Retry
5    <-       Ignore
6    <-       Yes
7    <-       No

cf, 반환값 상수는 명시적으로 상수로 선언해야 사용 가능.


 

>예문 보기

>접기


Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")

Return = WshShell.RegRead(strRegName)

Return = WshShell.RegRead("HKCU\Software\Microsoft\Notepad\lfFaceName")  ' 굴림
Return = WshShell.RegRead("HKCU\Software\Winamp\") ' C:\Program Files\Winamp
Return = WshShell.RegRead("HKCU\Software\WinRAR\") ' 기본값 없어서 에러 발생.

- strRegName : key or value-name

 

' strRegName의 루트키 약자
    HKEY_CURRENT_USER         :   HKCU 
    HKEY_LOCAL_MACHINE       :   HKLM 
    HKEY_CLASSES_ROOT         :   HKCR 
    HKEY_USERS                       :   HKEY_USERS
    HKEY_CURRENT_CONFIG      :   HKEY_CURRENT_CONFIG

 

' 레지스트 경로의 마지막에 백슬래시 \ 가 있으면 키, 없으면 값의 이름을 가리킨다. 

' 키나 값이 존재하지 않을 경우, 값이 바이너리값인 경우 -> 에러 발생.

' 키의 default value 가 존재하지 않을 경우 -> 에러 발생.
' REG_SZ 값은 String 을 읽어온다.
' REG_DWORD 값은 dword 값이 아닌 실제 정수값을 읽어온다.
' REG_BINARY 값은 읽지 못한다. (에러 발생)
' REG_EXPAND_SZ 값은 String 문자열 그대로 읽어온다.
=========================================================

WshShell.RegWrite strRegName, anyValue [, strType]

- strRegName : key or value-name

' 키    추가 : strRegName에 \ 를 붙여준다.
' 이름 추가 : strRegName에 \ 를 붙이지 않음.
' strRegName에 \ 붙이고 Value 가 공백(zero-length string) 이면 빈 새 키가 생성된다

- anyValue
' value에 Dword 값 입력시에는 dowrd값이 아닌 실제 정수(십진수)로 입력해야 함.
' value에 쌍따옴표 포함된 String 입력시 다시 쌍따옴표로 감싸주거나 Chr(34) 를 이용한다.
' value에 경로문자 \가 포함된 String 입력시 \ 는 \\ 로 바꿔 입력할 필요가 없다.
' value에 환경변수 포함된 String 입력하면 변환된 값이 아닌 환경변수 문자열 그대로 입력된다.

- strType (Registry Data Type)
REG_SZ               : 문자열 (String)
REG_DWORD        : 정수 (Integer)
REG_EXPAND_SZ : 문자열 ( %comspec% 등과 같은 환경 변수를 포함하는 경우)
REG_BINARY        : 이진 문자열

' 값의 형식 지정하지 않으면 REG_SZ 로 인식
' REG_MULTI_SZ 값 입력은 지원되지 않음.


WshShell.RegWrite "HKCU\Software\AAA\", ""   ' 빈 새키 생성

WshShell.RegWrite "HKLM\...\ValName", 1000, "REG_DWORD" ' dword:000003e8 입력시

WshShell.RegWrite "HKCU\..", """%ProgramFiles%\..""", "REG_EXPAND_SZ"


Dim WshEnv : Set WshEnv = WshShell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
WshShell.RegWrite "HKCU\..", Chr(34) & ProgramDir & "\some.txt" & Chr(34), "REG_SZ"

' REG_EXPAND_SZ타입은 %~%를 문자열 그대로 입력.

' 맞는 값으로 변환시켜 입력하려면 Environment 등을 이용하여 값을 얻어 입력해야 함.

=========================================================

WshShell.RegDelete strRegName

- strName : key or value-name

WshShell.RegDelete "HKCU\MyNewKey\"                ' 키    삭제 : 맨 뒤에 \ 를 붙여준다
WshShell.RegDelete "HKCU\MyNewKey\MyValue"    ' 이름 삭제 : 맨 뒤에 \ 를 붙이지 않음


 예문)

Dim WshShell : WshSet Shell = createobject ("wscript.shell")
Const vbYes = 6
Dim p : p = WshShell.Popup ("would you like to GO ON?:  ", 5, "go on qestion", vbYesNo+vbQuestion)

If p = vbYes Then
    MsgBox "ok"
Else
    set p = nothing
    Wscript.Quit
End If

 

Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")
Dim BtnCode : BtnCode = WshShell.Popup("Do you feel alright ?", 7, "Answer This Question:", 4 + 32)

Select Case BtnCode
   case 6   WScript.Echo "Glad to hear you feel alright."
   case 7   WScript.Echo "Hope you're feeling better soon."
   case -1  WScript.Echo "Is there anybody out there?"
End Select

 

Dim MyVar : MyVar = MsgBox ("안녕하십니까?", 65, "메시지 상자 예제")

' vbOKCancel(1) + vbInformation(64) = 65

 

Dim strReturn : strReturn = InputBox ("What is the sum of 1 + 5 * 9 / 3 ?  ", "The Math Game")
Dim TrimReturn : TrimReturn = Trim(strReturn)
If Len(TrimReturn) = 0 Then
    MsgBox "Sorry. You must enter a number to play this game."
    WScript.Quit
End If

If IsNumeric(TrimReturn) <> True Then
    MsgBox "Sorry. You must enter a number to play this game."
    WScript.Quit
End If

 

// JScript
var WshShell = WScript.CreateObject("WScript.Shell");
var BtnCode = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32);
switch(BtnCode) {
   case 6:
      WScript.Echo("Glad to hear you feel alright.");
      break;
   case 7:
      WScript.Echo("Hope you're feeling better soon.");
      break;
   case -1:
      WScript.Echo("Is there anybody out there?");
      break;
}

 

Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")

Return = WshShell.RegRead(strRegName)

Return = WshShell.RegRead("HKCU\Software\Microsoft\Notepad\lfFaceName")  ' 굴림
Return = WshShell.RegRead("HKCU\Software\Winamp\") ' C:\Program Files\Winamp
Return = WshShell.RegRead("HKCU\Software\WinRAR\") ' 기본값 없어서 에러 발생.

- strRegName : key or value-name

 

' strRegName의 루트키 약자
    HKEY_CURRENT_USER         :   HKCU 
    HKEY_LOCAL_MACHINE       :   HKLM 
    HKEY_CLASSES_ROOT         :   HKCR 
    HKEY_USERS                       :   HKEY_USERS
    HKEY_CURRENT_CONFIG      :   HKEY_CURRENT_CONFIG

 

' 레지스트 경로의 마지막에 백슬래시 \ 가 있으면 키, 없으면 값의 이름을 가리킨다. 

' 키나 값이 존재하지 않을 경우, 값이 바이너리값인 경우 -> 에러 발생.

' 키의 default value 가 존재하지 않을 경우 -> 에러 발생.
' REG_SZ 값은 String 을 읽어온다.
' REG_DWORD 값은 dword 값이 아닌 실제 정수값을 읽어온다.
' REG_BINARY 값은 읽지 못한다. (에러 발생)
' REG_EXPAND_SZ 값은 String 문자열 그대로 읽어온다.
=========================================================

WshShell.RegWrite strRegName, anyValue [, strType]

- strRegName : key or value-name

' 키    추가 : strRegName에 \ 를 붙여준다.
' 이름 추가 : strRegName에 \ 를 붙이지 않음.
' strRegName에 \ 붙이고 Value 가 공백(zero-length string) 이면 빈 새 키가 생성된다

- anyValue
' value에 Dword 값 입력시에는 dowrd값이 아닌 실제 정수(십진수)로 입력해야 함.
' value에 쌍따옴표 포함된 String 입력시 다시 쌍따옴표로 감싸주거나 Chr(34) 를 이용한다.
' value에 경로문자 \가 포함된 String 입력시 \ 는 \\ 로 바꿔 입력할 필요가 없다.
' value에 환경변수 포함된 String 입력하면 변환된 값이 아닌 환경변수 문자열 그대로 입력된다.

- strType (Registry Data Type)
REG_SZ               : 문자열 (String)
REG_DWORD        : 정수 (Integer)
REG_EXPAND_SZ : 문자열 ( %comspec% 등과 같은 환경 변수를 포함하는 경우)
REG_BINARY        : 이진 문자열

' 값의 형식 지정하지 않으면 REG_SZ 로 인식
' REG_MULTI_SZ 값 입력은 지원되지 않음.


WshShell.RegWrite "HKCU\Software\AAA\", ""   ' 빈 새키 생성

WshShell.RegWrite "HKLM\...\ValName", 1000, "REG_DWORD" ' dword:000003e8 입력시

WshShell.RegWrite "HKCU\..", """%ProgramFiles%\..""", "REG_EXPAND_SZ"


Dim WshEnv : Set WshEnv = WshShell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
WshShell.RegWrite "HKCU\..", Chr(34) & ProgramDir & "\some.txt" & Chr(34), "REG_SZ"

' REG_EXPAND_SZ타입은 %~%를 문자열 그대로 입력.

' 맞는 값으로 변환시켜 입력하려면 Environment 등을 이용하여 값을 얻어 입력해야 함.

=========================================================

WshShell.RegDelete strRegName

- strName : key or value-name

WshShell.RegDelete "HKCU\MyNewKey\"                ' 키    삭제 : 맨 뒤에 \ 를 붙여준다
WshShell.RegDelete "HKCU\MyNewKey\MyValue"    ' 이름 삭제 : 맨 뒤에 \ 를 붙이지 않음

 

' 레지스트리 읽어서 .reg 파일로 저장
Set WshShell = CreateObject("WScript.Shell")
sKey = "HKEY_CURRENT_USER\Software\Microsoft\Notepad"

fName = "c:\TEMP\FirstPage.reg"
sCmd = "regedit /e/a " & Chr(34) & fName & Chr(34) & " " & Chr(34) & sKey & Chr(34)
WshShell.Run "%comspec% /c " & sCmd, 0, True

Set WshShell = Nothing
'================================================================
' 레지스트리 파일 읽어서 Program Files 경로 변경 후 병합하기

Option Explicit

'On Error Resume Next
'Err.Clear


Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
Dim ProgramDir : ProgramDir = Shell.Environment("Process").Item("ProgramFiles")


Const FindLong = "C:\\Program Files"
Const FindShort = "C:\\PROGRA~1"


Dim ProgArray, ProgLong, ProgShort
ProgArray = Split (ProgramDir, "\")
ProgLong = ProgArray(1)
ProgShort = ProgArray(1)


If Len(ProgLong) > 8 Then
    ProgShort = Left(ProgLong, 6) & "~1"    ' PROGRA~1
End If


Dim RepLong : RepLong = ProgArray(0) & "\\" & ProgLong
Dim RepShort : RepShort = ProgArray(0) & "\\" & ProgShort
' 레지파일의 경로 구분자는 \가 아닌 \\


Dim RegFile : RegFile = "install.reg"
Dim ts, strLine, newLine
Dim newReg : newReg = ""


If FSO.FileExists(RegFile) Then
    Set ts = FSO.OpenTextFile(RegFile, 1)  ' 1 => ForReading
    Do Until ts.AtEndOfStream
        strLine = ts.ReadLine
        newLine = Replace(strLine, FindLong, RepLong, 1, -1, 1)
        newLine = Replace(newLine, FindShort, RepShort, 1, -1, 1)
        newReg = newReg & newLine & vbCrLf
    Loop
    ts.Close

    Dim fTmp : fTmp = FSO.GetAbsolutePathName(FSO.GetTempName)
    FSO.CreateTextFile(fTmp)
    Dim getTmp : Set getTmp = FSO.GetFile(fTmp)
    Dim tsTmp : Set tsTmp = getTmp.OpenAsTextStream(2, True)  ' Const ForWriting = 2
    tsTmp.Write(newReg): tsTmp.Close
    Shell.Run "%COMSPEC% /C regedit /s " & Chr(34) & fTmp & Chr(34), 0, True
    FSO.DeleteFile fTmp, True
End If


Set Shell = Nothing
Set FSO = Nothing

WScript.Quit

'================================================================

' 프로그램 설치되었는지 여부 검사하기

Set WshShell = CreateObject("WScript.Shell")
If WshShell.RegRead("HKCR\.BMP\\") = "ACDC_BMP" Then
   WScript.Echo "ACDSee installed."
Else
   WScript.Echo "You can install ACDSee."
End If
           
Set WshShell = Nothing



- [Method] SendKeys

Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys string[, wait]

string   : 필수. 입력된 문자식을 보냅니다.
Wait   : 선택. 부울 값은 대기 모드로 지정합니다.
  False (기본값)이면 키가 입력이 되면 컨트롤은 바로 프로시저에 반환됩니다.
  True 이면 프로시저에게 컨트롤이 반환되기 전에 반드시 키가 입력되어야 합니다.

--------------------------------------------------------------------------


* 문자 입력 : 그 문자 자체를 표시.
    예) ABC   => "ABC"


* 기호 문자 입력 : 중괄호({})로 묶어준다.
    예) 덧셈 기호를 입력   =>  {+}

    더하기 기호   plus sign           +
    삽입 기호      caret                 ^
    퍼센트 기호   percent sign      %
    생략 기호      and tilde            ~
    괄호                                    ( )


 cf, 대괄호([ ]) :  대괄호는 그냥 입력이 가능하지만, 다른 응용프로그램에서 특수하게

                        인식될수 있으므로 중괄호로 묶어준다.
                        [  =>  {{}         ] => {}}


* 특수 키 입력
키                               코드
백스페이스                   {BACKSPACE}, {BS} 또는 {BKSP}
Break                          {BREAK}
Caps Lock                   {CAPSLOCK}
Del 또는 Delete             {DELETE} 또는 {DEL}
아래쪽 화살표               {DOWN}
End                             {END}
Enter                           {ENTER} 또는 ~
Esc                             {ESC}
Help                            {HELP}
Home                          {HOME}
Ins 또는 Insert              {INSERT} 또는 {INS}
왼쪽 화살표                  {LEFT}
Num Lock                    {NUMLOCK}
Page Down                 {PGDN}
Page Up                     {PGUP}
Print Screen                {PRTSC}
오른쪽 화살표              {RIGHT}
Scroll Lock                 {SCROLLLOCK}
Tab                            {TAB}
위쪽 화살표                 {UP}
F1      {F1}
F2      {F2}
F3      {F3}
F4      {F4}
F5      {F5}
F6      {F6}
F7      {F7}
F8      {F8}
F9      {F9}
F10    {F10}
F11    {F11}
F12    {F12}
F13    {F13}
F14    {F14}
F15    {F15}
F16    {F16}


* Shift,Ctrl,Alt 와 일반 키를 동시에 누를 경우 : 아래 문자를 입력할 키 앞에 붙여준다.

     Shift    +
     Ctrl     ^
     Alt      %

 조합키 누른채 다른 여러 키를 입력해야 한다면 여러 키들을 괄호로 묶어준다.
     Shift + ( E + C...)        =>      "+(ec)"
     (Shift +  E)  + C          =>      "+ec"

     Alt + F4                     =>      "%{F4}"

* 키 반복 입력 : 반복되는 키를 지정할 때는 {keystroke number}의 형식으로 나타낸다.

  (키와 숫자 사이에 반드시 공백 필요)
   
    왼쪽 화살표키를 42회 입력    =>   {LEFT 42}
    H를 10 번 입력                    =>   {h 10}

    Ctrl+X 를 10번 입력하는 식으로 특수키와 일반키의 조합을 여러번 입력하는건 안된다.

        alt + ctrl + del  => Shell.Sendkeys("%^{DEL}") x
                                 Shell.Sendkeys("%^+{DEL}") o


* 참고 *
Microsoft Windows 내에서 실행되지 않는 응용 프로그램에 SendKeys를 사용하여 키를

입력할 수 없다.
Sendkeys는 또한 PRINT SCREEN key {PRTSC} 를 다른 응용 프로그램에 보낼 수 없다.




-  [Method] Run, Exec

Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
intError = WshShell.Run (strCommand [, intWindowStyle] [, bWaitOnReturn])


WshShell.Run "%windir%\notepad" & WScript.ScriptFullName

' cf, 반환값 없이 단독 실행시에는 괄호로 묶지 않는다.


intError = WshShell.Run("notepad " & WScript.ScriptFullName, 1, True)
intError = WshShell.Run ("setup.exe", 1, true)


- object : WshShell object.
- strCommand : String value indicating the command line you want to run.
- intWindowStyle : Optional. Integer value indicating the appearance of the program's window.


* intWindowStyle :
0    Hides the window and activates another window.
1    Activates and displays a window.

     If the window is minimized or maximized, the system restores it to its original size and position.
     An application should specify this flag when displaying the window for the first time.
2   Activates the window and displays it as a minimized window.  
3   Activates the window and displays it as a maximized window.  
4   Displays a window in its most recent size and position.

     The active window remains active.
5   Activates the window and displays it in its current size and position.
6   Minimizes the specified window and activates the next top-level window in the Z order.
7   Displays the window as a minimized window. The active window remains active.
8   Displays the window in its current state. The active window remains active.
9   Activates and displays the window.

    If the window is minimized or maximized, the system restores it to its original size and position.
     An application should specify this flag when restoring a minimized window.
10  Sets the show-state based on the state of the program that started the application.


- bWaitOnReturn : Optional. (true / false)

Boolean value indicating whether the script should wait for the program to finish executing
before continuing to the next statement in your script.
If set to true, script execution halts until the program finishes, and Run returns any error code returned by the program.
If set to false (the default), the Run method returns immediately after starting the program,
automatically returning 0 (not to be interpreted as an error code).

- intError : Error code ( integer ).

-----------------------------------------------------------------------------------

Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
Dim oExec : Set oExec = WshShell.Exec("calc")

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

WScript.Echo oExec.Status


' Status Return Values

'     0  : The job is still running.
'     1  : The job has completed.

-----------------------------------------------------------------------------------

' Run 과 Exec 의 가장 큰 차이

'=> Run 은 실행만 하지만, Exec는 실행과 동시에 객체(object)를 생성한다.

'    따라서 Exec를 통한 실행은 생성된 객체를 이용한 후속 작업이 용이하다.


Set FSO = Wscript.CreateObject("Scripting.FileSystemObject")
Set Shell = Wscript.CreateObject("Wscript.Shell")
TempName = FSO.GetTempName
TempFile = TempName

Shell.Run "cmd /c ping -n 3 -w 1000 157.59.0.1 >" & TempFile, 0, True

Set TextFile = FSO.OpenTextFile(TempFile, 1)
Do While TextFile.AtEndOfStream <> True
    strText = TextFile.ReadLine
    If Instr(strText, "Reply") > 0 Then
        Wscript.Echo "Reply received."
        Exit Do
    End If
Loop

TextFile.Close
FSO.DeleteFile(TempFile)


' 아래는 동일한 결과는 가지는 Exec 를 통한 실행이다.

' 실행을 통해 반환되는 StdOut 에 접근하기위해 임시파일 만들고 할 필요가 없다.


Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim ExecObject : Set ExecObject = Shell.Exec ("cmd /c ping -n 3 -w 1000 157.59.0.1")
Do While Not ExecObject.StdOut.AtEndOfStream
    strText = ExecObject.StdOut.ReadLine
Loop

 

 

 

-  [Method] Sign, SignFile, Verify, VerifyFile

Sign 
   Signs a script stored in a string.

SignFile 
   Signs a script using a digital signature.


Verify 
   Verifies a digital signature retrieved as a string.

VerifyFile 
   Verifies the digital signature encapsulated in a script.



-  [Method] CreateObject, GetObject

CreateObject 
   Creates an object specified by the strProgID parameter.


CreateScript 
   Creates a WshRemote object (an object that represents an instance of a script

   running in a remote process).


CreateShortcut
   Creates an object reference to a shortcut or URLshortcut.



ConnectObject
   Connects an object's event sources to functions with a given prefix.

 

DisconnectObject
   Disconnects a previously connected object from Windows Script Host.



GetObject
   Retrieves an Automation object from a file or an object specified by the strProgID parameter.



 [Method] MapNetworkDrive


MapNetworkDrive 
   Maps the share point specified by strRemoteName to the local resource name strLocalName.



EnumNetworkDrives 
   Returns the current network drive mappings.

EnumPrinterConnections
   Returns the current network printer mappings.



RemoveNetworkDrive 
   Removes the current resource connection denoted by strName.


RemovePrinterConnection 
   Removes the current resource connection denoted by strName.




AddPrinterConnection 
   Adds a DOS-style printer connection to your computer.


AddWindowsPrinterConnection 
   Adds a Windows-style printer connection to your computer.

SetDefaultPrinter 
   Sets the default printer to the remote printer specified.





-  [Method] ExpandEnvironmentStrings

* 환경변수값 알아내기 *

strReturn = WshShell.ExpandEnvironmentStrings(strString)
 
- strReturn : an environment variable's expanded value.
- strString : name of the environment variable.

- Remarks :
    The ExpandEnvironmentStrings method expands environment variables
    defined in the PROCESS environment space only.


'Visual Basic Script
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")
 

//JScript
var WshShell = WScript.CreateObject("WScript.Shell");
WScript.Echo("WinDir is " + WshShell.ExpandEnvironmentStrings("%WinDir%"));



* ReNamer.vbs *


입력 1. 대상 폴더 경로의 마지막에 \ 가 있으면 파일명 변경, 없으면 폴더명 변경.

입력 2. 찾을 단어, 바꿀 단어 를 입력받는다.

       - 쉼표로 구분

       - 바꿀 단어는 공백이 올 수 있다( = 특정 문자 제거)

       - 찾을 단어가 숫자 0 이라면 맨 앞 접두어 삽입으로 간주한다.


Option Explicit

'On Error Resume Next
'Err.Clear

Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = WScript.CreateObject("Scripting.FileSystemObject")

Dim TargetPath, fileMode


TargetPath = InputBox ("대상 폴더의 절대경로를 입력해 주세요." _
    & vbCrLf & "마지막에 \가 있으면 파일명 변경, " _
    & vbCrLf & "없으면 폴더명 변경입니다.  "  _
    & vbCrLf & vbCrLf & "예) C:\Temp  또는   C:\Temp\", "Parent Path")

' InputBox 는 Popup 과는 달리 오브젝트(WshShell)없이 단독으로 사용 가능.


Call CheckNull(TargetPath)
TargetPath = Trim(TargetPath)

 

' 기본은 폴더명 변경 , 경로 마지막에 \ 가 있으면 파일명 변경

' \ 가 붙은 경우, 대상 폴더의 경로를 얻기 위해 마지막 \ 는 제거해 줘야 한다.
fileMode = False
If Right(TargetPath, 1) = "\" Then
    TargetPath = Left(TargetPath, Len(TargetPath)-1) ' 마지막 \ 제거
    fileMode = True
End If

Call CheckRoot(TargetPath)

If fileMode = True Then
    Call RepFiles
Else
    Call RepFolders
End If


'[함수화]*******************************
Sub CheckRoot(s)
    If Trim(s) = "" Then ' 경로 입력 안했거나 취소버튼 누른 경우
        WScript.Quit
    ElseIf Len(s) <= 3 Then ' C  C:  C:\  등의 경우
        Shell.Popup "루터 디렉토리는 대상 폴더가 될 수 없습니다.  ", 3, "Path Error", vbOkOnly
        WScript.Quit
    ElseIf Not FSO.FolderExists(s) Then
        Shell.Popup "경로가 존재하지 않습니다.  ", 3, "Path Error", vbOkOnly
        WScript.Quit
    End If
End Sub
Sub CheckNull(s)
    If Trim(s) = "" Then
        Shell.Popup " 입력값 없음  ", 1, "Input Empty", vbOkOnly
        WScript.Quit
    End If
End Sub
Sub CheckRest(s)
    If InStr(1, s, ",", 1) <= 0 Then ' s 에서 쉼표가 위치한 곳(순서가 <= 0 는 말은 없다는 뜻)
        Shell.Popup "찾을 단어와 바꿀 단어를 쉼표로 구분하여 입력해 주세요.  ", 3, "Input Error", vbOkOnly
        WScript.Quit
    End If
End Sub

 

'[파일명 변경]***************************
Sub RepFiles
    Dim inputStr : inputStr = InputBox ("* 파일명 변경 *" & vbCrLf _
    & "찾을 단어와 바꿀 단어를 쉼표로 구분하여 입력해 주세요." & vbCrLf & vbCrLf _
    & "교체) target words, new words" & vbCrLf _
    & "삭제) target words," & vbCrLf _
    & "접두어 삽입) 0, insert words", "파일명 변경")
    Call CheckNull(inputStr)
    Call CheckRest(inputStr)
    Dim StrArray : StrArray = Split(inputStr, ",", -1, 1)  ' 쉼표로 구분(배열을 생성)
    Dim FindStr : FindStr = LTrim( StrArray(0) )  ' 단어 왼쪽 공백만 없앤다.
    Call CheckNull(FindStr)
    Dim RepStr : RepStr = LTrim( StrArray(1) ) ' 바꿀 단어는 Null Check 안함.

    Dim objFold : Set objFold = FSO.GetFolder(TargetPath)
    Dim fcoll : Set fcoll = objFold.Files

    ' Folder.files 와 Folder.subfolders는 콜렉션 객체를 생성한다.
    Dim f1, oName, nName, oPath, nPath
    For Each f1 in fcoll
        oName = f1.name  ' 하위 파일의 이름
        If IsNumeric(FindStr) Then ' 찾을 문자가 숫자 0 이면 접두어 삽입 모드
            nName = RepStr & oName
        Else
            nName = Replace(oName, FindStr, RepStr, 1, -1, 1)
        End If
        oPath = TargetPath & "\" & oName
        nPath = TargetPath & "\" & nName
        If Not FSO.FileExists(nPath) Then ' 같은 이름 있으면 변경 안함
            FSO.MoveFile oPath, nPath
        End If
    Next
    Set objFold = Nothing
    Set fcoll = Nothing
End Sub

 

'[폴더명 변경]***************************
Sub RepFolders

    Dim inputStr : inputStr = InputBox ("* 폴더명 변경 *" & vbCrLf _
    & "찾을 단어와 바꿀 단어를 쉼표로 구분하여 입력해 주세요." & vbCrLf & vbCrLf _
    & "교체) target words, new words" & vbCrLf _
    & "삭제) target words," & vbCrLf _
    & "접두어 삽입) 0, insert words", "폴더명 변경")
    Call CheckNull(inputStr)
    Call CheckRest(inputStr)

    Dim StrArray : StrArray = Split(inputStr, ",", -1, 1)  ' 쉼표로 구분(배열을 생성)
    Dim FindStr : FindStr = LTrim( StrArray(0) ) ' 단어 왼쪽 공백만 없앤다.
    Call CheckNull(FindStr)
    Dim RepStr : RepStr = LTrim( StrArray(1) )

    Dim objFold : Set objFold = FSO.GetFolder(TargetPath)
    Dim dcoll : Set dcoll = objFold.SubFolders
    Dim d1, oName, nName, oPath, nPath
    For Each d1 in dcoll
        oName = d1.name  ' 하위 폴더의 이름
        If IsNumeric(FindStr) Then
            nName = RepStr & oName
        Else
            nName = Replace(oName, FindStr, RepStr, 1, -1, 1)
        End If
        oPath = TargetPath & "\" & oName
        nPath = TargetPath & "\" & nName
        If Not FSO.FolderExists(nPath) Then ' 같은 이름 있으면 변경 안함
            FSO.MoveFolder oPath, nPath
        End If
    Next
    Set objFold = Nothing
    Set dcoll = Nothing
End Sub


Set Shell = Nothing
Set FSO = Nothing

WScript.Quit


WSH - ex) 코덱박사 슈퍼코덱팩 자동설치

* AutoInstall.vbs *


Option Explicit

On Error Resume Next  

Err.Clear


Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
Dim COMSPEC : COMSPEC = Shell.ExpandEnvironmentStrings("%COMSPEC%")

Dim ExeFile : ExeFile = "Super_20060524.exe"   ' 파일명 바꾸면 설치 에러남


If MsgBox ("코덱박사 슈퍼 코덱팩 v20060524 을 설치하시겠습니까?   " , 36, "Setup - SuperCodec") = 6 Then
 Shell.Run COMSPEC & " /c " & ExeFile & " & Exit", 0

 'cmd창 숨기고 설치창 활성화.  뒤에 ,true 붙이면 안됨
 Wscript.Sleep 3000
 Shell.AppActivate "코덱박사 슈퍼 코덱팩 v20060524"  '활성창 타이틀
 Wscript.Sleep 800
 Shell.SendKeys "~", True ' 엔터키

 Wscript.Sleep 1000
 Shell.SendKeys "~", True
 Wscript.Sleep 1000
 Shell.SendKeys "{TAB}", True
 Wscript.Sleep 500
 Shell.SendKeys "{right}", True
 Wscript.Sleep 500
 Shell.SendKeys "~", True

 Wscript.Sleep 1000
 Shell.SendKeys "~", True
 Wscript.Sleep 1000
 Shell.SendKeys "~", True
 Wscript.Sleep 1000

 Shell.SendKeys "{TAB}", True
 Wscript.Sleep 500
 Shell.SendKeys "{END}", True '맨아래칸 이동은 {down} 쓸 필요없이 바로 {END} 로..
 Wscript.Sleep 1000
 Shell.SendKeys " ", True ' PCClear는 설치요소에서 제거 ( " " -> 스페이스키)
 Wscript.Sleep 1000

 Shell.SendKeys "{TAB}", True
 Wscript.Sleep 500
 Shell.SendKeys "{right}", True
 Wscript.Sleep 500
 Shell.SendKeys "~", True

 Wscript.Sleep 1000
 Shell.SendKeys "~", True

 Wscript.Sleep 1000
 Shell.SendKeys "~", True

 Wscript.Sleep 3000

 Shell.SendKeys "~", True ' GomPlayer 발견 - 최적화할까요?  => yes

 ' GomPlayer , KMPlayer 등 미디어재생 소프트웨어를 먼저 설치해야 한다.
 Wscript.Sleep 3500
 Shell.SendKeys "~", True ' nomal
 Wscript.Sleep 1000
 Shell.SendKeys "~", True ' 2 channel
 Wscript.Sleep 1000
 Shell.SendKeys "~", True ' 환경설정

 ' Call DelStartup() ' 한글Windows에서는 하면 안됨...


Else
    Shell.Popup "코덱박사 슈퍼 코덱팩 v20060524 설치가 취소되었습니다.   ", 3, "Cancle", 48
    WScript.Quit
End if


' 영문Windows에는 "시작프로그램"이라는 폴더가 없다. ( Start Menu 가 있다 )

Sub DelStartup()

    Dim KorStartMenu : KorStartMenu = Shell.SpecialFolders("Programs") & "\시작프로그램"
    If FSO.FolderExists(KorStartMenu) Then
        FSO.DeleteFolder KorStartMenu
    End If
End Sub


Set Shell = Nothing
Set FSO = Nothing

WScript.Quit




-

WSH - ex) 곰플레이어 1.9 자동설치

* AutoInstall.vbs *


Option Explicit

On Error Resume Next
Err.Clear


Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")

Dim WshEnv : Set WshEnv = Shell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
Dim COMSPEC : COMSPEC = Shell.ExpandEnvironmentStrings("%comspec%")

' COMSPEC 지정할 필요없이 바로 Shell.Run "%comspec%~ 해도 됨..

 

Const ExeFile = "GOM.EXE"  '고정된 이름은 변수가 아닌 상수로 지정해도 무방..


If MsgBox ("곰플레이어 1.9를 설치하시겠습니까?  ", 36, "Setup - GomPlayer") = 6 Then

    Shell.Run COMSPEC & " /c " & ExeFile & " & Exit", 0

    ' 0 => cmd창 숨기고 설치창 활성화.   뒤에 ,true 붙이면 안됨
    Wscript.Sleep 3000
    Shell.AppActivate "곰플레이어 설치"
    Wscript.Sleep 800
    Shell.SendKeys "~", True ' next [엔터]
    Wscript.Sleep 800
    Shell.SendKeys "~", True ' 동의
    Wscript.Sleep 1000

    Shell.SendKeys "{TAB}", True ' 구성요소 (모든 동영상 확장자 등록 체크)
    Wscript.Sleep 500
    Shell.SendKeys "{DOWN}", True
    Wscript.Sleep 500
    Shell.SendKeys "{DOWN}", True
    Wscript.Sleep 500
    Shell.SendKeys "{DOWN}", True
    Wscript.Sleep 500
    Shell.SendKeys " ", True
    Wscript.Sleep 800
   
    Shell.SendKeys "~", True
    Wscript.Sleep 1000
    Shell.SendKeys "{DEL}", True  ' delete 키
    Wscript.Sleep 800
    Shell.SendKeys ProgramDir & "\GomPlayer", True ' 설치경로 변경( c:\prog~\Gomplayer )
    Wscript.Sleep 800
    Shell.SendKeys "~", True
    Wscript.Sleep 6500
    Shell.SendKeys "{TAB}", True
    Wscript.Sleep 800
    Shell.SendKeys "~" , True

Else
    Shell.Popup "곰플레이어 설치가 취소되었습니다.   ", 3, "Cancle", 48
    WScript.Quit
End if


' 바로가기 폴더(아이팝) 지우고 GomPlayer 새로 생성
Dim Programs : Programs = Shell.SpecialFolders("Programs") ' or AllUsersPrograms
Dim OldShortDir : OldShortDir = Programs & "\아이팝 (www.ipop.co.kr)"
Dim NewShortDir : NewShortDir = Programs & "\GomPlayer"

FSO.DeleteFolder OldShortDir
FSO.CreateFolder NewShortDir


Dim ExeLink : Set ExeLink = Shell.CreateShortcut(NewShortDir & "\곰플레이어.lnk")
ExeLink.HotKey = "CTRL+SHIFT+G"
ExeLink.TargetPath = ProgramDir & "\GomPlayer\Gom.exe"
ExeLink.WorkingDirectory = ProgramDir & "\GomPlayer"
ExeLink.Save

Set ExeLink = Nothing


Dim ManLink : Set ManLink = Shell.CreateShortcut(NewShortDir & "\곰매니저.lnk")
ManLink.TargetPath = ProgramDir & "\GomPlayer\GomMgr.exe"
ManLink.WorkingDirectory = ProgramDir & "\GomPlayer"
ManLink.Save

Set ManLink = Nothing


Dim UnLink : Set UnLink = Shell.CreateShortcut(NewShortDir & "\곰플레이어 제거.lnk")
UnLink.TargetPath = ProgramDir & "\GomPlayer\Uninstall.exe"
UnLink.Save

Set UnLink = Nothing


' _ad_temp_.ini 파일이 을 읽기전용으로 속성 변경.

' 최초 실행 전이라면 _ad_temp_.ini 파일이 아직 생성되지 않았음.

' _ad_temp_.ini 파일이 없는 상태라면 Gom.exe 를 실행시키야 환경설정창이 뜬다.
Dim iniFile : iniFile = ProgramDir & "\GomPlayer\_ad_temp_.ini"

Dim WizFile
If FSO.FileExists(iniFile) Then
    WizFile = "GomWiz.exe"
Else
    WizFile = "Gom.exe"
End If
   
Dim WizExec : Set WizExec = Shell.Exec(ProgramDir & "\GomPlayer\" & WizFile)
Wscript.Sleep 1000
Shell.AppActivate "언어 선택"
Shell.SendKeys "~" , True
Wscript.Sleep 800
Shell.AppActivate "곰플레이어 환경 설정 길잡이"
Wscript.Sleep 800
Shell.SendKeys "~" , True  ' 일반 모드
Wscript.Sleep 800
Shell.SendKeys "~" , True  ' 자체 코덱, 2채널 스피커
Wscript.Sleep 800
Shell.SendKeys "~", True

Wscript.Sleep 800
Shell.SendKeys "~" , True
Wscript.Sleep 800
Shell.SendKeys " " , True  ' 곰플레이어 실행 - 체크해제
Wscript.Sleep 800
Shell.SendKeys "~" , True
Wscript.Sleep 1500
Shell.SendKeys "{ESC}" , True  ' 곰플레이어 끄기


' WizExec 작업이 완전히 끝나야 다음으로 넘어간다.

' Run 과 Exec 의 차이 : Exec는 결과가 오브젝트로 생성되므로 이걸 다시 이용할 수 있다.

Do While WizExec.Status <> 1
 WScript.Sleep 100
Loop


Call SetReadOnly(iniFile)


Shell.Run  "regedit /s config.reg"

'Shell.Popup  "곰플레이어 1.9 설치가 완료되었습니다.   ", 3


'_ad_temp_.ini 파일을 읽기전용으로..
Sub SetReadOnly(f)
   Dim f1 : Set f1 = FSO.CreateTextFile(f, true) ' 덮어쓰면서 생성
   Dim f2 : Set f2 = FSO.GetFile(f1)
   f2.Attributes = 1
   Set f1 = Nothing
   Set f2 = Nothing
End Sub


Set Shell = Nothing
Set FSO = Nothing
Set WshEnv = Nothing
Set WizExec = Nothing

WScript.Quit

------------------------------

<config.reg>

Windows Registry Editor Version 5.00

; 옵션설정 - 업데이트 자동확인(x), 비슷한 파일명 열기(x), 재생시에만 맨위

[HKEY_CURRENT_USER\Software\GRETECH\GomPlayer\OPTION]
"bActiveMsg"=dword:00000000
"bCheckUpdate"=dword:00000000
"bNotifyUpdate"=dword:00000000
"bNotifyMinorUpdate"=dword:00000000
"bNotifySimilarFile"=dword:00000000
"idMenuLang"=dword:00000412
"idAudioLang"=dword:00000412
"idSubtitlesLang"=dword:00000412
"nOnTopMode"=dword:00000002


cf, 곰플레이어 2.0 버전 이상은 자동설치시 픽~ (Kill Processor).

'프로그래밍' 카테고리의 다른 글

아이폰에서 메일이 깨져 보인다!!  (0) 2010.08.19
FCKeditor JavaScript API  (0) 2009.06.10
PTviewer-속성  (0) 2008.01.04

 

FCKeditor JavaScript API

FCKeditor offers a complete JavaScript API so you can interact with it once the editor is loaded and running.

Once loaded, the editor registers a global object called FCKeditorAPI. This object offers the entry point to interact with any editor instance placed in a page (you can have more than one).

NOTE: The FCKeditorAPI object will not be available during the page load. You need to wait for the editor to be loaded to use it. If you need to interact with the editor right after is has been loaded, use the "FCKeditor_OnComplete" function (see Events).

Retrieving an Editor Instance

  • From out of an external script
    When placing the editor in the page, you give it an "instance name". To retrieve it, you must simply call the FCKeditorAPI.GetInstance method.
    Example:
    var oEditor = FCKeditorAPI.GetInstance('InstanceName') ;
    
  • From out of a dialog of the editor
    Call the InnerDialogLoaded to get the FCKObject.
    Example:
    var oEditor = window.parent.InnerDialogLoaded().FCK ;
    

Both methods return the main FCKeditor object that gives the necessary bridge to interact with it. These are the most useful properties and methods of this object:

Properties:

  • Name = ( string ) - the instance name.
  • Status = ( integer ) - the editor status (loading status).
  • EditorDocument = ( object ) - the DOM Document object for the editing area.
  • EditorWindow = ( object ) - the DOM Window object for the editing area.

Methods:

  • AttachToOnSelectionChange( functionPointer )
  • Focus()
  • SetHTML( html ), or SetData( html ) - sets the contents of the editor. Note that when using this method, you will loose any listener that you may have previously registered on the editor.EditorDocument.
  • GetHTML( formatted ), or GetXHTML( formatted ), or GetData( formatted ) - retrieves the edited html from the editor.
  • InsertElement( element )
  • InsertElementAndGetIt( e )
  • InsertHtml( html ) - inserts HTML in the current cursor position
  • IsDirty() - checks if the content in the editor has been changed
  • MakeEditable()
  • ResetIsDirty() - resets the dirty state
  • SwitchEditMode()
  • UpdateLinkedField()

Events

Once the editor loading phase is complete and it is ready to use (and interact with JavaScript), a standard function is called in the page that contains the editor, if the function is defined. This function must be named "FCKeditor_OnComplete" and receives the related editor instance as the parameter. Using it, you can execute any initial code that may interact with the editor. This is a declaration example:

function FCKeditor_OnComplete( editorInstance )
{
    alert( editorInstance.Name ) ;
}

Other than the above standard function, every FCKeditor instance has an "Event" object that can be used to listen for events to be fired.

Example: the following code listens for the "OnSelectionChange" to execute custom code:

function FCKeditor_OnComplete( editorInstance )
{
    editorInstance.Events.AttachEvent( 'OnSelectionChange', DoSomething ) ;
}

var counter = 0 ;

function DoSomething( editorInstance )
{
    // This is a sample function that shows in the title bar the number of times
    // the "OnSelectionChange" event is called.
    window.document.title = editorInstance.Name + ' : ' + ( ++counter ) ;
}

Note that every event callback function receives the editor instance as a parameter.

The following is the list of events available:

  • OnAfterLinkedFieldUpdate - fired right after the hidden linked field attached to the editor has its contents updated. It happens usually when the form is being posted.
  • OnAfterSetHTML - fired once the HTML is loaded in the editor (including when changing views).
  • OnFocus - fired when the editor acquires the focus.
  • OnPaste - fired when something is pasted in the editor. The function you specify must return true for the paste to proceed.
  • OnStatusChange - fired when the editor status changes. The following constants are also available globally in the page: FCK_STATUS_NOTLOADED, FCK_STATUS_ACTIVE and FCK_STATUS_COMPLETE.
  • OnSelectionChange - fired when the actual selection in the editor area changes (including cursor position and keystrokes). Note: In IE, this event does not fire on every keystroke, but only on some random keystrokes.

Usage Samples

The following are a few samples of things that can be done with the JavaScript API. (In these samples, oEditor = FCKeditorAPI.GetInstance('InstanceName').)

  • Insert HTML at cursor position:
    oEditor.InsertHtml(HTML);
  • Triggering a toolbar button / command:
    oEditor.Commands.GetCommand(commandName).Execute();
  • Disabling toolbar buttons:
    oEditor.EditorWindow.parent.FCKToolbarItems.LoadedItems[commandName].Disable();
  • Setting a config value:
    oEditor.Config['<configVariableName>'] = 'newValue';
  • Change editor document style at runtime:
    oEditor.EditorDocument.body.style.cssText += 'color: #322805; background-color: #F7C928;' ;
  • Set or get anything of the editor:
    FCKeditorAPI.GetInstance('InstanceName').EditorWindow.parent...
  • Add a dynamic Save function:
// called on save
function doSave(){
        alert('Saved.');
        document.getElementById('someElement').innerHTML = 'Saved!';
        return false; //this disables default action (submitting the form)
}
// called when FCKeditor is done starting..
function FCKeditor_OnComplete( editorInstance ){
        editorInstance.LinkedField.form.onsubmit = doSave;
}
  • Working with the selection in the editor: Use the Selection Object

'프로그래밍' 카테고리의 다른 글

Windows Script Host  (0) 2009.09.18
PTviewer-속성  (0) 2008.01.04
마이크로소프트 닷넷, 소스 공유한다  (0) 2007.10.08

 

ptviewer 영문 메뉴얼 바로가기

파라메터 값 기능설명

애플릿 코드, 뷰어크기
applet code="ptviewer.class" name="ptviewer" archive="ptviewer.jar"  height="222"  width="320"
 
파노라마 이미지
param name="file" value="panorama.jpg"
 
시작시 위치조정
param name="pan" value="0"
 
상하조절
param name="tilt" value="0"
 
시작때 확대.축소율 지정
param name="fov" value="90"
 
시작때 최대 축소율
param name=fovmin value=3
 
시작때 최대 확대율
param name="fovmax value="54"
 
시작시 회전속도
param name="auto" value="0.5"
 
이미지 퀄리티(선명도) 값
param name="quality" value="4"
 
이미지를 부드럽게
param name=antialias value="true"
 
파노라마 재생 시작 지점 (작동범위)
param name="panmin" value="-170"
 
파노라마 재생 끝 지점 (작동범위)
param name="panmax" value="175"
 
움직일 수 있는 최상단점  
param name=tiltmax value="18"
 
움직일 수 있는 최하단점
param name=tiltmin value="-18"
 
재생할 수 있는 최대 넓이
param name="view_width" value="150"
 
재생할 수 있는 최대높이
param name="view_height" value="60"
 
param name=oversampling value="1.8"
  -
커서 모양
param name="cursor" value="move"
 
뷰어 바탕색
param name="bgcolor" value="FFFFFF"
 
뷰어 스킨
param name="frame" value="navigator.gif"
 
param name="applet0" value="{code= ptmedia.class} {file= }"
 
나침반, 나침반 위치
param name="applet1" value="{code= ptcompass.class} {compass_map=compass.gif}
  {compass_x=75} {compass_y=206} {compass_pan=5}"

param name="inits" value="ptviewer:startApplet(1)"
 
Zoom Out
param name="shotspot0" value=" x16 y205 a32 b220 u'ptviewer:ZoomOut()' "
 
Zoom In
param name="shotspot1" value=" x32 y205 a48 b220 u'ptviewer:ZoomIn()' "
 
사이트 링크
param name="shotspot2" value=" x48 y205 a60 b220 u'http://www.vrclub.co.kr't'_blank' "
 
시작 (왼쪽 Play)
param name="shotspot3" value=" x100 y205 a116 b220 u'ptviewer:startAutoPan(-0.4,0,1)' "
 
위로 움직이기
param name="shotspot4" value=" x116 y205 a132 b220 u'ptviewer:panUp()' "
 
아래로 움직이기
param name="shotspot5" value=" x132 y205 a144 b220 u'ptviewer:panDown()' "
 
시작 (오른쪽 Play)
param name="shotspot6" value=" x144 y205 a160 b220 u'ptviewer:startAutoPan(0.4,0,1)' "
 
사이트 링크
param name="shotspot7" value=" x250 y200 a310 b225 u'http://www.vrclub.co.kr't'_blank' "
 
로딩 이미지
param name="wait" value="loading.gif"
 
로딩바 색상
param name="barcolor" value="CC0000"
 
로딩바 좌우 위치
param name="bar_x" value="40"
 
로딩바 상하 위치
param name="bar_y" value="170"
 
로딩바 길이
param name="bar_width" value="235"
 
로딩바 두께
param name="bar_height" value="8"

'프로그래밍' 카테고리의 다른 글

FCKeditor JavaScript API  (0) 2009.06.10
마이크로소프트 닷넷, 소스 공유한다  (0) 2007.10.08
iis6.0 에서 파일 업다운 제한  (2) 2007.05.02

 

과거 오픈소스에 대한 반대로 악명 높은 MS가 자사의 닷넷 프레임워크의 소스 코드를 공개하겠다는 4일(미국시간)의 발표는 다소 의외다.

소스 코드는 MS의 레퍼런스 라이선스에 따라 공개될 예정이다. 이는 이용자가 애플리케이션 디버깅이나 유지, 강화를 위한 레퍼런스로만 소스를 사용할 수 있다는 뜻이다. 코드는 어떤 목적으로도 변경하거나 유포할 수 없다.

이 라이선스는 MS가 보유하고 있는 가장 엄격한 소스 공유 라이선스다. 이번 발표는 닷넷이 오픈 소스로 혼란을 겪지 않고 공유 소스가 될 것이라는 점을 확인하고 있다.

닷넷 라이브러리 공개에 덧붙여, MS는 비주얼 스튜디오 2008에 닷넷용 디버깅 지원을 통합할 예정이다. MS는 “닷넷 프레임워크 심볼을 구성해 한 번에 다운로드하거나 주문에 따라 수동으로 검색할 수 있다”고 발표문에서 밝혔다.

코드는 완전한 오픈 소스가 아니지만, MS로서는 개방을 향한 중대한 조치이다. 닷넷 개발자 다수는 이번 공개가 오래 전부터 필요한 조치였다고 주장하지만, 개발자 커뮤니티는 코드 가용성의 혜택을 누릴 것으로 생각된다. 분명한 것은 이를 통해 MS가 완전한 오픈 소스에 한 발 다가섰으며 이를 지켜보는 일은 신선하다는 것이다.

하지만 과연 MS가 이 모험을 할지는 지켜 봐야 할 일이다. @

Harrison Hoffman (CNET News.com)

[ZDNet Korea 2007-10-08]

'프로그래밍' 카테고리의 다른 글

PTviewer-속성  (0) 2008.01.04
iis6.0 에서 파일 업다운 제한  (2) 2007.05.02
AJAX을 이용한 실시간 쪽지  (0) 2007.03.02

 


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Response.ContentType = 마임타입
Response.AddHeader "Content-Disposition","attachment; filename=" & 다운로드파일.확장자
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Type = 1
objStream.LoadFromFile 파일다운경로 & "\" & 다운로드파일.확장자
download = objStream.Read
Response.BinaryWrite download
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
iis 5.0에서 늘 쓰던 소스라 문제 없을줄 알았었는데.. 이상하리 만치 iis 6.0에선 다운로드할때 몇몇 녀석들이 안돼는것이였다. 단지 MIME 타입 설정, 혹은 헤더 값의 셋팅이 잘못되어있으리란 생각만으로 별짓을 다했것만....

고작 asp버퍼제한 용량이 문제였을 줄은.... 아 시간 아까워....

자, 해결방법!

1. IIS 등록정보
 -> 메타베이스 직접편집 허용 체크 :메타베이스소스를 iis 실행중일때도 수정 가능하도록 허용해준다.

2. 이제 제한되어있는 용량을 풀어주기만 하면 땡!
 - 메타베이스 파일위치 : C:\WINDOWS\system32\inetsrv\MetaBase.xml

 - 다운로드 버퍼링 제한

 -> AspBufferingLimit="4194304"  바로 이부분!!! 1024로 나누어보면 4096 byte 즉 4M 이다!!!
      늘리고 싶은 용량(byte) * 1024 로 해당부분 수정
 - 업로드 용량 제한
 -> AspMaxRequestEntityAllowed="204800"  역시 1024로 나누어보면 200 byte -_-a
      늘리고 싶은 용량(byte) * 1024 로 해당부분 수정


오늘의 교훈 - 역시나 자유로운 영혼만이.. 문제를 해결할수 있다!
-_-; 아 허접해

by echo

'프로그래밍' 카테고리의 다른 글

PTviewer-속성  (0) 2008.01.04
마이크로소프트 닷넷, 소스 공유한다  (0) 2007.10.08
AJAX을 이용한 실시간 쪽지  (0) 2007.03.02

 

AJAX을 이용한 실시간 쪽지 구현..  엄준일 / umjunil  
 

http://ajax.schwarz-interactive.de/csharpsample/default.aspx
※ AJAX.DLL을 참조 하셔야 합니다.

 web.config에 다음을 추가합니다.
<httpHandlers>
    <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
    </httpHandlers>

다음의 스크립트를 추가합니다.
<script>
 setTimeout("memocheck()",3000);     //3초마다 쪽지함을 검색한다.
 
 function memocheck()
 {
   var c=Right.MemoCheck();     //AJAX으로 서버의 함수를 호출한다.
   if(c.value>0)                        // 내 쪽지함에 쪽지가 있다면..
   {                                        // 팝업창을 연다.
    open('/community/mail.aspx?id=<%=userid%       >','','width=300,height=320,location=no,status=no,scrollbar=no');
   }
   else setTimeout("memocheck()",3000);
 }
</script>

어떤분은 임의로 사용자가 mail.aspx?id=xxxx 로 접근 할 경우 어떻게 하냐고, 보안에 대해서 질타를 받을 것같네요

이부분은 여러분이 해결해 보세요 .. 어렵진 않을 것 같네영^^;;;
쪽지가 도착했을 경우 팝업을 하구, 그렇지 않으면 계속 타이머를 동작한다.

위 스크립트 코드 비하인드:
[Ajax.AjaxMethod]
  public int MemoCheck()
  {
    ... 디비 연결
   string strcmd=string.Format("select count(*) from Mail where ID='{0}' and Send=0",Context.User.Identity.Name);
   cn.Open();
   SqlCommand cmd=new SqlCommand(strcmd,cn);

   try {

       int cnt=(int)cmd.ExecuteScalar();

       return cnt;

   }

   catch ( Exception e) { throw e; }

   finaly { 디비 닫기 }
  }
위 코드는 자신의 ID로 내게 도착한 쪽지의 갯수를 리턴합니다.
Send가 0일 경우는 도착하지 않은 쪽지입니다. default값은 0 입니다.

private string userid;

private void Page_Load(object sender, System.EventArgs e)
  {

       userid=Context.User.Identity.Name;
       Ajax.Utility.RegisterTypeForAjax(typeof(Right));
  }
위 코드로 AJAX을 이용할 클래스를 페이지로드에서 등록해야 합니다. (저는 Right.ascx의 클래스이므로 Right를 등록했습니다)

쪽지함 팝업 스크립트:
<body MS_POSITIONING="FlowLayout" onunload="opener.setTimeout('memocheck()',3000);">
BODY에 다음과 같이 추가하여 쪽지함을 닫을경우 다시 부모창의 타이머를
동작 시킵니다.

도착한 쪽지가 있어 팝업창이 열릴경우 Send필드는 1(true)로 업데이트 필수~~


쪽지함 테이블입니다.
create table Mail

(

    Num int identity(1,1) primary key not null,

    ID varchar(20) not null,

    Title varchar(50) not null,

    Content text not null,

    PostDate datetime not null default getdate(),

    PostIP varchar(15) not null,

    FromID varchar(20) not null,

    MailRead bit default 0,

    Send bit default 0

)

go


출처 : http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=8&MAEULNo=5&no=586&ref=586

'프로그래밍' 카테고리의 다른 글

PTviewer-속성  (0) 2008.01.04
마이크로소프트 닷넷, 소스 공유한다  (0) 2007.10.08
iis6.0 에서 파일 업다운 제한  (2) 2007.05.02

 

+ Recent posts