c# using문 입니다.

MSDN을 인용하여 using문을 설명 드리자면 IDisposable 객체의 올바른 사용을 보장하는 편리한 구문을 제공해 주는 것이 바로 using문 입니다.

File및 Font와 같은 클래스들은 관리되지 않는 리소스에 액세스 하는 대표적인 클래스들입니다. 
File및 Font와 같은 클래스들은 관리되지 않는 리소스에 액세스 하는 대표적인 클래스들입니다.
File및 Font와 같은 클래스들은 관리되지 않는 리소스에 액세스 하는 대표적인 클래스들입니다.
File및 Font와 같은 클래스들은 관리되지 않는 리소스에 액세스 하는 대표적인 클래스들입니다.
File및 Font와 같은 클래스들은 관리되지 않는 리소스에 액세스 하는 대표적인 클래스들입니다.
File및 Font와 같은 클래스들은 관리되지 않는 리소스에 액세스 하는 대표적인 클래스들입니다.

이 말은 해당 클래스들을 다 사용한 후에는 적절한 시기에 해제(Dispose)하여 해당 리소스(자원)을 다시 반납해야 하는 것입니다.

프로그래머가 프로젝트를 하면서 매번 관리되지 않는 리소스에 액세스 하는 클래스들을 체크하여 Dispose 하는 것을 많은 시간과 실수를 야기합니다..이때 바로 using문을 이용하면 해당 리소스 범위를 벗어나게 되면 자동으로 리소스(자원)을 해제(Dispose)하여 관리를 쉽게 도와 줍니다.

Using문 사용한 경우

using (Font font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

Using문 사용하지 않은 경우

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

Using문 사용한 경우

void Create()
{
int result;
using (StreamReader rdr = new StreamReader("CreateDB.sql"))
{
string sql = rdr.ReadToEnd();
SQLiteCommand cmd  = new SQLiteCommand(sql, Conn);

try
{
result = cmd.ExecuteNonQuery();
}
catch(SQLiteException ae)
{
Console.WriteLine(ae.ToString());
}
}
}

using문을 사용하면 프로그래머가 일일이 Dispose를 해주지 않아도 되고 로직도 간단해지는 것을 확인 하실 수 있습니다.







/* DLL등록후(D:\tmp\console\sqlite3.dll) PATH설정후 컴파일&실행 

>basic compile
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" sql11.cs
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" sql11.cs
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" sql11.cs

>error message
처리되지 않은 예외: System.IO.FileNotFoundException: 파일이나 어셈블리 'System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139' 또는 여기에 종속되어 있는 파일이나 어셈블리 중 하나를 로드할 수 없습니다. 지정된 파일을 찾을 수 없습니다.
   위치: SQLiteManageConsole..ctor()
   위치: Program.Main()
   
>solution
파일이나 어셈블리 ‘System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139’ 또는 여기에 종속되어 있는 파일이나 어셈블리 중 하나를 로드할 수 없습니다. 프로그램을 잘못된 형식으로 로드하려고 했습니다.
이런 오류가 발생하는 경우는 컴파일 환경이 64bit로 되어 있어서 발생합니다.
구성 관리자로 이동을 해서 플랫폼을 Any CPU에서 x86으로 바꾸면 정상적으로 동작합니다.

>platform addition
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" /platform:"x86" sql11.cs
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" /platform:"x86" sql11.cs
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" /platform:"x86" sql11.cs
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" /platform:"x86" sql11.cs
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" /platform:"x86" sql11.cs
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" /platform:"x86" sql11.cs
csc.exe /r:"C:\Program Files (x86)\SQLite.NET\bin\System.Data.SQLite.dll" /platform:"x86" sql11.cs

>success compile
*/

using System;
using System.IO;
using System.Data.SQLite;


class Program
{
public static void Main()
{
SQLiteManageConsole nm = new SQLiteManageConsole();
nm.running();
}
}

class SQLiteManageConsole
{
//definition
const int sqlCmdLine=1;

//variables
SQLiteConnection Conn=null;

void SQLiteSys____Open()
{
Conn = new SQLiteConnection("Data Source=:memory:;Version=3;");
Conn.Open();
}
void SQLiteSys____Create()
{
int result;
using (StreamReader rdr = new StreamReader("D:\tmp/console/CreateDB.sql"))
{
string sql = rdr.ReadToEnd();
SQLiteCommand cmd  = new SQLiteCommand(sql, Conn);

try
{
result = cmd.ExecuteNonQuery();
}
catch(SQLiteException ae)
{
Console.WriteLine(ae.ToString());
}
}
}
void SQLiteSys____Insert()
{
string[] sql = new string[]
{
"insert into imt_mst_resource(resid, hostid, restype, resname) values('100101', '1001', 'linux', 'iuli_linux');",
};
int kk;

for(kk=0; kk<sqlCmdLine; kk++)
{
SQLiteCommand cmd  = new SQLiteCommand(sql[kk], Conn);

try
{
int result = cmd.ExecuteNonQuery();
}
catch(SQLiteException ae)
{
Console.WriteLine(ae.ToString());
}
}
}
void SQLiteSys____Select()
{
string sql = "select resid, hostid, restype, resname from imt_mst_resource;";
SQLiteCommand cmd  = new SQLiteCommand(sql, Conn);
SQLiteDataReader rdr = cmd.ExecuteReader();

int kk=1;

while(rdr.Read())
{
try
{
string resid   = rdr["resid"].ToString();
string hostid  = rdr["hostid"].ToString();
string restype = rdr["restype"].ToString();
string resname = rdr["resname"].ToString();

Console.WriteLine(">>>[" + kk.ToString("0000") + "]    :" + resid + "/" + hostid + "/" + restype + "/" + resname);
kk++;
}
finally
{
//
}
}
rdr.Close();
}
public void running()
{
SQLiteSys____Open();
SQLiteSys____Create();
SQLiteSys____Insert();

SQLiteSys____Select();
}
}







 

/*1. SQLite를 설치한(Install) 후에
2. SQLite DLL을 프로젝트에 참조한 후에*/

using System;
using System.Data.SQLite;

class Program
{
public static void Main()
{
SQLiteManageCls nm = new SQLiteManageCls();
nm.running();
}
}

class SQLiteManageCls
{
string connectionString = "Data Source=:memory:"; 
SQLiteConnection sqliteConnection = null; 
SQLiteCommand sqliteCommand = null;

public void running()
{
try 

sqliteConnection = new SQLiteConnection(connectionString); 
sqliteConnection.Open(); 
string sql = "SELECT SQLITE_VERSION()"; 
sqliteCommand = new SQLiteCommand(sql, sqliteConnection); 
string version = sqliteCommand.ExecuteScalar().ToString(); 
Console.WriteLine("SQLite version : {0}", version); 
}
catch(SQLiteException sqliteException) 

Console.WriteLine("Error: {0}", sqliteException.ToString()); 

finally 
{
if(sqliteCommand != null) { sqliteCommand.Dispose(); }
if(sqliteConnection != null) 
{
try 

sqliteConnection.Close(); 

catch(SQLiteException sqliteException) 

Console.WriteLine("Closing connection failed."); 
Console.WriteLine("Error: {0}", sqliteException.ToString()); 

finally 

sqliteConnection.Dispose(); 
}
}
}
}
}

using System;  
using System.Collections.Generic;  
using System.Net;  
using System.Net.Sockets;  
using System.IO;  
using System.Text;  
 
namespace FileTransfer  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            // Listen on port 31234    
            TcpListener tcpListener = new TcpListener(IPAddress.Any, 31234);  
            tcpListener.Start();  
 
            Console.WriteLine("Server started");  
 
            //Infinite loop to connect to new clients    
            while (true)  
            {  
                // Accept a TcpClient    
                TcpClient tcpClient = tcpListener.AcceptTcpClient();  
 
                Console.WriteLine("Connected to client");  
 
                StreamReader reader = new StreamReader(tcpClient.GetStream());  
 
                // The first message from the client is the file size    
                string cmdFileSize = reader.ReadLine();  
 
                // The first message from the client is the filename    
                string cmdFileName = reader.ReadLine() + "_1";  
 
                int length = Convert.ToInt32(cmdFileSize);  
                byte[] buffer = new byte[length];  
                int received = 0;  
                int read = 0;  
                int size = 1024;  
                int remaining = 0;  
 
                // Read bytes from the client using the length sent from the client    
                while (received < length)  
                {  
                    remaining = length - received;  
                    if (remaining < size)  
                    {  
                        size = remaining;  
                    }  
 
                    read = tcpClient.GetStream().Read(buffer, received, size);  
                    received += read;  
                }  
 
                // Save the file using the filename sent by the client    
                using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))  
                {  
                    fStream.Write(buffer, 0, buffer.Length);  
                    fStream.Flush();  
                    fStream.Close();  
                }  
 
                Console.WriteLine("File received and saved in " + Environment.CurrentDirectory);  
            }  
        }  
    }  

using System;  
using System.Collections.Generic;  
using System.Net;  
using System.Net.Sockets;  
using System.IO;  
using System.Text;  
 
namespace FileTransferClient  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            try  
            {  
                Console.WriteLine("Please enter a full file path");  
                string fileName = Console.ReadLine();  
 
                TcpClient tcpClient = new TcpClient("127.0.0.1", 31234);  
                Console.WriteLine("Connected. Sending file.");  
 
                StreamWriter sWriter = new StreamWriter(tcpClient.GetStream());  
 
                byte[] bytes = File.ReadAllBytes(fileName);  
 
                sWriter.WriteLine(bytes.Length.ToString());  
                sWriter.Flush();  
 
                sWriter.WriteLine(fileName);  
                sWriter.Flush();  
 
                Console.WriteLine("Sending file");  
                tcpClient.Client.SendFile(fileName);  
 
            }  
            catch (Exception e)  
            {  
                Console.Write(e.Message);  
            }  
 
            Console.Read();  
        }  
    }  

 

Other Application기동을 클라이언트에서 하도록 수정(Other Application프로그램이 뛰워져 있지 않을경우에)
Other Application기동을 클라이언트에서 하도록 수정(Other Application프로그램이 뛰워져 있지 않을경우에)

____handle_mmm = FindWindow(null, "CONSOLE.TRIS");
if(____handle_mmm==IntPtr.Zero)
{
Console.WriteLine("Time:[" + DateTime.Now.ToString() + "]::" + "FindWindow(CONSOLE.TRIS) FAIL!!, Try Execute CONSOLE.TRIS Application!!");

Process process = Process.Start("____rcv.exe");

DateTime endTime = DateTime.Now.AddMinutes(1);

/*
System.Threading.Thread.Sleep(1000);
____handle_mmm = FindWindow(null, "CONSOLE.TRIS");
if(____handle_mmm==IntPtr.Zero) 
{
Console.WriteLine("Time:[" + DateTime.Now.ToString() + "]::" + "FindWindow(CONSOLE.TRIS) FAIL!!, Try Execute CONSOLE.TRIS Application!!");
}
*/

while(true)
{
if((____handle_mmm = FindWindow(null, "CONSOLE.TRIS"))==IntPtr.Zero)
{
System.Threading.Thread.Sleep(10);
}
else break;

if(endTime<DateTime.Now)
{
index=100;
break;
}
}
if(index==100) return;
}

 

 

____snd.cs
0.00MB

/*2개의 Application이 동작한다. 2개의 Application이 Data를 Communication할때에 사용하는 방식이다.
1. Console에서 Key를 동작하여, 다른 Application으로 SendMessage(Text)한다. 일명 조정
2. 다른 Application에서는 WndProc(override frm)에서 WM_COPYDATA를 통해서 데이타를 받은다음에 
Key에 따라서 동작한다.
3. 억지로 말을 붙이자면, 한쪽방향으로의 클라이언트,서버의 관계이다.*/

>주의할점은 Tris Server Frm(No Key) 의 Application의 Handle이 반드시 일단 존재해야 한다.

____snd.cs
0.00MB

 

____rcv.cs
0.01MB

 

/*Data communication between Proesses!!*/

Windows OS
프로세스간 Window Handle 공유를 통한 SendMessage & WndProc(WM_COPYDATA)

참조)
SendMessage/FindWindow/Snd/Rcv Str :: 석수코딩교육 (tistory.com)

Linux & Unix OS
1) 프로세스간 Message Queue 공유를 통한 Message Send & Recv
2) 프로세스간 Semaphor & Shared Meory 공유를 통한 Message Send & Recv(비추)

+ Recent posts