GSI

[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();
        }
    }
}

Posted by gsi
:


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에서 제대로 나오는걸 확인 했다.

Posted by gsi
:


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

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

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

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

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

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

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

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

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

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

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

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

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

그럼 오늘도 해결 안되는 문제를 안고 씨름 하는 많은 개발자들 화이팅 ^^
Posted by gsi
:

> 테이블 합치는 방법 : 테이블 + 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

Posted by gsi
:


[MS-SQL][Visual C++ 6.0_Stored_Procedures_TEST_예제_Program]


//--------------------------------------------------------------
[New Class...]


[Class type] : [Generic Class] | [Name] : [CADODB]
#include "ADODB.h"

class CADODB
{
private:
    _RecordsetPtr  m_RS;
    _CommandPtr    m_CMD;
    _ConnectionPtr m_CONN;

public:
             CADODB();
    virtual ~CADODB();

    CString  db_Error_Message;

    BOOL     DBConnect(char* pWD, char* pID, char* pDataBase, char* pConnectIP);
    BOOL     IsOpen_DB();
    BOOL     IsOpen_RS();
    void     Close_RS();

    BOOL     IsEOF();
    BOOL     Next();
    BOOL     First();

    int      GetRecordCount();
    int      GetFieldCount();

    void     GetRS(_variant_t x, _bstr_t& ret);
    void     GetRS(_variant_t x, _variant_t& ret);
    void     GetRS(_variant_t x, float& ret);
    void     GetRS(_variant_t x, long& ret);
    void     GetRS(_variant_t x, double& ret);

    void     Open_Command(char* StoredProcedureString);
    void     Add_Parameters(_bstr_t _ParameterName,
                             DataTypeEnum _SqlDbType,
                             int _Size,
                             ParameterDirectionEnum _Direction,
                            _variant_t _User_Value);

    BOOL     RowReader();
    long     QueryExecute(_bstr_t _ParameterName);
};



//--------------------------------------------------------------
[ClassView] - [CADODB]

CADODB::CADODB()
{
    m_RS = NULL;
    m_CMD = NULL;
    m_CONN = NULL;
}

CADODB::~CADODB()
{
    if(m_RS != NULL)
    {
        if(IsOpen_RS())
        {
            m_RS->Close();
        }
    }

    if(m_CONN != NULL)
    {
        if(IsOpen_DB())
        {
            m_CONN->Close();
        }
    }
}

BOOL CADODB::DBConnect(char* pWD, char* pID, char* pDataBase, char* pConnectIP)
{
    CString strConnectionString;
    strConnectionString.Format(_T("Provider=SQLOLEDB.1;Persist Security Info=True;
                                   Password = %s;
                                   User ID = %s;
                                   Initial Catalog = %s;
                                   Data Source = %s"),
                                   pWD,
                                   pID,
                                   pDataBase,
                                   pConnectIP);

    m_CONN.CreateInstance("ADODB.Connection");
    m_CONN->ConnectionString = _bstr_t(strConnectionString);
    HRESULT hr = m_CONN->Open("", "", "", -1);

    if(SUCCEEDED(hr))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

BOOL CADODB::IsOpen_DB()
{
    return ((m_CONN->GetState() == adStateOpen ) ? TRUE : FALSE);
}

BOOL CADODB::IsOpen_RS()
{
    return ((m_RS->GetState() == adStateOpen ) ? TRUE : FALSE);
}

void CADODB::Close_RS()
{
    if(IsOpen_RS())
    {
        m_RS->Close();
    }
}

BOOL CADODB::IsEOF()
{
    return m_RS->adoEOF;
}

BOOL CADODB::Next()
{
    return (FAILED(m_RS->MoveNext()) ? FALSE : TRUE);
}

BOOL CADODB::First()
{
    return (FAILED(m_RS->MoveFirst()) ? FALSE : TRUE);
}

int CADODB::GetRecordCount()
{
    HRESULT hr;
    ASSERT(m_RS != NULL);
    try
    {
        int count = (int)m_RS->GetRecordCount();

        if (count < 0)
        {
            hr = m_RS->MoveFirst();
            count = 0;
            while (!m_RS->adoEOF)
            {
                count++;
                m_RS->MoveNext();
            }
        }

        if (m_RS->adoEOF)
        {
            m_RS->MoveFirst();
        }

        return count;
    }
    catch (_com_error ex)
    {
        TRACE(_T("Warning: GetRecordCount ErrorMessage: %s;
                  File: %s;
                  Line: %d\n"),
                  ex.ErrorMessage(),
                __FILE__,
                __LINE__);
        return -1;
    }
}

int CADODB::GetFieldCount()
{
    return (int)m_RS->Fields->GetCount();
}

void CADODB::GetRS(_variant_t x, _bstr_t& ret)
{
    ret = m_RS->Fields->Item[x]->Value;
}

void CADODB::GetRS(_variant_t x, _variant_t& ret)
{
    ret = m_RS->Fields->Item[x]->Value;
}

void CADODB::GetRS(_variant_t x, float& ret)
{
    ret = m_RS->Fields->Item[x]->Value;
}

void CADODB::GetRS(_variant_t x, long& ret)
{
    ret = m_RS->Fields->Item[x]->Value;
}

void CADODB::GetRS(_variant_t x, double& ret)
{
    ret = m_RS->Fields->Item[x]->Value;
}

void CADODB::Open_Command(char* StoredProcedureString)
{
    m_CMD.CreateInstance("ADODB.Command");
    m_CMD->CommandText = StoredProcedureString;
    m_CMD->CommandType = adCmdStoredProc;
}

void CADODB::Add_Parameters(_bstr_t _ParameterName,
                               DataTypeEnum _SqlDbType,
                               int _Size,
                               ParameterDirectionEnum _Direction,
                              _variant_t _User_Value)
{
    _ParameterPtr AddParameter;
    AddParameter.CreateInstance("ADODB.Parameter");
    AddParameter->Name = _ParameterName;
    AddParameter->Type = _SqlDbType;
    AddParameter->Size = _Size;
    AddParameter->Direction = _Direction;
    m_CMD->Parameters->Append(AddParameter);
    m_CMD->Parameters->Item[_ParameterName]->Value = _User_Value;
}

BOOL CADODB::RowReader()
{
    try
    {
        m_CMD->ActiveConnection = m_CONN;
        m_CMD->Execute(NULL, NULL, adCmdStoredProc);

        m_RS.CreateInstance(__uuidof(Recordset));
        m_RS->PutRefSource(m_CMD);

        _variant_t vNull;
        vNull.vt = VT_ERROR;
        vNull.scode = DISP_E_PARAMNOTFOUND;
        m_RS->CursorLocation = adUseClient;
        m_RS->Open(vNull, vNull, adOpenStatic, adLockOptimistic, adCmdStoredProc);

        return true;
    }
    catch (_com_error ex)
    {
        if(m_RS != NULL)
        {
            db_Error_Message = ex.ErrorMessage();
            Close_RS();
        }
        else
        {
            db_Error_Message = ex.ErrorMessage();
        }
        return false;
    }
}

long CADODB::QueryExecute(_bstr_t _ParameterName)
{
    m_CMD->ActiveConnection = m_CONN;

    try
    {
        m_CMD->Execute(NULL, NULL, adCmdStoredProc);

        return long(m_CMD->Parameters->Item[_ParameterName]->Value);
    }
    catch (_com_error ex)
    {
        db_Error_Message = ex.ErrorMessage();

        return -1;
    }
}



//--------------------------------------------------------------
[include files] - [stdafx.h]
//------------------------------
#pragma warning(push)
#pragma warning(disable:4146)
#import "c:\Program Files\Common Files\System\ADO\msado15.dll" no_namespace rename("EOF","adoEOF")
#pragma warning(pop)
//--------------------------------------------------------------


//--------------------------------------------------------------
[ClassView] - [CADOVCApp]

BOOL CADOVCApp::InitInstance()
{
     CoInitialize(NULL); //ADO 초기화
}

int CADOVCApp::ExitInstance()
{
    CoUninitialize();   //ADO 제거

    return CWinApp::ExitInstance();
}


//--------------------------------------------------------------
[include] - [ADOVCDlg.h]


#include "ADODB.h"

class CADOVCDlg : public CDialog
{
public:
    void Execute_Message_Send(CString GetMessage);
    void iMageList_LiST_View();
    BOOL DBConnect();
    CADODB m_ADO;
    CStatusBar  m_wndStatusBar;


//--------------------------------------------------------------
[ClassView] - [CADOVCDlg]

BOOL CADOVCDlg::OnInitDialog()
{
    if(!DBConnect())
    {
        AfxMessageBox("Error DB Connect!!");
    }
}


//--------------------------------------------------------------
[ClassView] - [CADOVCDlg]

void CADOVCDlg::Execute_Message_Send(CString GetMessage)
{
    m_Message_List.AddString(GetMessage);
    m_Message_List.SetTopIndex(m_Message_List.GetCount() - 1);
}

// Stored Procedure - [MS-SQL][Microsoft Visual C++ 6.0]
BOOL CADOVCDlg::DBConnect()
{
    if(m_ADO.DBConnect("550107", "sa", "iMageDB", "SCORPION"))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

void CADOVCDlg::OnBtnDelete()
{
    CString msgString;
    long ErrorNUM = 0;
    BOOL b_GetValue = TRUE;

    m_DB_Delete_NUM = GetDlgItemInt(IDC_EDIT_DELETE, &b_GetValue, FALSE);

    msgString.Format(_T("[삭제] - [PF1_1_5_iMageList_DELETE]"));
    m_wndStatusBar.SetPaneText(0, msgString);

    msgString.Format(_T("[삭제]-[PF1_1_5_iMageList_DELETE] - [삭제번호] → [%d]"), m_DB_Delete_NUM);
    Execute_Message_Send(msgString);

    msgString.Format(_T("삭제번호 : [%d]\n\n삭제 하시겠습니까?"), m_DB_Delete_NUM);
    if(AfxMessageBox(msgString, MB_YESNO) == IDYES)
    {
        m_ADO.Open_Command("PF1_1_5_iMageList_DELETE");
        m_ADO.Add_Parameters("@DB_ERR", adInteger, 4, adParamOutput, 0l);
        m_ADO.Add_Parameters("@iMageNUM_1", adInteger, 4, adParamInput, m_DB_Delete_NUM);
        ErrorNUM = m_ADO.QueryExecute("@DB_ERR");

        if(ErrorNUM == 0)
        {
            msgString.Format(_T("[삭제] → [Success]"));
            Execute_Message_Send(msgString);

            iMageList_LiST_View();
        }
        else
        {
            if (ErrorNUM == 544)
            {
                msgString.Format(_T("[iMageList][Delete ERROR] [Delete NUM] : [%d] %s"),
                                 m_DB_Delete_NUM, m_ADO.db_Error_Message);
            }
            else
            {
                msgString.Format(_T("[PF1_1_5_iMageList_DELETE][Delete ERROR] %s"), m_ADO.db_Error_Message);
            }
            Execute_Message_Send(msgString);
        }
    }
}

void CADOVCDlg::OnBtnInsert()
{
    CString msgString;
    long ErrorNUM = 0;
    BOOL b_GetValue = TRUE;

    long Get_INPUT_Error_NUM = 0;
    long Get_iMageNUM = 0;

    GetDlgItemText(IDC_EDIT_PATH, m_DB_Insert_Path);
    GetDlgItemText(IDC_EDIT_FILENAME, m_DB_Insert_FileName);
    m_DB_Insert_FileSize = GetDlgItemInt(IDC_EDIT_FILESIZE, &b_GetValue, FALSE);

    msgString.Format(_T("[저장] - [PF1_1_5_iMageList_iNSERT"));
    m_wndStatusBar.SetPaneText(0, msgString);

    msgString.Format(_T("[저장]-[PF1_1_5_iMageList_iNSERT] - [파일명] → [%s]"), m_DB_Insert_FileName);
    Execute_Message_Send(msgString);

    if(!m_ADO.IsOpen_DB())
    {
        DBConnect();
    }

    m_ADO.Open_Command("PF1_1_5_iMageList_iNSERT");
    m_ADO.Add_Parameters("@DB_ERR", adInteger, 4, adParamOutput, 0l);
    m_ADO.Add_Parameters("@iMageNUM_1", adInteger, 4, adParamOutput, 0l);
    m_ADO.Add_Parameters("@ImagePath_2", adVarChar, 255, adParamInput, _variant_t(m_DB_Insert_Path));
    m_ADO.Add_Parameters("@ImageFile_3", adVarChar, 255, adParamInput, _variant_t(m_DB_Insert_FileName));
    m_ADO.Add_Parameters("@iMageSize_4", adInteger, 4, adParamInput, m_DB_Insert_FileSize);
    ErrorNUM = m_ADO.QueryExecute("@DB_ERR");

    if(ErrorNUM == 0)
    {
        msgString.Format(_T("[추가] → [Success]"));
        Execute_Message_Send(msgString);

        iMageList_LiST_View();
    }
    else
    {
        if (ErrorNUM == 541)
        {
            msgString.Format(_T("[iMageList][iNSERT ERROR] [iMageList FileName] : [%d] %s"),
                             m_DB_Insert_FileName, m_ADO.db_Error_Message);
        }
        else
        {
            msgString.Format(_T("[iMageList][iNSERT ERROR] %s"), m_ADO.db_Error_Message);
        }
        Execute_Message_Send(msgString);
    }
}

void CADOVCDlg::OnBtnSearch()
{
    CString msgString;

    msgString.Format(_T("[조회] - [PF1_1_5_iMageList_LIST]"));
    m_wndStatusBar.SetPaneText(0, msgString);

    iMageList_LiST_View();
}

void CADOVCDlg::iMageList_LiST_View()
{
    CString msgString;
    CString db_Get_String;
    CString str_temp;

    int iROWCOUNT;
    int iField;

    BOOL b_GetValue = TRUE;

    GetDlgItemText(IDC_EDIT_SEARCH_FILENAME, m_DB_Search_FileName);
    m_DB_UserTOP = GetDlgItemInt(IDC_EDIT_USER_TOP, &b_GetValue, FALSE);

    if(m_DB_Search_FileName.GetLength() == 0 || !b_GetValue)
    {
        m_DB_Search_FileName = '%';
    }
    else
    {
        m_DB_Search_FileName = m_DB_Search_FileName + '%';
    }

    msgString.Format(_T("[조회][Stored_Procedure - %s] - [검색문자 : %s]"),
                     _T("PF1_1_5_iMageList_LIST"), m_DB_Search_FileName);
    Execute_Message_Send(msgString);

    if(!m_ADO.IsOpen_DB())
    {
        DBConnect();
    }

    m_ADO.Open_Command("PF1_1_5_iMageList_LIST");
    m_ADO.Add_Parameters("@USER_TOP", adInteger, 4, adParamInput, m_DB_UserTOP);
    m_ADO.Add_Parameters("@iMageName", adVarChar, 255, adParamInput, _variant_t(m_DB_Search_FileName));

    if(m_ADO.RowReader())
    {
        _bstr_t dbFieldGetValue;

        iROWCOUNT = m_ADO.GetRecordCount();
        if(iROWCOUNT <= 0) return;
        iField = m_ADO.GetFieldCount();

        msgString.Format(_T("Record : [%d]"), iROWCOUNT);
        m_wndStatusBar.SetPaneText(1, msgString);
        msgString.Format(_T("Field : [%d]"), iField);
        m_wndStatusBar.SetPaneText(2, msgString);

        m_ADO.GetRS(_variant_t((short)0), dbFieldGetValue);

        m_DB_Search_List.DeleteAllItems();
        for(int iROW = 0; iROW < iROWCOUNT; iROW++)
        {
            str_temp.Format(_T("%d"), (iROW + 1));
            m_DB_Search_List.InsertItem(iROW, str_temp);
            for(int jCOL = 0; jCOL < iField; jCOL++)
            {
                m_ADO.GetRS(_variant_t((short)jCOL), dbFieldGetValue);
                db_Get_String.Format(_T(("%s"), (LPCTSTR)dbFieldGetValue);

                m_DB_Search_List.SetItemText(iROW, (jCOL + 1), db_Get_String);
            }

            m_ADO.Next();
        }
        m_ADO.Close_RS();
    }
    else
    {
        msgString.Format(_T("Table ROW Read Error [%s]"), m_ADO.db_Error_Message);
        Execute_Message_Send(msgString);
    }
}



----------------------------------------------------------------
[MS-SQL] - [Stored Procedure]
----------------------------------------------------------------
[CREATE TABLE] - [iMageList]
--------------------------------
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[iMageList]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table   [dbo].[iMageList]
GO

CREATE TABLE [dbo].[iMageList]
(
             [iMageNUM] [int] IDENTITY (1, 1) NOT NULL ,
             [iMagePath] [varchar] (255) COLLATE Korean_Wansung_CI_AS NOT NULL ,
             [iMageFile] [varchar] (255) COLLATE Korean_Wansung_CI_AS NOT NULL ,
             [iMageSize] [int] NULL
) ON         [PRIMARY]
GO

ALTER TABLE  [dbo].[iMageList] WITH NOCHECK ADD
CONSTRAINT   [PK_iMageList] PRIMARY KEY  CLUSTERED
(
             [iMageNUM]
) ON         [PRIMARY]
GO

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


----------------------------------------------------------------
[iMageDB - iMageList] Table
+--------------------------------+
|     [iMageDB] - [DataBase]     |
+--------------------------------+
|            iMageList           |
+----------------+---------+-----+
| iMageNUM       | int     |   4 |
| iMagePath      | varchar | 255 |
| iMageFile      | varchar | 255 |
| iMageSize      | int     |   4 |
+----------------+---------+-----+
----------------------------------------------------------------


----------------------------------------------------------------
[Stored Procedures]

----------------------------------------------------------------
[PF1_1_5_iMageList_LIST]
----------------------------------------------------------------
CREATE PROCEDURE [PF1_1_5_iMageList_LIST]
                (@USER_TOP  [INT],
                 @iMageName [VARCHAR](255))

AS

SET ROWCOUNT @USER_TOP

SELECT
            [dbo].[iMageList].iMagePath,
            [dbo].[iMageList].iMageFile,
            [dbo].[iMageList].iMageSize,
            [dbo].[iMageList].iMageNUM
FROM        [dbo].[iMageList]
WHERE      ([dbo].[iMageList].iMageFile LIKE @iMageName)
ORDER BY    [dbo].[iMageList].iMageNUM DESC

GO


----------------------------------------------------------------
[PF1_1_5_iMageList_DELETE]
----------------------------------------------------------------
CREATE PROCEDURE [PF1_1_5_iMageList_DELETE]
                (@DB_ERR      [INT] OUTPUT,
                 @iMageNUM_1  [INT])

AS

SET @DB_ERR = 0
SET XACT_ABORT OFF

BEGIN TRANSACTION

DELETE [iMageDB].[dbo].[iMageList]
WHERE ([iMageDB].[dbo].[iMageList].[iMageNUM] = @iMageNUM_1)

IF @@ERROR <> 0

   BEGIN
         ROLLBACK TRANSACTION
         SET @DB_ERR = 544
         RETURN
   END

COMMIT TRANSACTION
RETURN

GO


----------------------------------------------------------------
[PF1_1_5_iMageList_iNSERT]
----------------------------------------------------------------
CREATE PROCEDURE [PF1_1_5_iMageList_iNSERT]
                (@DB_ERR           [INT] OUTPUT,
                 @iMageNUM_1       [INT] OUTPUT,
                 @iMagePath_2      [VARCHAR](255),
                 @iMageFile_3      [VARCHAR](255),
                 @iMageSize_4      [INT])

AS

SET @DB_ERR = 0
SET XACT_ABORT OFF

BEGIN TRANSACTION

INSERT INTO [iMageDB].[dbo].[iMageList]
           ([iMagePath],
            [iMageFile],
            [iMageSize])
VALUES
           (@iMagePath_2,
            @iMageFile_3,
            @iMageSize_4)

IF @@ERROR <> 0

   BEGIN
         ROLLBACK TRANSACTION
         SET @DB_ERR = 541

         RETURN
   END

SET @iMageNUM_1 = (SELECT MAX([dbo].[iMageList].iMageNUM) FROM [iMageDB].[dbo].[iMageList])

COMMIT TRANSACTION
RETURN

GO
----------------------------------------------------------------


----------------------------------------------------------------
[T-SQL]-[Data Insert]
----------------------------------------------------------------
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'CostumePlay_001.jpg',  34511)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'CostumePlay_002.jpg',  83316)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'CostumePlay_003.jpg',  95997)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'CostumePlay_004.jpg', 192613)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'CostumePlay_005.jpg',  33858)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'CostumePlay_006.jpg',  67318)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'CostumePlay_007.jpg',  64452)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'imgGirl_001.jpg', 224121)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'imgGirl_002.jpg',  58777)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'imgGirl_003.jpg',  33838)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'imgGirl_004.jpg', 191308)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'imgGirl_005.jpg', 467618)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'imgGirl_006.jpg', 184552)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'imgGirl_007.jpg',  78885)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'jpnGirl_001.jpg',  56778)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'jpnGirl_002.jpg', 123445)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'jpnGirl_003.jpg', 179880)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'jpnGirl_004.jpg',  98878)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'jpnGirl_005.jpg', 105567)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'jpnGirl_006.jpg',  58890)
INSERT INTO iMageList ([iMagePath], [iMageFile], [iMageSize]) VALUES ('iMageList\', 'jpnGirl_007.jpg',  71103)
----------------------------------------------------------------
Posted by gsi
:


-- 하루전 오후 12:00 시 구하는 방법
DECLARE @prevDate varchar(100)
DECLARE @prevDateTime DateTime
SET @prevDate = convert(varchar, getDate(), 112)-1
SET @prevDate = @prevDate
PRINT @prevDate
SET @prevDateTime = cast(@prevDate as DateTime)
PRINT @prevDateTime
PRINT DATEADD(hh, 12, @prevDateTime)

>> 위에걸 최적화 하면 한줄로 되네요. ^^
DATEADD(HOUR,12, CONVERT(DATETIME, CONVERT(CHAR(10), DATEADD(DAY,-1,GETDATE()) ,120)))
Posted by gsi
:


웹에서 실행 파일을 다운로드 할 경우
CGI 오류가 날 경우가 있다.

이때 내가 해결한 방법은 IIS의 웹 속성에서 "실행권한" 을 "스트립트 전용" 으로 해주니까 되었다.
Posted by gsi
:

image = [MenuItemImage itemFromNormalImage:@"image1.png" selectedImage:@"image2.png" target:self selector:@selector(step1:)];
Menu *menu = [Menu menuWithItems:image, nil];
image.position = cpv( -135, -185);
[self addChild: menu z:2];
Posted by gsi
:


가끔은 인생의 목표에 있어서 조금은 다르게 흘러 갈때가 있는거 같다.
돈이 목표가 되고, 잠깐의 단기 목표로 인한 결정으로 인해서
인생의 틀어짐이 생기는거 같다.

하지만 이 틀어짐이 얼마나 멀리 가느냐에 따라서 나의 목표에서 점점 멀어 지고 있는건지
알아 채지 못한다.

이젠 그걸 다시금 되돌릴려고 한다.
단순하게 한달 한달 돈을 벌기 보다, 내가 진정하게 추구 하고자 하는 목표를 위해서.
그걸 위해서 지금의 비 정상적인 종료로 인한 모든 문제는 안고 갈려고 한다.

나쁜넘.. 치사한넘.. 이런 말들은 듣고 그냥 흘러 버리려 한다.
Posted by gsi
:


VS2008에서 .NET 2.0 으로 개발한 웹 서비스를 VS 2003에서 연동이 가능한데요.
아래의 이미지 처럼 "웹 참조 추가"를 통해서 연동이 가능합니다.


정상적으로 연동이 된다면 아래의 화면 처름 보여지게 됩니다.


하지만 아래와 같은 오류가 날때가 있어요.


위의 내용처럼 오류가 난걸 확인해 봤더니..
해당 폴더의 machine.config 의 내용을 보니
<system.data><DbProviderFactories><add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" /></DbProviderFactories></system.data>
위와 같은 구문이 보였습니다.

헉.. SQLite 라는걸 설치를 하면 여기에 추가 되는걸 이제야 알았네요.. -.-

그래서 이 부분을 삭제를 했습니다.
그리고 나서 프로젝트를 닫고 새로 연 다음에 "웹 참조 추가"를 누르면 정상적으로 되는걸 확인할 수 있습니다.
Posted by gsi
:


sqlite3 의 쿼리중에서 select 에서 랜덤하게 뿌리는게 없는줄 알았다. ㅋ.

select * from s1 order by random()

이 쿼리를 사용하면 랜덤하게 출력할 수 있다.
Posted by gsi
:



VC++ 2008을 작업 하다 보면 다른 pc에서 이런 오류 메시지를 종종 보게 된다.
이때 해결 방법은 몇가지로 나눠 진다.

1. DLL을 같이 배포
  - C:\Program Files\Microsoft Visual Studio 9.0\VC\redist 폴더 안에 있는 debug, release 의 내용을 복사해서 같이 배포 한다.
  - 사실 이렇게 해봤지만. 되지 않을때가 많다.

2. 배포 패키지를 사용
  - 어떤 개발툴(2005, 2008) 둘중에 하나를 쓰게 되는데요. 이때 선택해서 배포 패키지를 깔아서 써야 한다.




  - 위의 3개 중에서 내가 테스트 할때는 2008로 개발했을때인데.. 이때 sp1 빼고 2008 배포 패키지만 깔아도 될때도 있었다.

Tip :
  - 컴파일 할때 보면 "다중 스레드 디버그 DLL", "다중 스레드 디버그" 두개가 실행파일의 dll 관계를 보면 좀 틀려 보이긴 한다. 어쩔땐 이걸 해결하면 될때도 있다.. 쩝.. 너무 귀찮다.

[아래 화면은 Tip에 적어 놓은, 걸 Depends로 찍어 본것..]
Posted by gsi
:

s1.sqlitedb 를 하나 제작했습니다.

그리고 나서 xcode의 resource에 추가를 했습니다.
그리고 아래와 같은 코드를 이용해서 프로그램을 짜주었습니다.

-(void) readAnimalsFromDatabase {

// Setup the database object

sqlite3 *database;

// Init the animals Array

// animals = [[NSMutableArray alloc] init];

// Open the database from the users filessytem

if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK) {

// Setup the SQL Statement and compile it for faster access

NSString* sqlStatement = [NSString stringWithFormat:@"select * from s1"];

sqlite3_stmt *compiledStatement;

if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) {

// Loop through the results and add them to the feeds array

while(sqlite3_step(compiledStatement) == SQLITE_ROW) {

int idx = sqlite3_column_int( compiledStatement, 0 );

int level = sqlite3_column_int( compiledStatement, 1 );

int c1 = sqlite3_column_int( compiledStatement, 2 );

int c2 = sqlite3_column_int( compiledStatement, 3 );

int c3 = sqlite3_column_int( compiledStatement, 4 );

// Create a new animal object with the data from the database

// Animal *animal = [[Animal alloc] initWithName:aName description:aDescription url:aImageUrl];

// Add the animal object to the animals Array

// [animals addObject:animal];

// [animal release];

}

}

else

{

NSString* msg = [[NSString alloc] initWithFormat:@"%s", sqlite3_errmsg( database )];

NSLog( @"Failed to open database with message '%s'.", sqlite3_errmsg( database ) );

}

// Release the compiled statement from memory

sqlite3_finalize(compiledStatement);

}

sqlite3_close(database);

}

** 연동 방법에 대해서는 따로 적지를 않았습니다.


이렇게 작업 후에 테스트를 해보니 이상한 결과가 나오더군요.

if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement,NULL) == SQLITE_OK)

여기 코드에서 "실패"가 떨어 지더라구요.
그래서 위의 코드에서 보는 msg라는 내용에 글자를 찍어 보면

no such table s1 이라고 나오게 됩니다.

그래서 과연 이 파일이 어디 있나 찾아 봤더니 컴파일 되고 빌드 되면서
해당 응용 프로그램의 document에 하나 생기더군요 하지만 사이즈가 0으로 나오더라구요.

그래서 다른 소스들을 보니 아래의 메소드를 적용해주는걸 보았습니다.

-(void) checkAndCreateDatabase{

// Check if the SQL database has already been saved to the users phone, if not then copy it over

BOOL success;

// Create a FileManager object, we will use this to check the status

// of the database and to copy it over if required

NSFileManager *fileManager = [NSFileManager defaultManager];

// Check if the database has already been created in the users filesystem

success = [fileManager fileExistsAtPath:[self dataFilePath]];

// If the database already exists then return without doing anything

if(success) return;

// If not then proceed to copy the database from the application to the users filesystem

// Get the path to the database in the application package

NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kFilename];

// Copy the database from the package to the users filesystem

[fileManager copyItemAtPath:databasePathFromApp toPath:[self dataFilePath] error:nil];

[fileManager release];

}


위의 코드를 수행하게 되면 document에 데이터가 없다면 복사를 수행하라는 의미의 코드인듯 합니다.( 사실 이 부분은 아직 잘 모름 )


그래서 위의 함수를 적용 및 호출을 아래와 같이 해주니까.

제대로 데이터가 불러와 지더군요.


- (id) init

{

if (self = [super init])

{

touchPos = CGPointMake(0, 0);

gameState = kLogo;

logoBack = [[LogoBack alloc] init];

// Execute the "checkAndCreateDatabase" function

[self checkAndCreateDatabase];

// Query the database for all animal records and construct the "animals" array

[self readAnimalsFromDatabase];

}

return self;

}


위의 내용에 대해서 실제적인 코드는 여기 압축을 해서 올리지 못하지만,

sqlite3의 내용을 조금 숙지 하셨다면 금방 이해 하시리라 믿습니다. ^^


이거 가지고 조금 삽질을 했네요.

다행이 이 코드를 보면서 다른 면을 보게 되서 더 기쁘네요 ^^

Posted by gsi
:


기본 DB를 만들면 sqlite는 idx등의 고유번호를 자동증가가 안되는거 같다.

그래서 아래와 같이 Execute SQL에서 아래와 같은 쿼리를 통해서
값을 처리 해야 한다.


위와 같이 쿼리를 해서 "Exeture Query" 를 누른다.

위와 같이 s1 이란 것과 "sqlite_sequence" 가 생기게 된다.

Posted by gsi
:

Texture2DEx2.h
-------------------------------

#import <Foundation/Foundation.h>

#import "Texture2D.h"


@interface Texture2DEx2 : Texture2D {

CGPoint tileSize;

CGPoint frameSize;

int curIndex;

int Delay;

int Tick;

}


@property CGPoint tileSize;

@property CGPoint frameSize;

@property int curIndex;

@property int Delay;

@property int Tick;


- (void) TileSize:(CGPoint)ts FrameSize:(CGPoint)fs Delay:(int)delay;

- (void) drawAtPointTest:(CGPoint)point;


@end



Texture2DEx2.m
-------------------------------

#import "Texture2DEx2.h"



@implementation Texture2DEx2


@synthesize tileSize;

@synthesize frameSize;

@synthesize curIndex;

@synthesize Delay;

@synthesize Tick;


- (void) TileSize:(CGPoint)ts FrameSize:(CGPoint)fs Delay:(int)delay

{

self.tileSize = ts;

self.frameSize = fs;

self.Delay = delay;

self.Tick = 0;

}


- (void) drawAtPointTest:(CGPoint)point 

{

if( Tick > Delay )

{

Tick = 0;

curIndex++;

if( curIndex >= frameSize.x )

{

curIndex = 0;

}

}

Tick++;

GLfloat leftTc = tileSize.x * curIndex / _width;

GLfloat rightTc = tileSize.x * (curIndex+1) / _width;

GLfloat coordinates[] = { leftTc, _maxT,

rightTc, _maxT,

leftTc, 0,

rightTc, 0 };

// 넓이와 높이는 타일의 사이즈로 교체

GLfloat width = tileSize.x,

height = tileSize.y;

GLfloat vertices[] = { -width / 2 + point.x, -height / 2 + point.y, 0.0,

width / 2 + point.x, -height / 2 + point.y, 0.0,

-width / 2 + point.x, height / 2 + point.y, 0.0,

width / 2 + point.x, height / 2 + point.y, 0.0 };

glBindTexture(GL_TEXTURE_2D, _name);

glVertexPointer(3, GL_FLOAT, 0, vertices);

glTexCoordPointer(2, GL_FLOAT, 0, coordinates);

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

}


@end


/////////////////

Texture2DEx2 *bluePlaneEx;


@property (nonatomic, retain) Texture2DEx2 *bluePlaneEx;



if (bluePlaneEx == nil) {

self.bluePlaneEx = [[Texture2DEx2 alloc] initWithImage: [UIImage imageNamed:@"bluePlane2.png"]];

glBindTexture(GL_TEXTURE_2D, sprite.name);

// 타일 사이즈, 이미지 내부 프레임 개수, 딜레이 타임(호출타임)

[self.bluePlaneEx TileSize:CGPointMake(63.0, 55.0) FrameSize:CGPointMake(3, 1) Delay:10];

[bluePlaneEx drawAtPointTest:CGPointMake(Pos.x, Pos.y)];



Posted by gsi
: