Host에 있는 Script file등을 Process.Start로 실행시켜 보자.

 

#region "서버로 접근하여 특정 파일 실행시키기 : ExecuteServerFile"
/// ////////////////////////////////////////////////////////////
/// Makeby : HJKIM@FROM30 200900903
/// FuncName: StartHostFile
/// review : This function can start from server which is USER decide.
/// apply : System.Diagnostics.Process.Start function user method,
/// ////////////////////////////////////////////////////////////
public bool StartHostFile(string strServerFile)
{
// 1. check target
string target=null;
if (strServerFile.Contains("/"))
target = AdjustDir(strServerFile);

string strArgument = string.Format("/c rsh {0} -l {1} {2}", axSinfo.hostname, axSinfo.userid, target);

ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = strArgument;
Process.Start(startInfo);
//System.Diagnostics.Process.Start("cmd.exe",strAgument);

return true;
}
#endregion

 

 

ftp protocol을 이용하여 지정된 host에 파일 업로드 하기(ftp upload)

 

#region "로컬로부터 파일을 업로드 하기 위한 함수 : UploadFile"


/// ////////////////////////////////////////////////////////////
/// Makeby : HJKIM@FROM30 20090828
/// FuncName: DownloadFile
/// review : This function can download the files of server.
/// apply : ftp client download function method,
/// ////////////////////////////////////////////////////////////
public bool UploadFile(string localfile, string targetfile, bool IsfileSizeChk)
{
FileInfo fi = new FileInfo(localfile);
if (fi.Exists != true)
{
string strtemp;
strtemp = string.Format("\"{0}\" File이 존재하지 않습니다. 확인 바랍니다.", localfile);
MessageBox.Show(strtemp, "File Not Exsit!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}

// 1. check target
string target;
if (targetfile.Contains("/"))
{
//treat as a full path
target = AdjustDir(targetfile);
}
else
target = "/" + targetfile;

string URI = "ftp://" + axSinfo.hostname + "/" + target;

// 2. perform copy
System.Net.FtpWebRequest ftp = GetRequest(URI);

// set requeset to download a file in binary mode
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftp.UseBinary = true;

// Notify FTP of the expected size
ftp.ContentLength = fi.Length;

// create byte array to store : ensure at least 1 byte!
const int BufferSize = 2048;
byte[] content = new byte[BufferSize];
int dataRead;

using (FileStream fs = fi.OpenRead())
{
try
{
// open request to send
using (Stream rs = ftp.GetRequestStream())
{
do
{
dataRead = fs.Read(content, 0, BufferSize);
rs.Write(content, 0, dataRead);
} while (!(dataRead < BufferSize));
rs.Close();
}

// local PC로 download가 정상적으로 수행되었는지 file size를 Check한다.
CheckFileStatus(Convert.ToInt32(ftp.ContentLength), fi, IsfileSizeChk);
}
catch (Exception err)
{
string strErrMsg;
strErrMsg = string.Format(@"Window MSG:{0}

[서버 접근이 가능한지 확인 바랍니다.]
[INFORM: Upload file name:{1} IP:{2}, USER ID:{3}]", err.ToString(), target, axSinfo.hostname, axSinfo.userid);
MessageBox.Show(strErrMsg, "Error Information!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
// ensure file closed
fs.Close();
}
}


ftp = null;
return true;
}

#endregion

 

//부수적인 함수들

/// ////////////////////////////////////////////////////////////
/// Makeby : HJKIM@FROM30 20090828
/// FuncName: CheckFileStatus
/// review : This function is compare to "local file" and "server file".
/// apply : etc
/// ////////////////////////////////////////////////////////////
private void CheckFileStatus(int fsize, FileInfo fi, bool IsfileSizeChk)
{
if (IsfileSizeChk == true)
{
string strTemp;
if (fi.Exists == false)
MessageBox.Show("TESTER SIDE에 파일이 존재하지 않습니다. 확인 바랍니다.", "Error Information",
MessageBoxButtons.OK, MessageBoxIcon.Error);
if (fsize != fi.Length)
{
strTemp = string.Format("파일이 정상적으로 다운로드 되지 않았습니다. filesize [{0}] : [{1}]",
fsize, fi.Length);
MessageBox.Show(strTemp, "Error Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}
}


/// Amend an FTP path so that it always starts with
private string AdjustDir(string path)
{
return ((path.StartsWith("/")) ? "" : "/").ToString() + path;
}

//Get the basic FtpWebRequest object with the
//common settings and security
private FtpWebRequest GetRequest(string URI)
{
//create request
FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
//Set the login details
result.Credentials = GetCredentials();
//Do not keep alive (stateless mode)
result.KeepAlive = false;

return result;
}

/// <summary>
/// Get the credentials from username/password
/// </summary>
private System.Net.ICredentials GetCredentials()
{
return new System.Net.NetworkCredential(axSinfo.userid, axSinfo.password);
}

 

 

목표: ftp protocol을 이용하여 지정된 host로부터 파일 다운로드 하여보자.

 

public bool DownloadFile(string sourcefile, string localfile, bool IsfileSizeChk)
{
int fsize=0;
FileInfo fi = new FileInfo(localfile);

// 1. check source
string target;
if (sourcefile.Trim() == "")
{
throw (new ApplicationException("File not Specified!"));
}
else if (sourcefile.Contains("/"))
{
//treat as a full path
target = AdjustDir(sourcefile);
}
else
target = "/" + sourcefile;

string URI = "ftp://" + axSinfo.hostname + "/" + target;

// 2. perform copy
System.Net.FtpWebRequest ftp = GetRequest(URI);

// set requeset to download a file in binary mode
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;

// open request and get response stream
try
{
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
// loop to read & write to file
using (FileStream fs = fi.OpenWrite())
{
try
{
byte[] buffer = new byte[2048];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
fsize +=read;
} while (!(read == 0));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
// catch error and delete file only partially dowmloaded
fs.Close();
// delete target files as it's incomplete
fi.Delete();
throw;
}
}

responseStream.Close();
}
response.Close();

// local PC로 download가 정상적으로 수행되었는지 file size를 Check한다.
CheckFileStatus(fsize, fi, IsfileSizeChk);
}
}
catch (WebException err)
{
string strErrMsg;
strErrMsg = string.Format(@"Window MSG:{0}

파일이 존재하는지 확인해 주십시요]
Download file name:{1} IP:{2}, USER ID:{3}]", err.ToString(),target, axSinfo.hostname, axSinfo.userid);
MessageBox.Show(strErrMsg,"Error Information!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}


ftp = null;

return true;
}

 

file이 존재하는지 확인한다.

private void CheckFileStatus(int fsize, FileInfo fi, bool IsfileSizeChk)
{
if (IsfileSizeChk == true)
{
string strTemp;
if (fi.Exists == false)
MessageBox.Show("TESTER SIDE에 파일이 존재하지 않습니다. 확인 바랍니다.", "Error Information",
MessageBoxButtons.OK, MessageBoxIcon.Error);
if (fsize != fi.Length)
{
strTemp = string.Format("파일이 정상적으로 다운로드 되지 않았습니다. filesize [{0}] : [{1}]",
fsize, fi.Length);
MessageBox.Show(strTemp, "Error Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}
}

/를 씌우고, user name password를 지정한다.

/// Amend an FTP path so that it always starts with
private string AdjustDir(string path)
{
return ((path.StartsWith("/")) ? "" : "/").ToString() + path;
}

//Get the basic FtpWebRequest object with the
//common settings and security
private FtpWebRequest GetRequest(string URI)
{
//create request
FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
//Set the login details
result.Credentials = GetCredentials();
//Do not keep alive (stateless mode)
result.KeepAlive = false;

return result;
}

/// <summary>
/// Get the credentials from username/password
/// </summary>
private System.Net.ICredentials GetCredentials()
{
return new System.Net.NetworkCredential(axSinfo.userid, axSinfo.password);
}

 

목표: Control로 설정된 값(Text등)을 바꾸거나 값을 가져와 보자

본 Control은 User Control로 제작된 Form에서 수행된다.

 

#region "Control 속성을 변경 및 문자열을 얻기이한 Method"

/// GroupBoxCtrlTest Name Get/Set
public string GrpBoxCtrlText
{
get
{
return grpBox.Text;
}
set
{
grpBox.Text = value;
}
}

#endregion

목표 : 외부 응용 프로그램을 실행하는 함수의 사용방법을 익혀보자.

 

 

good luck.. 출처: http://blog.naver.com/tear230?Redirect=Log&logNo=100002921976

 

목표: 서버에 연결가능하지를 검사하기 위한 방법으로,

Ping Test 기능을 구현해 봤다(USER Control 제작중 Ping Test 기능 구현)

처음에는 ActiveX를 이용하여 구현하려 했으나, C#으로 Main UI를 개발중이여서,

User Control을 사용하였다.

1. using을 선언하여 network에 필요한 namespace들을 지정한다.

//for use the network, you will define the list like under sentance
using System.Net;
using System.Net.NetworkInformation;

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

public partical class ServerLoginX : UserControl

{

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

2. 먼저 초기화 전역 선언부로 Ping Class를 선언한다.//

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

private string strCurIP = "";
private Ping ping = null;
private PingOptions pingOption = null;

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

3. Form이 생성되는 생성부에 초기값을 설정.

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

public ServerLoginX()
{
InitializeComponent();


// textbox ping result output window attribute set.
txtboxResult.Enabled = false;
txtboxResult.BackColor = Color.Black;
txtboxResult.ForeColor = Color.White;

// IP는 xxx.xxx.xxx.xxx 형태로 나타내기위해서 maskedTextBox 사용.
mskTxtBoxServerIP.Mask = "000.000.000.000";
}

 

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

4.실제 Ping Test Button이 수행되는 부분.

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

/// function : btnPingTest_Click
/// review : This "PING TEST" function is confirm whether The Linux Server connect
private void btnPingTest_Click(object sender, EventArgs e)
{
ping = new Ping();
pingOption = new PingOptions();

string sdata = "samplesentance";

strCurIP = mskTxtBoxServerIP.Text;
if(strCurIP.Substring(0,1) == " ")
{
strCurIP = "192.168.001.197"; // default set
mskTxtBoxServerIP.Text = strCurIP;
}

if (!mskTxtBoxServerIP.MaskCompleted)
{
MessageBox.Show("Not IP Address Style your input Address!! ex)192.168.001.1100");
mskTxtBoxServerIP.Focus();
return;
}

// txtbox clear...
txtboxResult.Clear();

byte[] byteSendData = Encoding.ASCII.GetBytes(sdata);

// combo box로부터 반복실행할 값을 얻어 int형으로 변환하였다.
int pingcnt = Convert.ToInt32(cboxPingCnt.Text.ToString());

for (int loopcnt = 0; loopcnt < pingcnt; loopcnt++)
{
PingReply pingReply = ping.Send(strCurIP, 120, byteSendData, pingOption);

string strTemp;
if (pingReply.Status == IPStatus.Success)
{
strTemp = string.Format("Replay[{0}] From {1} : {2} Bytes TTL = {3}\r\n",
loopcnt+1, pingReply.Address, pingReply.Buffer.Length, pingReply.Options.Ttl);
txtboxResult.AppendText(strTemp);
txtboxResult.ScrollToCaret();
}
else
{
strTemp = string.Format("Request Time Out!!\r\n");
txtboxResult.AppendText(strTemp);
txtboxResult.ScrollToCaret();
}
}
}

}

목표: C#에서 사용하고자 하는 데이터를 class type(Struct)로 만들어 보자.

* 주의점: Main Form보다 상위에 Class를 선언하면, UI error가 발생함.

 

==============================================================================

구조체는 Value타입이고 Class Reference타입니다.

으잉? 항상 듣는 소리다. ‘ValueReference’

차이점은 이거면 충분히 알 수 있다.

int a = 10;

int b = a;

a = 20;

현재 b의 값은? 당연히 10이다. Value타입이니까

class ClassA

{

public int valTest = 0;

}

ClassA a = new ClassA();

ClassA b = a;

a.valTest = 5;

현재 b.valTest의 값은? 당연히 5. bnew ClassA();에서 생성된 메모리 번지를 가리키고 있기 때문이다. Reference니까

그럼

struct StructA

{}

StructA a = new Struct();

StructA b = a;

이건?

다시말하지만 struct Value타입이다 기억해두도록

==============================================================================

 

// This structure create the DataBase which the variables used in the this program.
public class PKGDataStructure
{
public PKGDataStructure() { }
~PKGDataStructure() { }

// TestInfo

// Summary View
public string strFilePath;

};

 

목표: Form을 생성시킨 후, Dialog를 띄워보자. (참~ 쉽다. 역쉬 시샵이다~!!)

 

private void btnFuncSetup_Click(object sender, EventArgs e)
{
FunctionSetupDlg funcDlg = new FunctionSetupDlg();
funcDlg.Show();
}

 

'프로그래밍 > .Net' 카테고리의 다른 글

Ping Test를 해보자  (0) 2014.01.17
class를 만들어 보자  (0) 2014.01.17
file access, file을 생성하고 읽어보자  (0) 2014.01.17
OpenFileDialog 사용하기.(OpenFileDlg)  (0) 2014.01.17
SourceGrid2 사용하기  (0) 2014.01.17

목표: File을 생성하거나 파일 내용을 읽어오는 코딩을 해보자.

 

using System.IO;

 

1. File Read 작업순서:

/// 파일을 읽어서 richtxt에 보여준다.

/// FuncName: btnSummaryView_Click
/// review : This function is view after read the Summary file
/// apply : file access method,
/// ////////////////////////////////////////////////////////////
private void btnSummaryView_Click(object sender, EventArgs e)
{
if (m_bOpenfile != true)
{
MessageBox.Show("It is not set to see the Summary file!");
return;
}
//richtxtSummaryView.LoadFile(axDBS.strFilePath);
// Read the summary files
string strOneLine = null, strTotalLine = null;
try
{

FileStream aFile = new FileStream(axDBS.strFilePath, FileMode.Open);
StreamReader sr = new StreamReader(aFile);
strOneLine = sr.ReadLine();

// Read the One line from the opened this file.
while (strOneLine != null)
{
strTotalLine += strOneLine + "\r\n";
strOneLine = sr.ReadLine();
}

sr.Close();
richtxtSummaryView.Text = strTotalLine;
}
catch (IOException err)
{
MessageBox.Show(err.ToString());
return;
}

}

 

2. File Write 작업순서

/// FuncName: btnSummarySave_Click
/// review : This function is view after read the Summary file
/// apply : file access method,
/// ///////////////////////////////////////////////////////////////
private void btnSummarySave_Click(object sender, EventArgs e)
{
if (m_bOpenfile != true)
{
MessageBox.Show("It is not set to see the Summary file!");
return;
}

if (richtxtSummaryView.Text == "")
{
MessageBox.Show("Context of the Summary File is not exist!");
return;
}

FileStream aFile = new FileStream(axDBS.strFilePath, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
sw.Write(richtxtSummaryView.Text);
sw.Close();
}

 

 

OpenFileDlg Class가 있어서,

그냥 선언 후 사용하면 OpenDialog Box를 생성시킬 수 있다.

 

1. Button을 클릭했을때, OpenFileDialog를 만들어 보자.

/// function history
/// FuncName: btnOpenFile_Click
/// review : This function is execute the Open File Dialog
/// apply : Open File Dialog method.
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Summary files...";
dlg.InitialDirectory = @"c:\FROM30";
dlg.Filter = "Summary files(*.dat)|*.dat|All Files|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
string strFilePath = dlg.FileName;
txtSummaryPath.Text = strFilePath;
m_bOpenfile = true;
}else
m_bOpenfile = false;

this.btnSummaryView_Click(sender, e);
}

 

 

추가로 폴더만 선택하고 싶다면..

FolerBrowserDialog를 사용할것..

// 요렇게..

private void btnRFilePath_Click(object sender, EventArgs e)
{
FolderBrowserDialog fDlg = new FolderBrowserDialog();
fDlg.ShowNewFolderButton = true;
fDlg.SelectedPath = @"c:\From30"; //초기값설정.
if (fDlg.ShowDialog() == DialogResult.OK)
{
txtboxResultFilePath.Text = fDlg.SelectedPath;
}
}

 

 

+ Recent posts