Tuesday, March 9, 2010

C# - Example to use CheckListBox in a Windows Form

Below is some example to use a CheckListBox:

1) Clear content
ChkBoxList_TID.Items.Clear();

2) Add CheckBox
ChkBoxList_TID.Items.Add("ChkBox Text1");

3) Deteremine # of elements and its status
iTotal = ChkBoxList_TID.Items.Count;
int iIndex = ChkBoxList_TID.SelectedIndex;
ChkBoxList_TID.SelectedItem.ToString()

Monday, March 8, 2010

C# - Example to do logging in Web Service

Below is an example to write log file in Web Service:

1) Call the following function is a Web Service

strLog = "UserName=[" + strUser + "]. PW=[" + strUserPW + "]";
LogToFile(this.Server.MapPath(".\\"), strLog);

2) Provide function of LogToFile as below:

private static void LogToFile(string strURL,
string strMess)
{
DateTime Now = System.DateTime.Now;
string strNow = Now.ToString("yyyyMMdd");

string REQUEST_LOG = strURL + "\\TextFile_" + strNow + ".txt";
StreamWriter sr = File.Exists(REQUEST_LOG) ? File.AppendText
(REQUEST_LOG) : File.CreateText(REQUEST_LOG);
sr.WriteLine(strMess);
sr.Close();
}

Wednesday, March 3, 2010

C# - Example to create web service

Below is an example to create / utilize Web Service:
1) By using Visual Studio 2008, select to create a project of "ASP .NET Web Service" using C#

2) Change namespace to Microsoft as below:
[WebService(Namespace = "http://microsoft.com/webservices/")]

3) Right Click file "Service1.asmx", select "View in Browser" to test functionality of the "Web Service".

4) Right Click the project file, select "Rebuild", "Convert to Web Application" and then "Pubish" to publish the web service to proper Virtual Directory of IIS.

5) For the Virtual Directory of the folder which stores the Web Service, right click to sleect "Property" and then click button "CReate" to make the directory to support "Application".

These complete the building and publishing of a web service.

6) Use Visual Studio to create aWeb Form application. Click to select "Add web reference" and declare URL as below to add the service for usage:

http://server_ip/xxx/yyy/zzz/Service1.asmx?op=HelloWorld

7) Add code as below to use the "Web Service":

{ ....

WebReference.Service1 service = new WebReference.Service1();
string message = service.HelloWorld();
MessageBox.Show(message);
....
}

C# - Example of TCPServer

1) Sample code of TCP Server
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;

using System.Windows.Forms;

using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Reflection;

namespace TCP_Server
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread;

// ------------------------------------------------
// To start TCP Service
// ------------------------------------------------
public Server()
{
try
{
this.tcpListener = new TcpListener(IPAddress.Any, 3003);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();

LogToFile("Success to start TCPServer");
}
catch (Exception ex)
{
LogToFile("!!!Fail to start TCPServer. Error=[" + ex.Message + "]");
}
}

// ------------------------------------------------
// To stop TCP Service
// ------------------------------------------------
public void Stop_TCPService()
{
try
{
listenThread.Abort();
LogToFile("Success to stop TCPServer");
}
catch (Exception ex)
{
LogToFile("!!!Fail to stop TCPServer. Error=[" + ex.Message + "]");
}
}

private void ListenForClients()
{
try
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();

//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
catch (Exception ex)
{
LogToFile("!!!Fail to ListenForClients. Error=[" + ex.Message + "]");
}
}

private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();

byte[] message = new byte[4096];
int bytesRead;

while (true)
{
bytesRead = 0;

try
{ //blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);

if (bytesRead != 0)
{
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string strLog = enc.GetString(message);
LogToFile("Data read;[" + strLog + "]");
}
}
catch (Exception ex)
{
//a socket error has occured
LogToFile("!!!Fail to HandleClientComm. Error=[" + ex.Message + "]");
break;
}

if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}

//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}

tcpClient.Close();
}


2) Sample code of client using the service
// TCP Client: Test operation
TcpClient client = new TcpClient();

IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3003);

client.Connect(serverEndPoint);

NetworkStream clientStream = client.GetStream();

ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Server!");

clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();

Monday, March 1, 2010

ASP.NET - modify content of GridView

Below is an example which modify content of a cell of GridView, after data binding:

{
............. // do data binding

int count = GridView_Result1.Rows.Count;
if (count > 0)
{
iCnt = 0;
foreach (GridViewRow row in GridView_Result1.Rows)
{
if (row.Cells[7].Text.Length > 10)
{
iCnt++;
strTemp = row.Cells[7].Text;
row.Cells[7].Text = "View";
}
}
}
....
}

Tuesday, February 23, 2010

C# - example of using Web Service

Assume a web service (with .ASMX file) have been created and registered properly.

Below please find steps to utilize the Web Serice;

1) Use "Add Reference --> Add Web reference" to add the web service by using "Visual Studio" (to specify the URL of the ASMX file, e.g.: http://xxx/sample.asmx). It will create a name space of the service.

2) Use code as below to call function(s) provided by the service:

try
{
//身份验证
cn.xxx.MySoapHeader soapHeader = new cn.xxx.MySoapHeader();
soapHeader.UserName = "test";
soapHeader.PassWord = "test";
string FileName = "";
byte[] AccessoriesByte =null;

cn.xxx.SendEmail service = new cn.xxx.SendEmail();
service.MySoapHeaderValue = soapHeader;

int result=service.SendXXXEmail("111", "222");
if (result==1) MessageBox.Show("Success"); }
else MessageBox.Show("Failure");+ "]");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
...
}

Monday, February 22, 2010

C# - example of HTTP call

1. Sample to use HTTP GET protocol

using system.net;

{
....
string strURL;
strURL = "http://xxxx/default.aspx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);

request.Method = "GET";
try
{
using (WebResponse wr = request.GetResponse())
{
Stream strm = wr.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string line;

while ((line = sr.ReadLine()) != null)
{
MessageBox.Show(line.ToString());
}
strm.Close();
wr.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
....
}

2. Example of reading content of a file through URL

string strURL = "http://xxx/test.html";
string rl = "";
string strContent = "";

try
{
WebRequest myReq = WebRequest.Create(strURL);
WebResponse myRes = myReq.GetResponse();
Stream resStream = myRes.GetResponseStream();
StreamReader sr = new StreamReader(resStream, Encoding.Default);
StringBuilder sb = new StringBuilder();

while ((rl = sr.ReadLine()) != null)
{
sb.Append(rl);
}
strContent = sb.ToString();
myRes.Close();
}