using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterfaceUnderstand
{
    interface IPower
    {
        void action();
    }

    interface IBoot
    {
        void action();
    }

    class NoteBook : IPower, IBoot
    {
        void IPower.action()
        {
            Console.WriteLine("NoteBook::IPower.action() 호출.");
        }

        void IBoot.action()
        {
            Console.WriteLine("NoteBook::IBoot.action() 호출.");
        }
    }

class DesktopPC : IPower, IBoot
    {
        void IPower.action()
        {
            Console.WriteLine("DesktopPC::IPower.action() 호출.");
        }

        void IBoot.action()
        {
            Console.WriteLine("DesktopPC::IBoot.action() 호출.");
        }
    }

class Program
{
static void Main(string[] args)
        {
/*NoteBook을 Handling*//*NoteBook을 Handling*//*NoteBook을 Handling*/
/*NoteBook을 Handling*//*NoteBook을 Handling*//*NoteBook을 Handling*/
            NoteBook mc = new NoteBook();
            
            IPower imca = mc;
            imca.action();

            IBoot imcb = mc;
            imcb.action();

/*DesktopPC를 Handling*//*DesktopPC를 Handling*//*DesktopPC를 Handling*/
/*DesktopPC를 Handling*//*DesktopPC를 Handling*//*DesktopPC를 Handling*/
DesktopPC mcc = new DesktopPC();
            
            IPower imcaa = mcc;
            imcaa.action();

            IBoot imcbb = mcc;
            imcbb.action();
        }
}
}



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를 해주지 않아도 되고 로직도 간단해지는 것을 확인 하실 수 있습니다.







/*
싱글톤 패턴(Singleton Pattern)

1. 싱글톤 패턴

애플리케이션이 시작될 때 어떤 클래스가 최초 한번만 메모리를 할당하고(Static) 그 메모리에 인스턴스를 만들어 사용하는 디자인패턴.
생성자가 여러 차례 호출되더라도 실제로 생성되는 객체는 하나고 최초 생성 이후에 호출된 생성자는 최초에 생성한 객체를 반환한다. (자바에선 생성자를 private로 선언해서 생성 불가하게 하고 getInstance()로 받아쓰기도 함)
=> 싱글톤 패턴은 단 하나의 인스턴스를 생성해 사용하는 디자인 패턴이다.
(인스턴스가 필요 할 때 똑같은 인스턴스를 만들어 내는 것이 아니라, 동일(기존) 인스턴스를 사용하게함)

2. 싱글톤 패턴을 쓰는 이유

고정된 메모리 영역을 얻으면서 한번의 new로 인스턴스를 사용하기 때문에 메모리 낭비를 방지할 수 있음
또한 싱글톤으로 만들어진 클래스의 인스턴스는 전역 인스턴스이기 때문에 다른 클래스의 인스턴스들이 데이터를 공유하기 쉽다.
DBCP(DataBase Connection Pool)처럼 공통된 객체를 여러개 생성해서 사용해야하는 상황에서 많이 사용.
(쓰레드풀, 캐시, 대화상자, 사용자 설정, 레지스트리 설정, 로그 기록 객체등)
안드로이드 앱 같은 경우 각 액티비티나 클래스별로 주요 클래스들을 일일이 전달하기가 번거롭기 때문에 싱글톤 클래스를 만들어 어디서나 접근하도록 설계하는 것이 편하기 때문...
+ 인스턴스가 절대적으로 한개만 존재하는 것을 보증하고 싶을 경우 사용.
+ 두 번째 이용시부터는 객체 로딩 시간이 현저하게 줄어 성능이 좋아지는 장점!

3. 싱글톤 패턴의 문제점

싱글톤 인스턴스가 너무 많은 일을 하거나 많은 데이터를 공유시킬 경우 다른 클래스의 인스턴스들 간에 결합도가 높아져 "개방-폐쇄 원칙" 을 위배하게 된다. (=객체 지향 설계 원칙에 어긋남)
따라서 수정이 어려워지고 테스트하기 어려워진다.
또한 멀티쓰레드환경에서 동기화처리를 안하면 인스턴스가 두개가 생성된다든지 하는 경우가 발생할 수 있음
*/

/*
공통데이타 저장변수를 사용시에 필요한부분이다.*/

public class APMMemory
{
private static APMMemory apmMemory;
string ____processid;

public static APMMemory GetInstance
{
get
{
if(apmMemory == null)
{
apmMemory = new APMMemory();
}
return apmMemory;
}
}

public string processid
{
get {return ____processid};
set { ____processid = value;}
}
}

class SampleManage
{
public void running()
{
Console.WriteLine("" + APMMemory.GetInstance.processid);
}
}

class Program
{
public static void Main()
{
APMMemory.GetInstatnce.processid = "999";

SampleManage nm = new SampleManage();
nm.running();
}
}

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

/*c# *.DLL IDE에 추가하기*/

새로운 using 구문을 사용하기 위해서 예를들어서 using System.Data.SQLite;


DLL을 함께 추가해줘야 한다. 

1. Visual Studio(IDE)에서

2. Project 트리에서

3. 참조

4. 참조추가

5. 찾아보기로 해당 DLL을 클릭후에 확인(full path)

빌드후에 정상적으로 실행이 되는지 확인한다.

SQLite을 설치한 후에 C# 프로젝트에서 System.Data.SQLite.dll를 참조한 후 using System.Data.SQLite; 네임스페이스를 참조하면, SQLite의 .NET 클래스들 (예: SQLiteConnection, SQLiteCommand, SQLiteDataReader 등)을 사용할 수 있다.

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

+ Recent posts