티스토리 툴바



'전체'에 해당되는 글 422건

  1. 2011/05/01 카메라 연동 코드 (UIImagePickerController) (2)
  2. 2011/04/25 iphone에서 http 사용하기 (get/post) - 소스코드는 퍼왔습니다.
  3. 2010/01/01 CxImage의 MakeBitmap를 잘못 사용하면 페이지파일(PF), 메모리 사용량이 늘어난다. (1)
  4. 2009/12/27 C#을 이용한 LPT1 포트 제어 자료 - 시작시점...
  5. 2009/12/23 MD5 샘플 코드
  6. 2009/12/16 C# WebBrowser의 다른 사용법 (WebBrowser, Bitmap)
  7. 2009/12/15 C# USB 인식 심플한 코드
  8. 2009/12/15 C# Thread, delegate, Invoke 사용예
  9. 2009/12/07 WebBrowser 처리방식.. 참.. (1)
  10. 2009/12/01 [MSSQL] 문자일 일부분 특정문자(**)로 치환
  11. 2009/11/20 DB에 Image 데이터를 바이너리로 저장 및 로드하기
  12. 2009/11/10 DB 바인딩 클래스 - 펌 - 미테스트본. (2)
  13. 2009/10/30 InstallShield 제작시 url 파일을 적용하면 설치된 pc에 아이콘 이미지가 적용이 되지 않는 문제 [해결방법]
  14. 2009/10/19 ActiveX Cab 파일 제작기.. - 문제점에 대한 의견
  15. 2009/09/09 [MSSQL 2005] 년+월 정보를 사용해서 테이블이 존재 할때는 생성하는 방법
2011/05/01 22:34

카메라 연동 코드 (UIImagePickerController)

[기능]
- 카메라를 통한 사진 선택
- 롤 이미지에서 사진 선택
- 도큐먼트에 이미지 저장
- 새로 실행할때 도큐먼트 이미지 로드 기능

-h 코드

//

//  DocumentTestViewController.h

//  DocumentTest

//

//  Created by 병욱 on 11. 5. 1..

//  Copyright 2011 GsiSystem. All rights reserved.

//


#import <UIKit/UIKit.h>


#define kFilename @"data.plist"

#define kImageFilename @"Test.png"


@interface DocumentTestViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate> {

IBOutlet UIImageView *imageView;

IBOutlet UIButton *takePictureButton;

IBOutlet UIButton *selectFromCameraRollButton;

IBOutlet UITextField *field1;

IBOutlet UITextField *field2;

IBOutlet UITextField *field3;

IBOutlet UITextField *field4;

}


@property (nonatomic, retain) UIImageView *imageView;

@property (nonatomic, retain) UIButton *takePictureButton;

@property (nonatomic, retain) UIButton *selectFromCameraRollButton;


@property (nonatomic, retain) UITextField *field1;

@property (nonatomic, retain) UITextField *field2;

@property (nonatomic, retain) UITextField *field3;

@property (nonatomic, retain) UITextField *field4;


- (NSString *)dataFilePath;

- (NSString *)dataImageFilePath;

- (void) applicationWillTerminate:(NSNotification *)notification;

- (IBAction)getCameraPicture:(id)sender;

- (IBAction)selectExistingPicture;


@end


- m 코드

//

//  DocumentTestViewController.m

//  DocumentTest

//

//  Created by 병욱 on 11. 5. 1..

//  Copyright 2011 GsiSystem. All rights reserved.

//


#import "DocumentTestViewController.h"


@implementation DocumentTestViewController


@synthesize field1, field2, field3, field4;

@synthesize imageView;

@synthesize takePictureButton;

@synthesize selectFromCameraRollButton;


/*

// The designated initializer. Override to perform setup that is required before the view is loaded.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}

*/


/*

// Implement loadView to create a view hierarchy programmatically, without using a nib.

- (void)loadView {

}

*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

//    [super viewDidLoad];

//

NSString *filePath = [self dataFilePath];

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {

NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];

field1.text = [array objectAtIndex:0];

field2.text = [array objectAtIndex:1];

field3.text = [array objectAtIndex:2];

field4.text = [array objectAtIndex:3];

[array release];

}

//

NSString *imageFilePath = [self dataImageFilePath];

if ([[NSFileManager defaultManager] fileExistsAtPath:imageFilePath]) {

UIImage *image = [UIImage imageWithContentsOfFile:imageFilePath];

imageView.image = image;

}

//

UIApplication *app = [UIApplication sharedApplication];

[[NSNotificationCenter defaultCenter] addObserver:self 

selector:@selector(applicationWillTerminate:) 

name:UIApplicationWillTerminateNotification 

  object:app];

[super viewDidLoad];

//

if (![UIImagePickerController isSourceTypeAvailable:

  UIImagePickerControllerSourceTypeCamera]) {

takePictureButton.hidden = YES;

selectFromCameraRollButton.hidden = YES;

}

}


- (NSString *)dataFilePath

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

return [documentsDirectory stringByAppendingPathComponent:kFilename];

}


- (NSString *)dataImageFilePath

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

return [documentsDirectory stringByAppendingPathComponent:kImageFilename];

}


- (void) applicationWillTerminate:(NSNotification *)notification

{

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:field1.text];

[array addObject:field2.text];

[array addObject:field3.text];

[array addObject:field4.text];

[array writeToFile:[self dataFilePath] atomically:YES];

[array release];

}


/*

// Override to allow orientations other than the default portrait orientation.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

*/


- (void)didReceiveMemoryWarning {

// Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.

}


- (void)viewDidUnload {

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}



- (void)dealloc {

    [super dealloc];

[field1 release];

[field2 release];

[field3 release];

[field4 release];

[imageView release];

[takePictureButton release];

[selectFromCameraRollButton release];

}


- (IBAction)getCameraPicture:(id)sender

{

UIImagePickerController *picker = 

[[UIImagePickerController alloc] init];

picker.delegate = self;

picker.allowsImageEditing = YES;

picker.sourceType = (sender == takePictureButton) ?

UIImagePickerControllerSourceTypeCamera

UIImagePickerControllerSourceTypeSavedPhotosAlbum;

[self presentModalViewController:picker animated:YES];

[picker release];

}


- (IBAction)selectExistingPicture

{

if ([UIImagePickerController isSourceTypeAvailable:

UIImagePickerControllerSourceTypePhotoLibrary]) {

UIImagePickerController *picker = 

[[UIImagePickerController alloc] init];

picker.delegate = self;

picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

picker.allowsImageEditing = YES;

[self presentModalViewController:picker animated:YES];

[picker release];

}

else {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error accessing photo library"

message:@"Device does not support a photo library"

  delegate:nil

  cancelButtonTitle:@"Drat!"

  otherButtonTitles:nil];

[alert show];

[alert release];

}

}


- (void)imagePickerController:(UIImagePickerController *)picker

didFinishPickingImage:(UIImage *)image

  editingInfo:(NSDictionary *)editingInfo {

imageView.image = image;

printf("Image:%f, %f", image.size.width, image.size.height);

[UIImagePNGRepresentation(image) writeToFile:[self dataImageFilePath]

  atomically:YES];

[picker dismissModalViewControllerAnimated:YES];

}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

[picker dismissModalViewControllerAnimated:YES];

}


@end


- 인터페이스 빌더 내용
캡춰 맥에서 어케 하는지 몰겠군요. ^^
 
저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 2
2011/04/25 17:50

iphone에서 http 사용하기 (get/post) - 소스코드는 퍼왔습니다.

POST로 데이터를 보낼때 NSDictionary를 사용하면 되는데 스타일은
아래의 코드와 같이 실제 값이 앞에 가고 뒤에 이름이 들어간다.

[뷰에 클릭후 http를 생성 및 초기 코드]

// url 문자열을 이용하여 HTTP 웹사이트에 접속

- (void)requestUrl {

    // 접속할 주소 설정

    NSString *url = @"http://사용자의 웹 페이지 주소";

    

    // HTTP Request 인스턴스 생성

    HTTPRequest *httpRequest = [[HTTPRequest alloc] init];

    

    // POST 전송할 데이터 설정

    NSDictionary *bodyObject = [NSDictionary dictionaryWithObjectsAndKeys:

@"38.0", @"latitude"

@"127.0", @"longitude",

nil];

//NSString *bodyObject = @"type=getUser&seq=1&latitude=38.0&longitude=127.0&time=13600&unit='k'&distance=9999";

    

    // 통신 완료 호출할 델리게이트 셀렉터 설정

    [httpRequest setDelegate:self selector:@selector(didReceiveFinished:)];

    

    // 페이지 호출

    [httpRequest requestUrl:url bodyObject:bodyObject];

//

[spinner startAnimating];

}


아래 코드들은 클래스 생성후에 내용을 추가 해야 합니다.
[HTTPRequest.h]

#import <Foundation/Foundation.h>



@interface HTTPRequest : NSObject

{

    NSMutableData *receivedData;

    NSURLResponse *response;

    NSString *result;

    id target;

    SEL selector;

}


- (BOOL)requestUrl:(NSString *)url bodyObject:(NSDictionary *)bodyObject;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

- (void)setDelegate:(id)aTarget selector:(SEL)aSelector;


@property (nonatomic, retain) NSMutableData *receivedData;

@property (nonatomic, retain) NSURLResponse *response;

@property (nonatomic, assign) NSString *result;

@property (nonatomic, assign) id target;

@property (nonatomic, assign) SEL selector;


@end



[HTTPRequest.m]

#import "HTTPRequest.h"


@implementation HTTPRequest


@synthesize receivedData;

@synthesize response;

@synthesize result;

@synthesize target;

@synthesize selector;


- (BOOL)requestUrl:(NSString *)url bodyObject:(NSDictionary *)bodyObject

{

    // URL Request 객체 생성

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]

                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                       timeoutInterval:5.0f];

    

    // 통신방식 정의 (POST, GET)

    [request setHTTPMethod:@"POST"];

    

    // bodyObject 객체가 존재할 경우 QueryString형태로 변환

    if(bodyObject)

    {

        // 임시 변수 선언

        NSMutableArray *parts = [NSMutableArray array];

        NSString *part;

        id key;

        id value;

        

        // 값을 하나하나 변환

        for(key in bodyObject)

        {

            value = [bodyObject objectForKey:key];

            part = [NSString stringWithFormat:@"%@=%@", [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],

[value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

            [parts addObject:part];

        }

        

        // 값들을 & 연결하여 Body 사용

        [request setHTTPBody:[[parts componentsJoinedByString:@"&"] dataUsingEncoding:NSUTF8StringEncoding]];

    }

    

    // Request 사용하여 실제 연결을 시도하는 NSURLConnection 인스턴스 생성

    NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

    

    // 정상적으로 연결이 되었다면

    if(connection)

    {

        // 데이터를 전송받을 멤버 변수 초기화

        receivedData = [[NSMutableData alloc] init];

        return YES;

    }

    

    return NO;

}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse

{

    // 데이터를 전송받기 전에 호출되는 메서드, 우선 Response 헤더만을 먼저 받아 온다.

    //[receivedData setLength:0];

    self.response = aResponse;

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    // 데이터를 전송받는 도중에 호출되는 메서드, 여러번에 나누어 호출될 있으므로 appendData 사용한다.

    [receivedData appendData:data];

}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    // 에러가 발생되었을 경우 호출되는 메서드

    NSLog(@"Error: %@", [error localizedDescription]);

}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    // 데이터 전송이 끝났을 호출되는 메서드, 전송받은 데이터를 NSString형태로 변환한다.

    result = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

    

    // 델리게이트가 설정되어있다면 실행한다.

    if(target)

    {

        [target performSelector:selector withObject:result];

    }

}


- (void)setDelegate:(id)aTarget selector:(SEL)aSelector

{

    // 데이터 수신이 완료된 이후에 호출될 메서드의 정보를 담고 있는 셀렉터 설정

    self.target = aTarget;

    self.selector = aSelector;

}


- (void)dealloc

{

    [receivedData release];

    [response release];

    [result release];

    [super dealloc];

}


@end


 
저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2010/01/01 23:29

CxImage의 MakeBitmap를 잘못 사용하면 페이지파일(PF), 메모리 사용량이 늘어난다.


MFC의 Dialog 베이스를 사용해서 폼을 하나 제작합니다.
그리고 picture Box 를 하나 제작한 후에 CxImage를 사용해서 png 파일을 하나 로드 한후에
picture Box에 SetBitmap 를 하고 나서 이걸 다른 형태로 테스트를 진행해 봤습니다.

기본 코드는 아래와 같아요.

// CxImage 객체 생성
m_pImage = new CxImage("D:\\Test.png", CXIMAGE_FORMAT_PNG);

// PictureBox 컨트롤에 CxImage 이미지 연동
m_pic.SetBitmap( m_pImage->MakeBitmap() );

이렇게 하고 나서 실행 하고, 종료 하게 되면 크게 문제는 안되는듯 하다.

이걸 다른 형태로 테스트를 해봤다.
타이머를 통해서 CxImage 객체 두개의 Bitmap를 m_pic(PictureBox) 컨트롤에 SetBitmap를 반복해서 처리해봤다.

void CPngToBitmapDlg::OnTimer(UINT nIDEvent)
{
 static bool bFirst = false;
 static HBITMAP hBitmap = NULL;

 if( bFirst == false )
 { 
  hBitmap = m_pic.SetBitmap( m_pImage2->MakeBitmap() );
 }
 else
 {
  hBitmap = m_pic.SetBitmap( m_pImage->MakeBitmap() );
 }

 ::DeleteObject( hBitmap );

 //
 bFirst = !bFirst;

 m_loopCount++;
 UpdateData(false);
 

 CDialog::OnTimer(nIDEvent);
}

위의 붉은색 코드를 하지 않고 계속해서 SetBitmap을 하게 되면
페이지파일(PF)가 계속 증가 하는 것을 볼 수 있다.

앞으로 코드 구현을 할때 하나 하나 단위테스트를 통해서 반복적인 메모리 및 GDI 사용량 등을
체크 하고 좀 안정성 있는 프로그램을 하도록 해야 할거 같다.

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 1
2009/12/27 00:04

C#을 이용한 LPT1 포트 제어 자료 - 시작시점...


참고자료 : http://www.codeproject.com/KB/cs/control_e_appliances.aspx

1. hwinterface.ocx 를 regsvr32 를 통해서 등록한다.
2. Visual Studio 의 도구 상자에서 ocx 를 등록한다.
   - Hwinterface Control의 activex 컨트롤이 생긴다.
3. 해당 폼으로 가져와서 인스턴스를 생성한다.
4. 나머지 코드는 참고 자료의 링크에 존재 하는 파일을 참고 하기 바람

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/12/23 13:44

MD5 샘플 코드


--선언--
using System.Security.Cryptography;

--코드--
        #region MD5 메소드
        static string getMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        // Verify a hash against a string.
        static bool verifyMd5Hash(string input, string hash)
        {
            // Hash the input.
            string hashOfInput = getMd5Hash(input);

            // Create a StringComparer an comare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region MD5 테스트 블록
        private void button1_Click(object sender, EventArgs e)
        {
            // 암호화 문자열을 가져온다.
            string convmd5 = getMd5Hash(textBox1.Text);

            // 암호화된 내용을 출력한다.
            textBox2.Text = convmd5;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 해당 문자열을 가져와서 암호화된 내용과 비교 한다.
            if (verifyMd5Hash(textBox3.Text, textBox2.Text) == true)
            {
                MessageBox.Show("맞습니다.");
            }
            else
            {
                MessageBox.Show("틀립니다.");
            }
        }
        #endregion

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/12/16 03:11

C# WebBrowser의 다른 사용법 (WebBrowser, Bitmap)


WebBrowser를 사용해야 되는 부분이 생겨서
많이 자료를 보고 해봤지만 TopMost라는 특성 때문에 Winform, WPF 모두
원하는 효과를 낼수가 없더라구요.

그래서 여러가지 보고 테스트도 해봤지만.
어떤건 속도가 너무 느리더라구요.

아래 코드는 완전 해결한건 아니지만,
이것도 조금은 접근이 된거 같아요.

목표점은
- 스레드를 통한 백그라운드 처리를 통해서 다른 UI의 동작을 원할하게 처리
-  모자이크 처리로 화면에 출력함으로 해서 조금은 이펙트를 중점으로 한다.

아래의 코드는 일부 접근된 코드를 우선 올려 봅니다.

-- Code --
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;
using System.Media;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        WebBrowser web = new WebBrowser();

        public Form1()
        {
            InitializeComponent();

            web.Width = 1000;
            web.Height = 1000;
            web.ScrollBarsEnabled = false;
            web.ScriptErrorsSuppressed = true;
            web.Navigate("http://dev.iamgsi.com/googlemap");

            timer1.Start();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //while (web.ReadyState != WebBrowserReadyState.Complete)
            //    System.Windows.Forms.Application.DoEvents();
            //System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));

            int width = web.Document.Body.ScrollRectangle.Width;
            int height = web.Document.Body.ScrollRectangle.Height;
            web.Width = width;
            web.Height = height;

            System.Drawing.Bitmap bmp = new Bitmap(width, height);
            web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height));

            this.pictureBox1.Width = width;
            this.pictureBox1.Height = height;
            if (this.pictureBox1.Image != null)
            {
                this.pictureBox1.Image.Dispose();
            }
            this.pictureBox1.Image = null;
            this.pictureBox1.Image = bmp;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            web.Document.InvokeScript("MoveAddress", new object[] { "서울" });
        }

        private void button3_Click(object sender, EventArgs e)
        {
            web.Document.InvokeScript("MoveAddress", new object[] { "거창" });
        }

        private void button4_Click(object sender, EventArgs e)
        {
            web.Document.InvokeScript("MoveAddress", new object[] { "광주" });
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (web.ReadyState != WebBrowserReadyState.Complete)
                return;

            int width = web.Document.Body.ScrollRectangle.Width;
            int height = web.Document.Body.ScrollRectangle.Height;
            web.Width = width;
            web.Height = height;

            System.Drawing.Bitmap bmp = new Bitmap(width, height);
            web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height));

            this.pictureBox1.Width = width;
            this.pictureBox1.Height = height;
            if (this.pictureBox1.Image != null)
            {
                this.pictureBox1.Image.Dispose();
            }
            this.pictureBox1.Image = null;
            this.pictureBox1.Image = bmp;
        }
    }
}

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/12/15 18:25

C# USB 인식 심플한 코드


    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            bool bFind = false;

            // USB 상태 체크
            DriveInfo [] diArray = DriveInfo.GetDrives();
            foreach (DriveInfo di in diArray)
            {
                if (di.IsReady == true && di.DriveType == DriveType.Removable)
                {
                    bFind = true;
                    break;
                }
            }

            label1.Text = (bFind == true) ? "존재합니다." : "없습니다.";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }
    }

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/12/15 17:34

C# Thread, delegate, Invoke 사용예


    public partial class ucPanel : UserControl
    {
        public ucPanel()
        {
            InitializeComponent();

            //
            backgroundWorker1.RunWorkerAsync();
        }

        static public Font ChangeFontSize2(Font font, float fontSize, GraphicsUnit unit)
        {
            if (font != null)
            {
                float currentSize = font.Size;
                if (currentSize != fontSize)
                {
                    font = new Font(font.Name, fontSize,
                        font.Style, unit,
                        font.GdiCharSet, font.GdiVerticalFont);
                }
            }
            return font;
        }

        public delegate void OnAddNode(string title, int x, int y);
        public void AddNode(string title, int x, int y)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new OnAddNode(this.AddNode), new object[] { title, x, y });
                return;
            }

            // 객체 추가
            Label lbl2 = new Label();
            lbl2.AutoSize = true;
            lbl2.Text = title;
            lbl2.Font = ChangeFontSize2(lbl2.Font, lbl2.Font.Size * 2, GraphicsUnit.Pixel);
            lbl2.Left = x;
            lbl2.Top = y;
            this.Controls.Add(lbl2);

            ucNode ucn = new ucNode();
            ucn.Left = x;
            ucn.Top = y;
            this.Controls.Add(ucn);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int breakCount = 0;
            Random rand = new Random();

            while (true)
            {
                //
                this.Invoke(new OnAddNode(this.AddNode), new object[] { "test", rand.Next(10, 738), rand.Next(10, 460) });

                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));

                //
                breakCount++;
                if (breakCount > 100)
                {
                    break;
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }
    }

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/12/07 06:09

WebBrowser 처리방식.. 참..


2일 정도 자료를 찾아 보고 했지만.
WebBrowser 는 왜 WPF의 렌더링 방식과 차이가 있는지 모르겠다.
왜냐하면 WebBrowser 위에 다른걸 그리고 싶었지만.
되지 않더라..

그래서 자료를 보다 보니. BitmapSource 라는걸 사용해서 WPF의 렌더링 방식에
맞출수 있다는걸 알았다.
뭐 용어는 잘 모르겠고 암튼 이런 방식인게다. 쩝..
산넘어 산인거지..

우선 이걸 해결 하고 나니 몇가지 더 테스트 할게 남아 있다.
실제 WebBrowser는 숨겨 놓고 Image 같은데 실시간으로 뿌리면서 드로잉 해야 한다는 것과
숨겨 놓은 웹의 Mouse, Keyboard 등의 접근을 또 어떻게 처리 해야 하느냔데..

암튼 더 고민해봐야 할듯 하다.
아래 자료는 최종 코드...

-- Source --
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="600" Width="1000" xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration">

    <Grid>
        <WebBrowser x:Name="webbrowser" Source="http://www.naver.com" Margin="0,0,437,199" />
       
        <Button Height="23" HorizontalAlignment="Right" Margin="0,104,307,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click">Button</Button>
        <Image HorizontalAlignment="Right" Margin="0,178,18,21" Name="image1" Stretch="Fill" Width="399" />
    </Grid>

</Window>

..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;


namespace WpfApplication1
{
    /// <summary> 
    /// Interaction logic for Window1.xaml 
    /// </summary> 
    public partial class Window1 : Window
    {
        BitmapSource bitmapsource = null;

        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);

        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
       
        public Window1()
        {
            InitializeComponent();
        }

        BitmapSource GetScreenInt()
        {
            Bitmap bm = new Bitmap((int)300, (int)300);
            IntPtr hBitmap = bm.GetHbitmap();
            Graphics g = Graphics.FromImage(bm);
            PrintWindow(this.webbrowser.Handle, g.GetHdc(), 0);

            g.ReleaseHdc();

            g.Flush();

            BitmapSource src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bm.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            src.Freeze();

            bm.Dispose();
            bm = null;
            DeleteObject(hBitmap);

            return src;

        }
       
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.image1.Source = null;
            this.image1.Source = GetScreenInt();
        }
    } 
}

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 1
2009/12/01 03:40

[MSSQL] 문자일 일부분 특정문자(**)로 치환

SELECT REPLACE(CONVERT(varchar(max),textvalue), Substring(textvalue,Len(textvalue)-1,2),'**')
from TBL_TEST_DB

textvalue의 값이 12345 라고 하면 123** 로 치환한다.
저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/11/20 17:17

DB에 Image 데이터를 바이너리로 저장 및 로드하기


구글이라던지 이곳저곳 찾아 보면 상당히 많은 예제가 나오는거 같다.
GsiClip을 제작중에 DB에 이미지를 데이터로 추가 해야 하는 부분에
단위 테스트에 사용한 소스 코드임. (테스트 수행)

        private void button1_Click(object sender, EventArgs e)
        {
            // 이미지를 DB로 저장한다.
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ImageSave(openFileDialog1.FileName);

                MessageBox.Show("저장완료");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 이미지를 DB에서 로드한다.
            dsImageTableAdapters.Test1TableAdapter adapter =
                new ImageSaveDB.dsImageTableAdapters.Test1TableAdapter();
            dsImage.Test1DataTable table =
                new dsImage.Test1DataTable();

            adapter.Fill(table);

            if (table.Count > 0)
            {
                pictureBox1.Image = byteArrayToImage(table[0].Content2);
            }
        }

        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        byte[] ReadFile(string sPath)
        {
            byte[] data = null;

            //
            FileInfo fInfo = new FileInfo(sPath);
            long numBytes = fInfo.Length;
            //
            FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
            //
            BinaryReader br = new BinaryReader(fStream);
            //
            data = br.ReadBytes((int)numBytes);

            return data;
        }

        private void ImageSave(string filename)
        {
            byte[] imageData = ReadFile(filename);

            //
            dsImageTableAdapters.Test1TableAdapter adapter =
                new ImageSaveDB.dsImageTableAdapters.Test1TableAdapter();

            adapter.Insert(imageData);
        }

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/11/10 17:47

DB 바인딩 클래스 - 펌 - 미테스트본.

[web.config 쪽에 해당 내용 추가]
 <appSettings>
  <add key="DSN" value="Data Source=dev.iamgsi.com,1433;Initial Catalog=testdb;user id=test;Password=test;"/>
 </appSettings>

[DB 처리 클래스]
using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication1
{
    public class GDBCon
    {
        private int mCount = 0;
        private SqlConnection mDbConn = null;
        private SqlCommand mCmd = null;
        private SqlDataReader mReader = null;
        StringBuilder sb = new StringBuilder();

        /* DataBase Connection Open */
        public void DbConn()
        {
            try
            {
                mDbConn = new SqlConnection(GetDSN);
                mDbConn.Open();
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "DataBase Open 실패");
            }
        }

        // 연결문자열을 위한 Property
        protected string GetDSN
        {
            get
            {
                // 밑에 구문이 web.config 에 있는 AppSettings
                return System.Configuration.ConfigurationSettings.AppSettings["BoardDSN"];
            }
        }
       
        /* DataBase Connection Close */
        public void DbClose()
        {
            if (mDbConn == null)
            {
                return;
            }

            try
            {
                if (mDbConn.State.ToString() == "Open")
                {
                    mDbConn.Close();
                }
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "DataBase Close 실패");
            }
        }

        /* DataBase Transaction Init */
        public void InitTransaction(string TransName)
        {
            try
            {
                mCmd = new SqlCommand();
                mCmd.Connection = mDbConn;
                mCmd.Transaction = mDbConn.BeginTransaction(IsolationLevel.ReadCommitted, TransName);
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "Trancsaction Open 실패");
            }
        }

        /* Transaction Execute Query */
        public void ExecuteTransaction(string[] QueryArr)
        {
            try
            {
                foreach (string Query in QueryArr)
                {
                    mCmd.CommandText = Query;
                    mCmd.ExecuteNonQuery();
                }
                mCmd.Transaction.Commit();

            }
            catch (Exception e)
            {
                mCmd.Transaction.Rollback();
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "Trancsaction Commit 실패");
            }
        }


        /* Query Execute */
        public void ExecuteQuery(string Query)
        {
            try
            {
                mCmd = new SqlCommand(Query, mDbConn);
                mCmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, Query);
            }
        }

        /* SQL DataReader Fatech Query */
        public SqlDataReader FatechQuery(string Query)
        {
            try
            {
                mCmd = new SqlCommand(Query, mDbConn);
                mReader = mCmd.ExecuteReader();
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, Query);
            }
            return mReader;
        }

        /* SQL DataReader Close */
        public void ReaderClose()
        {
            try
            {
                if (!mReader.IsClosed)
                {
                    mReader.Close();
                }
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "SQLReader Close 실패");
            }
        }

        /* Procedure Execute */
        public int ExecuteProc(string ProcName, IDataParameter[] parameters)
        {
            int Result = 0;
            try
            {
                SqlCommand Cmd = BuildIntCommand(ProcName, parameters);
                Cmd.ExecuteNonQuery();
                Result = (int)Cmd.Parameters["ReturnValue"].Value;
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "Procedure ExecuteProc Error");
            }
            return Result;
        }

        /* SQL DataReader Fatech Procedure */
        public SqlDataReader FatechProc(string ProcName, IDataParameter[] parameters)
        {
            SqlCommand Cmd = BuildProcCommand(ProcName, parameters);
            try
            {
                Cmd.CommandType = CommandType.StoredProcedure;
                mReader = Cmd.ExecuteReader();
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "Procedure FatechProc Error");
            }
            return mReader;
        }

        /* Execute Query DateSet */
        public DataSet ExecuteDataSet(string Query, string TableName, int StartRecord, int PageSize)
        {
            DataSet mDataSet = new DataSet();
            try
            {
                SqlDataAdapter mDataAdapter = new SqlDataAdapter(Query, mDbConn);
                mDataAdapter.Fill(mDataSet, StartRecord, PageSize, TableName);
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, Query);
            }

            return mDataSet;
        }

        /* Execute Procedure DateSet */
        public DataSet ExecuteProcDataSet(string ProcName, IDataParameter[] parameters, string TableName, int StartRecord, int PageSize)
        {
            DataSet mDataSet = new DataSet();
            SqlDataAdapter mDataAdapter = new SqlDataAdapter();

            mDataAdapter.SelectCommand = BuildProcCommand(ProcName, parameters);
            try
            {
                mDataAdapter.Fill(mDataSet, StartRecord, PageSize, TableName);
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "Procedure ExecuteProcDataSet Error");
            }

            return mDataSet;
        }

        /* Total Count Function */
        public int TotalQuery(string Query)
        {
            try
            {
                mCmd = new SqlCommand(Query, mDbConn);
                mCount = (int)mCmd.ExecuteScalar();
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, Query);
            }
            return mCount;
        }

        /* Procedure BuildIntCommand */
        protected SqlCommand BuildIntCommand(string ProcName, IDataParameter[] parameters)
        {
            SqlCommand Cmd = BuildProcCommand(ProcName, parameters);

            try
            {
                Cmd.Parameters.Add(new SqlParameter("ReturnValue",
                 SqlDbType.Int,
                 4, /* Size */
                 ParameterDirection.ReturnValue,
                 false, /* is nullable */
                 0, /* byte precision */
                 0, /* byte scale */
                 string.Empty,
                 DataRowVersion.Default,
                 null));
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "Procedure BuildIntCommand Error");
            }

            return Cmd;
        }

        /* Procedure Parameter Build */
        protected SqlCommand BuildProcCommand(string ProcName, IDataParameter[] parameters)
        {
            try
            {
                mCmd = new SqlCommand(ProcName, mDbConn);
                mCmd.CommandType = CommandType.StoredProcedure;

                foreach (SqlParameter parameter in parameters)
                {
                    mCmd.Parameters.Add(parameter);
                }
            }
            catch (Exception e)
            {
                DbErrorMsg(e.Source, e.Message, e.StackTrace, "Procedure BuildProcCommand Error");
            }

            return mCmd;
        }

        /* Error Message Print */
        public void DbErrorMsg(string ErrSource, string ErrMsg, string stack, string Query)
        {
            DbClose();
            string ErrorMsg = "Error Souce =" + ErrSource + "<br>"
             + "Error Message = <font color='red'><b>" + ErrMsg + "</b></font><br>"
             + "Stack = " + stack + "<br><br>"
             + "Query = <font color='blue'><b>" + Query + "</b></font>";
            System.Web.HttpContext.Current.Response.Write(ErrorMsg);
            System.Web.HttpContext.Current.Response.End();
        }
    }
}

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 2
2009/10/30 15:12

InstallShield 제작시 url 파일을 적용하면 설치된 pc에 아이콘 이미지가 적용이 되지 않는 문제 [해결방법]


url 파일을 하나 만들어서 인스톨 쉴드를 통해서 배포를 했는데
설치한 pc에서 해당 url이 바탕화면에 깔리긴 하는데.
이상하게 아이콘 이미지가 나오지 않았다.

제작을 할때 바로가기 아이콘을 하나 만든 다음에 ico 를 해당 url 파일 속성에서 아이콘 변경을 통해서
처리를 했다.
근데 문제는 여기서 발생했는데 ico 파일을 메모장에서 열어 보면 아래와 같은 경로 입력 부분이 나오게 된다.

[InternetShortcut]
URL=http://www.test.co.kr/
IDList=
IconFile=C:\Program Files\JupiterSoft\test\bb.ico
HotKey=0
IconIndex=0
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2

위와 같이 IconFile 쪽에 내가 설치한후 ico 파일이 있는 경로를 적어 줘야
다른 pc에서 제대로 나오는걸 확인 했다.

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/10/19 03:27

ActiveX Cab 파일 제작기.. - 문제점에 대한 의견


한동안 포스트를 못했다.
삶이 너무 바쁘게 돌아 가다 보니

이 포스트를 한건건 소스를 공개 하는건 아니다.
하지만 몇가지 경우에 대해서 공론화를 하기 위해서다.
물론 여기에 있어서 지원을 받고 싶거나, 질문을 주시면 성심 성의껏 도와줄 의양은 있어요 ^^

ActiveX를 이용해서 웹에서 실행 파일을 제어 하기 위해서
최근에 작업을 했다.

기존에 크게 문제시 되었던 부분이 아니라서 개발 일정을 짦게 잡았던게 화근이였다. -.-

참.. 쉽게 해결되지 않는게 프로그램의 일이란걸 세삼 느꼈다.

.Net 2003으로 ActiveX를 개발을 하였다.
아주 기본으로 해서 메소드를 정의 하고 웹에 붙였다.

로컬에서는 아주 잘 되었고 그래서 웹 서버에 올려서 테스트 하면 잘 되겠지
싶었다.
웹 서버에 올리고 노란바가 정상적으로 나왔다.
그래서 이제 되겠거니 했지만.
ActiveX의 메소드가 웹에서 인식이 되지 않아서 메소드 정의가 없다는 오류가 나왔다.
IE 6.0, 8.0 모두 그런 현상이 발생 하였다.

그래서 보안 탭의 신뢰할 수 있는 사이트에 넣고 하니
제대로 될때도 있었지만.
안될때가 더 많았고 안되는 pc가 더 많았다.

근데 또 이상한건 신뢰할 수 있는 사이트에 웹 주소를 넣고 나서는
ACtiveX의 버젼을 올려서 배포를 해도 노란바가 아예 뜨지를 않았다.
하지만 구동은 정상적으로 업데이트 된게 실행이 되는 상태였다.

근데 그것도 이상하게 메소드가 없는 오류가 나올때가 있었다.

여러가지를 테스트해본 결과 IObjectSafety 인가 그 인터페이스 추가에서 문제가 나왔던거 같다.
이 코드를 적용하는데 있어서 helper.h, cpp 파일을 추가 하고 Ctrl.cpp에 추가 하고 하는 과정에서
오류가 있었던거 같다.

이제는 어려 곳의 컴퓨터에서 실행을 해봤지만 잘 되는거 같다.

ActiveX에서 많이 어려움을 가지는 초보 개발자가 있다면
언제든 쪽지 및 네이트온 추가를 통해서 질문해 주시기 바랍니다.
프로그래머는 항상 자료를 공유 하고 많이 나누면서 서로 발전해야 한다고 생각해요

그럼 오늘도 해결 안되는 문제를 안고 씨름 하는 많은 개발자들 화이팅 ^^
저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/09/09 04:16

[MSSQL 2005] 년+월 정보를 사용해서 테이블이 존재 할때는 생성하는 방법

> 테이블 합치는 방법 : 테이블 + 2009 + 09
> 테이블이 존재 하지 않으면 테이블을 생성한다.

---------------------------------------------------------------------------------------
DECLARE @curDateString varchar(100)
DECLARE @tableCount int
DECLARE @sql nvarchar(4000)

-- 현재 시간에서 년, 월을 가져온다.
SET @curDateString = 'TBL_SERVICE_LOG_'
     + convert(varchar(30), year(GetDate()))
     + REPLICATE('0', 2 - len(month(GetDate()))) + convert(varchar(30), month(GetDate()))
--print @curDateString

-- 테이블 존재 하는지 개수를 가져온다.
select @tableCount = count(*)
from sysobjects
where xtype='U' and
name = @curDateString

--print @tableCount

-- 테이블이 존재 하지 않으면 테이블을 생성한다.
IF @tableCount != 1
BEGIN
 SET @sql = N'CREATE TABLE ' + @curDateString + N' (' +
 N'[OrderNo] [int] NULL,' + 
 ...................생략...............
 N'[OriginTelNo] [varchar](50) NULL' +
 N');'
 EXEC(@sql)
END
--ELSE
--BEGIN
 --print '테이블 존재함'
--END

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0