Programming/C#2011/10/20 13:40
스레드를 이용한 비동기 멀티스레딩
TitleSearch titleSearch = new TitleSearch();
ImageSearch imageSearch = new ImageSearch();
SemanticSearch semanticSearch = new SemanticSearch();

Task[] threads = new Task[]
{
//타이틀 검색 결과
new Task(() => resultTitleSearchXmlData=titleSearch.Operation(keyword)),
//시맨틱 검색 결과
new Task(() => resultSemanticSearchXmlData=semanticSearch.General(catgory,keyword)),
//이미지 검색결과
new Task(() => resultImageSearchXmlData=imageSearch.Operation(keyword))
};
for (int i = 0; i < threads.Length; i++)
{
threads[i].Start();
}
Task.WaitAll(threads);
또는

델리게이트를 이용한 비동기 멀티스레딩
//비동기 엔진 호출을 위한 메소드 선언
public delegate XmlDocument SemanticDele(int? catgory, string keyword);
public delegate XmlDocument ImageDele(string keyword);
public delegate XmlDocument TitleDele(string keyword);

SemanticDele semanticDele = new SemanticDele(semanticSearch.General);
ImageDele imageDele = new ImageDele(imageSearch.Operation);
TitleDele titleDele = new TitleDele(titleSearch.Operation);

IAsyncResult semanticSearchResult = semanticDele.BeginInvoke(catgory, keyword, null, null);
IAsyncResult titleSearchResult = titleDele.BeginInvoke(keyword, null, null);
IAsyncResult imageSearchResult = imageDele.BeginInvoke(keyword, null, null);

//Do some other work on priamry thread..
resultTitleSearchXmlData = titleDele.EndInvoke(titleSearchResult);
resultImageSearchXmlData = imageDele.EndInvoke(imageSearchResult);
resultSemanticSearchXmlData = semanticDele.EndInvoke(semanticSearchResult);

저작자 표시 비영리 변경 금지
Posted by Mizix
Programming/C#2011/10/06 12:20
기본 HTTP 호출

WebRequest request = (HttpWebRequest)WebRequest.Create(urlStr);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();

string tempString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?

C#에서 인증서 까지 가져오기.

public string GetHttpResult(string urlStr)
{
string certPath = cqLog.AppPath + "\\" + tsi.Host + ".cer";
if (!File.Exists(certPath))
{
// 오류
}
X509Certificate cert = X509Certificate.CreateFromCertFile(certPath);
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlStr);
request.ClientCertificates.Add(cert); // Attaching the Certificate To the request
TrustAllCert ValCallback = new TrustAllCert();
ServicePointManager.ServerCertificateValidationCallback =
new System.Net.Security.RemoteCertificateValidationCallback(ValCallback.OnValidationCallback);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();

string tempString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?

// print out page source
//Console.WriteLine(sb.ToString());
return sb.ToString();
}

...

public class TrustAllCert
{
public TrustAllCert()
{
}

public bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}

저작자 표시 비영리 변경 금지
Posted by Mizix
Programming2010/10/28 17:32
바다와 이클립스
View more presentations from mosaicnet.



저작자 표시 비영리 변경 금지

'Programming' 카테고리의 다른 글

바다와 이클립스  (0) 2010/10/28
Posted by Mizix
Programming/JAVA & JSP2010/08/24 16:07
Sqlite JDBC 다운

Example Source
import java.sql.*;

public class Test {
public static void main(String[] args) throws Exception {
Class.forName("org.sqlite.JDBC");
        Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
        Statement stat = conn.createStatement();
        
        stat.executeUpdate("drop table if exists people;");
        stat.executeUpdate("create table people (name, occupation);");
        PreparedStatement prep = conn.prepareStatement(
        "insert into people values (?, ?);");

        prep.setString(1, "Gandhi");
        prep.setString(2, "politics");
        prep.addBatch();
        prep.setString(1, "Turing");
        prep.setString(2, "computers");
        prep.addBatch();
        prep.setString(1, "Wittgenstein");
        prep.setString(2, "smartypants");
        prep.addBatch();

        conn.setAutoCommit(false);
        prep.executeBatch();
        conn.setAutoCommit(true);
        
        ResultSet rs = stat.executeQuery("select * from people;");
        while (rs.next()) {
                System.out.println("name = " + rs.getString("name"));
                System.out.println("job = " + rs.getString("occupation"));
        }
        rs.close();
        conn.close();
}
}
저작자 표시 비영리 변경 금지

'Programming > JAVA & JSP' 카테고리의 다른 글

Sqlite DB + java 연동  (0) 2010/08/24
각종 DB JDBC 연결  (0) 2010/08/17
JDK 1.6 + mssql 2005 연동하기.  (0) 2010/06/25
페이징 처리 UI&Application Logic  (0) 2010/03/08
소스 사이트  (0) 2010/01/08
Posted by Mizix
Programming/C#2010/08/18 16:08

ex>>
// 암호화 키(8byte)
static byte[] desKey = ASCIIEncoding.ASCII.GetBytes("tech0001");
Des des = new Des(desKey);
.......

Des Class(암호화, 복호화)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;


/// <summary>
/// Summary description for Des
/// </summary>
public class Des
{
    byte[] key = null;
protected Des()
{
}

    public Des(byte[] desKey)
    {
        this.key = desKey;
    }

    public string Encrypt(string plain_text)
    {
        if (string.IsNullOrEmpty(plain_text))
        {
            throw new ArgumentException("The string which needs to be encrypted can not be null.");
        }
        if (key.Length != 8)
        {
            throw (new Exception("Invalid key. Key length must be 8 byte."));
        }

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
            cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);
        StreamWriter writer = new StreamWriter(cryptoStream);
        writer.Write(plain_text);
        writer.Flush();
        cryptoStream.FlushFinalBlock();
        writer.Flush();
        string cypher_text = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
        return cypher_text;
    }

    public string Decrypt(string cypher_text)
    {
        if (String.IsNullOrEmpty(cypher_text))
        {
            throw new ArgumentNullException
               ("The string which needs to be decrypted can not be null.");
        }
        if (key.Length != 8)
        {
            throw (new Exception("Invalid key. Key length must be 8 byte."));
        }
        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream
                (Convert.FromBase64String(cypher_text));
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
            cryptoProvider.CreateDecryptor(key, key), CryptoStreamMode.Read);
        StreamReader reader = new StreamReader(cryptoStream);
        string plain_text = reader.ReadToEnd();
        return plain_text;
    }
}
저작자 표시 비영리 변경 금지
Posted by Mizix
Programming/JAVA & JSP2010/08/17 13:11
1. Oracle
    1). 서버환경
        - 서버 주소 : 127.0.0.1
        - 서비스 포트 : 1521
    
    2). JDBC 설정
        - Driver 클래스 : oracle.jdbc.driver.OracleDriver
        - URL 형식 : jdbc:oracle:thin:@127.0.0.1:1521

2. MySQL
    1). 서버환경
        - 서버 주소 : 127.0.0.1
        - 서비스 포트 : 3306
        - MySQL Database Name : mydb
    
    2). JDBC 설정
        - Driver 클래스 : com.mysql.jdbc.Driver
        - URL 형식 : jdbc:mysql://127.0.0.1:3306/mydb

3. MS-SQL
    1). 서버환경
        - 서버 주소 : 127.0.0.1
        - 서비스 포트 : 1433
    
    2). JDBC 설정
        - Driver 클래스 : com.microsoft.jdbc.sqlserver.SQLServerDriver
        - URL 형식 : jdbc:microsoft:sqlserver://127.0.0.1:1433

4. JavaDB
    1). 서버환경
        - 서버 주소 : 127.0.0.1
        - JavaDB Database Name : derbyDB
    
    2). JDBC 설정
        - Driver 클래스 : org.apache.derby.jdbc.EmbeddedDriver
        - URL 형식 : jdbc:derby:derbyDB

5. Postgresql
    1). 서버환경
        - 서버 주소 : 127.0.0.1
        - 서비스 포트 : 5432
        - Postgresql Database Name : postDB
    
    2). JDBC 설정
        - Driver 클래스 : org.postgresql.Driver
        - URL 형식 : jdbc:postgresql://127.0.0.1:5432/postDB
저작자 표시 비영리 변경 금지

'Programming > JAVA & JSP' 카테고리의 다른 글

Sqlite DB + java 연동  (0) 2010/08/24
각종 DB JDBC 연결  (0) 2010/08/17
JDK 1.6 + mssql 2005 연동하기.  (0) 2010/06/25
페이징 처리 UI&Application Logic  (0) 2010/03/08
소스 사이트  (0) 2010/01/08
Posted by Mizix
Programming/C#2010/08/06 10:41

인덱스 생성 법

struct IntBits
    {
        public IntBits(int initialBitValue)
        {
            bits = initialBitValue;
        }

        //여기에 인덱서를 작성.
        public bool this[int index]
        {
            get { return (bits & (1 << index)) != 0; }
            set
            {
                if (value)
                    bits |= (1 << index);
                else
                    bits &= ~(1 << index);
            }
        }
        private int bits;
       
    }

인덱스 특성

  • 인덱서는 메서드가 아니다. 즉, 파라미터를 갖는 괄호가 없으나 인텍스를 지정하기 위한 각괄호가 있다. 이 인텍스는 어던 요소를 사용할 것인지를 지정한다.
  • 모든 인덱서는 메서드 이름 대신 this 키워드를 사용한다. 클레스 또는 구조체는 최대 하나의 인덱서를 정의할 수 있으며, 그 이름은 항상 this이다.
  • 인덱서는 속성처럼 get과 set 접근 메서드를 갖는다. 위의 예제에서 get과 set 접근 메서드는 앞에서 설명한 복잡한 비트 단위의 수식을 포함하게 된다.
  • 인덱서 선언문에 지정한 인덱스에는 인덱서를 호출할 때 지정한 인덱스 값이 사용된다. get과 set 접근 메서드에서는 어떤 요소에 접근할 것인지 결정하기 위해 이 인수를 읽을 수 있다.

인덱서 사용

int adapted = 62;   // 62는 2진수로 111110이다.
            IntBits bits = new IntBits(adapted);
            bool peek = bits[6];// 6번째 인덱스 위치의 논리값을 받는다. 여기서는 참(1)이 된다.
            bits[0] = true;     // 인덱스 0 위치의 비트를 참(1)으로 지정한다.
            bits[3] = false;    // 인덱스 3 위치의 비트를 거짓(0)으로 지정한다.
                                // 이렇게 완성된 값은 111011 또는 10진수 59가 된다.

'Programming > C#' 카테고리의 다른 글

https GET 결과 가져오기  (0) 2011/10/06
C# DES 암호화(Encrypt), 복호화(Decrypt)  (0) 2010/08/18
인덱서  (0) 2010/08/06
나열형(enum)과 구조체(struct) 선언.  (0) 2010/07/20
게시판 리스트 처리.  (0) 2010/06/10
Posted by Mizix
Programming/C#2010/07/20 15:35

나열 형식 선언하기

enum Season { Spring, Summer, Fall, Winter }

 

나열형 변수 선언하기

Season currentSeason;

 

나열형 변수에 값 지정하기

currentSeason = Spring; //오류

currentSeason = Season.Spring //올바름

 

구조체 선언하기

struct Time

{

   public Time(int hh, int mm, int cc)

   { … }

   …

   private int hours, minutes, seconds;

}

 

구조체 변수 선언하기

Time now;

 

구조체 변수에 값 초기화하기

Time lunch = new Time(12, 30, 0);

Posted by Mizix
TAG ENUM, struct
Programming/JAVA & JSP2010/06/25 09:00
마이크로소프트에 가서 mssql용 jdbc를 다운 받는다.
sqljdbc_2.0.1803.100_kor.exe <-- 이 파일을 압축 해제한다.
kor 폴더 안에 sqljdbc4.jar, sqljdbc.jar 이 두가지가 있는데, 자신의 java JDK 버전이 1.6 이상이면 sqljdbc4.jar 을 톰캣 안의 lib 폴더 안에 복사한다.
(절대, 두 파일을 같이 넣으면 안됨. 반드시 둘 중에 하나만 복사. 버전이 1.5 이하 버전이면, sqljdbc.jar을 넣는다.)

<< 기본적인 소스 코드 >>

    Connection conn=null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    String sql = null;

    try{
        String jdbcUrl="jdbc:sqlserver://주소:포트;DatabaseName=DB명";
        String dbId="DB 접속 ID";
        String dbPass="DB 접속 PASS";
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");


        conn = DriverManager.getConnection(jdbcUrl,dbId,dbPass);
        
        
        sql = "SELECT * FROM users";
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery(); 
        while(rs.next()) {  
            String id = rs.getString("uid");  
            String pass = rs.getString("pwd");
            String dateTime = rs.getDate("since").toString();
            out.println(id);  
            out.println(pass);
out.println(dateTime);
        }  
        rs.close();  
        pstmt.close();  
        conn.close();  
        
        out.println("제대로 연결되었습니다.");
        
    }catch(Exception e){
        out.println("오류..");
        e.printStackTrace();
    }finally{
        //con.close();
        out.println("제대로 종료되었습니다.");

<< mssql용 JDBC >>
저작자 표시 비영리 변경 금지

'Programming > JAVA & JSP' 카테고리의 다른 글

Sqlite DB + java 연동  (0) 2010/08/24
각종 DB JDBC 연결  (0) 2010/08/17
JDK 1.6 + mssql 2005 연동하기.  (0) 2010/06/25
페이징 처리 UI&Application Logic  (0) 2010/03/08
소스 사이트  (0) 2010/01/08
Posted by Mizix
Programming/C#2010/06/10 15:09
화면단.

<form id="form1" runat="server">
    <div>
        
        회원 리스트<br />
        <asp:GridView ID="memberListCtl" runat="server"  
            AutoGenerateColumns="False" Width="400px">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" />
                <asp:BoundField DataField="PASSWORD" HeaderText="PASSWORD" />
                <asp:BoundField DataField="NAME" HeaderText="NAME" />
                <asp:BoundField DataField="EMAIL" HeaderText="EMAIL" />
            </Columns>
            
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:intraConnectionString %>" 
            ProviderName="<%$ ConnectionStrings:intraConnectionString.ProviderName %>" 
            SelectCommand="SELECT * FROM member"></asp:SqlDataSource><br />
        검색 :
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem Value="ID">아이디</asp:ListItem>
            <asp:ListItem Value="NAME">이름</asp:ListItem>
        </asp:DropDownList>
    &nbsp;<asp:TextBox ID="searchText" runat="server" Width="200px"></asp:TextBox>
&nbsp;<asp:Button ID="searchBtn" runat="server" Text="검색" onclick="searchBtn_Click" />
    </div>
    </form>

소스단.

string strQuery = "select * from member";

        private void DisplayData()
        {
            string strCon = "server=localhost;database=intra;uid=intra;pwd=intra";
            MySqlConnection con = new MySqlConnection(strCon);


            MySqlCommand cmd = new MySqlCommand(strQuery, con);

            MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
            
            DataSet ds = new DataSet();
            adapter.Fill(ds, "VC");
            

            this.memberListCtl.DataSource = ds.Tables[0];
            this.memberListCtl.DataBind();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            DisplayData();
        }

        protected void searchBtn_Click(object sender, EventArgs e)
        {

            strQuery = "select * from member where " + DropDownList1.SelectedValue + "='" + searchText.Text + "'";
            DisplayData();
        }
저작자 표시 비영리 변경 금지
Posted by Mizix