Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, October 7, 2009

Thursday, August 6, 2009

CS programming with C++, C#

C++ 이랑 C# 이랑 client - server 프로그래밍을 할 때,
When we are programming a client-server application by C++ and C#,

예를 들면 서버는 C++, 클라는 C#. 또는 그 반대로.
For example, servers written by C++, clients written by C#. or vice versa.

신경써야 할 부분이 공통 자료형과 열거형이다.
One thing we should keep in mind, common data structure and enumeration.

공통 자료형과 열거형을 따로 분리해서 하나로 만들지 않으면
If we didn't create a separated method for common data structure and enumeration,

양 쪽에 모두 존재하게 되는데, 이런 경우에는 잠재적 위험성이 내포되어 있다.
Two projects (client and server) need to have it individually, then there is a potential dangerous thing.

특히 시간이 지날 수록, 작업자가 많아서 머지가 많아질 수록.
In particular, as time goes by, getting more programmers, getting more counts for merge,

어느 순간 패킷 번호가 달라져 있다던지. 구조체 멤버변수의 순서가 바껴있다던지.
It can silently happen to change a packet number, or mixed order of member variables in a structure.

디버깅하기 아주 괴로운 상황에 처할 수 있다.
This makes a debugging hell.

예전에 흥배님께서 python 으로 C++ 코드를 파싱해서 C# 쪽 패킷 번호와 구조체를 생성하는 툴을 사용하셨다는데
A few months ago, Mr. 흥배 used a tool which parses C++ codes, then creates common data for C# by python.

좋은 방법이긴 하지만, 뭔가 확실하게 integrated 된 방법은 없을까 하는 생각도 든다.
It's a good way. But, I think there are some full integrated ways. maybe.

좋은 idea 있으신 분은 넌지시 알려주시면 정말 감사하겠습니다.
It would be really appreciated if you let me know any ideas.

Wednesday, April 22, 2009

.Net framework for Linux

Mono.

I'm not sure whether this project is really useful or not.
I don't think there are many programmers who use .Net framework in linux.

But, .Net framework is very powerful, reliable and soft.
This project is a challenge. 
There are brave programmers who like a challenge.
They will prove it is useful or not. :)

Thursday, March 26, 2009

UAC refereneces (C#, .NET)

UAC (User Account Control)


How to set the UAC elevation with C# (.NET)?
1. Create a manifest file looks like below.


2. Adding the manifest to the executable.
tab BuildEvent, in the post-build,
"$(DevEnvDir)..\..\SDK\v2.0\bin\mt.exe" -manifest "$(ProjectDir)$(TargetName).exe.manifest"  –outputresource:"$(TargetDir)$(TargetFileName)";#1
You can change the paths to make a build possible.

Local User, Application Directory
The directory of a local user and an application directory is different from Windows Vista and Windows XP.
Windows Vista/Windows Server 2008: %LocalAppData%\Microsoft\Team Foundation
Windows Server 2003 / Windows XP: %UserProfile%\Local Settings\Application 

So, we can use environment values to get them.
Environment.GetEnvironmentVariable("LOCALAPPDATA"); // Get an application data path
Environment.GetEnvironmentVariable("USERPROFILE"); // Get an user directory

OS Version number
Operating systemVersion number
Windows 76.1
Windows Server 2008 R26.1
Windows Server 20086.0
Windows Vista6.0
Windows Server 2003 R25.2
Windows Server 20035.2
Windows XP5.1
Windows 20005.0

Summary

Other References





Friday, December 5, 2008

C# Client Network Library

C# 하면서 만들었던 거의 기억보존용.

아직 테스트 중이고, 살펴보면 허술한 부분도 많지만
뭐 간단하게 동작하는 데는 큰 문제 없음.

주요 특징 :
- Async 를 걸고 IOCP 에서 return 받는 간단한 구조.
- 방식은 proactor 이지만 thread 가 하나이기 때문에 뭐라 지칭하긴 그렇고, 그냥 비동기 콜임. :)
- boost::asio 를 많이 모방했음. 그래서 함수 이름이나, packet 을 읽는 방식이 거의 같음. -0-;
- connect 는 sync, send/recv 는 async.

Packet type - namespace Protocol

namespace Protocol
{
public struct packet_header
{
public System.UInt16 index_;
public System.UInt16 body_length_;
}

public struct packet
{
public packet_header h_;
public System.Byte[] data_;
}

public class packet_size
{
public static readonly int header_size;
public static readonly int max_body_size;
public static readonly int max_packet_size;

static packet_size()
{
header_size = Marshal.SizeOf(typeof(packet_header));
max_body_size = 1024;
max_packet_size = header_size + max_body_size;
}
}
}


Network Library - namespace NetworkLib

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;

using Protocol;

namespace network_lib
{
public class packet_args : EventArgs
{
private packet p_;
public packet_args(packet p)
{
p_ = p;
}

public packet data
{
get { return p_; }
}
}
public delegate void packet_event(object sender, packet_args p);

class packet_parse
{
public event packet_event e_;
public void do_packet_parse(packet p)
{
if (e_ != null)
e_(this, new packet_args(p));
}
}

public class client_session
{
#region Private Variables

private string ip_;
private string port_;
private Socket client_socket_;

private packet read_packet_;
private Byte[] read_buffer_;
private Byte[] write_buffer_;

private IAsyncResult result_;
private AsyncCallback cb_async_read_body_;
private AsyncCallback cb_handle_read_;
private AsyncCallback cb_handle_write_;

private packet_parse event_packet_;

#endregion

#region Constructors

public client_session()
{
init();
}

public client_session(string ip, string port)
{
ip_ = ip;
port_ = port;

init();
}

#endregion

#region Properties

public string IP
{
get { return ip_; }
set { ip_ = value; }
}

public string Port
{
get { return port_; }
set { port_ = value; }
}

public bool connected
{
get { return (client_socket_ != null) ? client_socket_.Connected: false; }
}

#endregion

#region Public Methods

public void add_packet_event(packet_event h)
{
event_packet_.e_ += h;
}

public void connect()
{
try
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ip_), System.Convert.ToUInt16(port_));
client_socket_ = new Socket(System.Net.Sockets.AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Stream,
System.Net.Sockets.ProtocolType.Tcp);
client_socket_.Connect(ip);
if (client_socket_.Connected)
do_async_read();
}
catch (SystemException se)
{
MessageBox.Show(se.Message);
}
}

public void disconnect()
{
if (connected)
client_socket_.Disconnect(false);
}

public void do_async_read()
{
try
{
// do_async_read_head
result_ = client_socket_.BeginReceive(read_buffer_,
0,
packet_size.header_size,
SocketFlags.None,
cb_async_read_body_,
read_buffer_);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

public void do_async_write(packet p)
{
try
{
packet_header heaer = p.h_;
System.Byte[] buffer = raw_serialize_ex(heaer);
buffer.CopyTo(write_buffer_, 0);
p.data_.CopyTo(write_buffer_, packet_size.header_size);

// do_async_write
result_ = client_socket_.BeginSend(write_buffer_,
0,
packet_size.header_size + p.h_.body_length_,
SocketFlags.None,
cb_handle_write_,
write_buffer_);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

// copied from group.google.com
public object raw_deserialize_ex(byte[] rawdatas, Type anytype)
{
int rawsize = Marshal.SizeOf(anytype);
if (rawsize > rawdatas.Length)
return null;
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
object retobj = Marshal.PtrToStructure(buffer, anytype);
handle.Free();
return retobj;
}

// copied from group.google.com
public byte[] raw_serialize_ex(object anything)
{
int rawsize = Marshal.SizeOf(anything);
byte[] rawdatas = new byte[rawsize];
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
Marshal.StructureToPtr(anything, buffer, false);
handle.Free();
return rawdatas;
}

#endregion

#region Private Methods

private void init()
{
client_socket_ = null;

cb_async_read_body_ = new AsyncCallback(do_async_read_body);
cb_handle_read_ = new AsyncCallback(cb_handle_read);
cb_handle_write_ = new AsyncCallback(cb_handle_write);

read_packet_.data_ = new System.Byte[packet_size.max_body_size];
read_buffer_ = new System.Byte[packet_size.max_packet_size];
write_buffer_ = new System.Byte[packet_size.max_packet_size];

event_packet_ = new packet_parse();
}

private void do_async_read_body(IAsyncResult r)
{
try
{
int bytes_transferred = client_socket_.EndReceive(r);
if (bytes_transferred == 0)
{
// normal close
return;
}

if (bytes_transferred != packet_size.header_size)
{
MessageBox.Show(" !Error - invalid received header size : " + bytes_transferred);
return;
}

packet_header header;
System.Byte[] header_buffer = new System.Byte[packet_size.header_size];
System.Buffer.BlockCopy(read_buffer_, 0, header_buffer, 0, packet_size.header_size);
header = (packet_header)raw_deserialize_ex(header_buffer, typeof(packet_header));

read_packet_.h_.index_ = header.index_;
read_packet_.h_.body_length_ = header.body_length_;

// do_async_read_body
result_ = client_socket_.BeginReceive(read_buffer_,
packet_size.header_size,
header.body_length_,
SocketFlags.None,
cb_handle_read_,
read_buffer_);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

private void cb_handle_read(IAsyncResult r)
{
try
{
int bytes_transferred = client_socket_.EndReceive(r);
if (bytes_transferred > packet_size.max_body_size)
{
MessageBox.Show(" !Error - invalid received body size : " + bytes_transferred);
return;
}

System.Buffer.BlockCopy(read_buffer_, packet_size.header_size, read_packet_.data_, 0, bytes_transferred);

// parse packet
event_packet_.do_packet_parse(read_packet_);

// do_async_read
do_async_read();
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

private void cb_handle_write(IAsyncResult r)
{
int bytes_transferred = client_socket_.EndSend(r);
string msg = "packet has been sent. bytes : " + bytes_transferred + "\n";
}

#endregion
}
}

Thursday, November 27, 2008

C# 에서 파일 읽기

C# 에서 파일 읽으려고 할 때는, 아주 다양한 방법을 사용할 수 있다.

File 클래스를 사용할 때도,
Open, OpenRead, ReadAllBytes, ReadAllLines, ReadAllText...

FileStrea 클래스를 사용할 때도,
Read, ReadByte...

이렇게 다양한 방법으로 읽어올 수 있는데,



// Open the stream and read it back.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);

while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}

저 링크에 있는 예제처럼은 사용하지 말아야 한다.

이유는 잘 모르겠지만 (내가 잘못한 것일 수 있음. 사실 이 확률이 젤 높음 -0-)
파일을 끝까지 못 읽는 문제가 발생한다.
왠지는 모르겠다고 -_-;;;

그냥 File.ReadAllBytes 로 읽어들이거나,
FileStream 의 ReadBytes 를 사용하는 것이 좋을 듯 하다.



using (FileStream fsSource = new FileStream(pathSource,
FileMode.Open, FileAccess.Read))
{

// Read the source file into a byte array.
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = (int)fsSource.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

// Break when the end of the file is reached.
if (n == 0)
break;

numBytesRead += n;
numBytesToRead -= n;
}
}

이 링크에 있는 예제는 문제 없이 잘 동작한다.

Wednesday, November 12, 2008

C#, Managed C++ 참고 자료

C# 레퍼런스 모음.

C/C++ 을 하다가 C# 으로 추가 개발을 하려는 사람에게 꼭 필요한 것들을 모아봤음.
직접 해보면서 삽질한 내용임.

C# eBook
http://www.bestsoftware4download.com/software/t-free-c-school-ebook-download-llijghlw.html
http://www.pnasoft.com/archive/2008/01/11/pro-csharp-2008-and-the-net-3-5-platform-4th-edition.aspx

C++ / CLI, Managed C++ eBook
http://int6.net/ebook/Expert.Cpp.Cli.NET.pdf

C# memcpy (링크를 까먹어서 -_- 코드로 대체)


// copied from group.google.com
public object raw_deserialize_ex(byte[] rawdatas, Type anytype)
{
int rawsize = Marshal.SizeOf(anytype);
if (rawsize > rawdatas.Length)
return null;
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
object retobj = Marshal.PtrToStructure(buffer, anytype);
handle.Free();
return retobj;
}

// copied from group.google.com
public byte[] raw_serialize_ex(object anything)
{
int rawsize = Marshal.SizeOf(anything);
byte[] rawdatas = new byte[rawsize];
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
Marshal.StructureToPtr(anything, buffer, false);
handle.Free();
return rawdatas;
}


Block Copy
http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx

Byte[] to String
System.Text.Encoding.UTF8.GetString(...);

String to Byte[]
ASCIIEncoding.UTF8.GetBytes(...);

[Managed C++] System::String^ <-> std::string
http://www.codeguru.com/forum/showthread.php?p=1722705#post1722705

UI Invoke (다른 Thread 에서 ui 를 업데이트 하려면 invoke 를 거쳐가야함.)
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.invoke.aspx
i.e.) this.Invoke(new _set_btn_enable_delegate(_set_btn_enable));

Property Grid
http://msdn.microsoft.com/en-us/library/aa302326.aspx

XML Serializer
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

CRC32, MD5, SHA1
http://www.vbaccelerator.com/home/net/code/Libraries/CRC32/article.asp
http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1cryptoserviceprovider.aspx

Native C++ <-> Unmanaged C++ <-> C#
http://sj21.wo.to/tt/483
http://sj21.wo.to/tt/484
http://blogs.msdn.com/junfeng/archive/2006/05/20/599434.aspx

Application 정보는 System.Application
Environment 정보는 System.Environment

다른 Application 실행시키려면
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx


일단 이정도.

위의 내용만 잘 숙지해도, 기본적인 개발은 할 수 있음.