Friday, March 26, 2010

e-Learning : Microsoft Content Preparation Tools

http://www.microsoft.com/learning/en/us/training/lcds.aspx#tab1

The Microsoft Learning Content Development System (LCDS) is a free tool that enables the Microsoft Learning community to create high-quality, interactive, online courses.

Thursday, March 25, 2010

C# - usage of static class

Below is an example of using "static class" in C#:

Ref.: http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx

Main class()
{
...

public static class UtilFunc
{
private static string g_strLogFileURL = "test";

public static void SetLogDir(string strURL)
{
if (strURL != "") g_strLogFileURL = strURL;
}

public static string LogToFile()
{
return g_strLogFileURL;
}
}
...
}

Other Class()
{
....

// static class can't be instantiated, simply use its APIs as below
MessageBox.Show(UtilFunc.LogToFile());

....
}

SQL : comparison with Oracle Server

Below is an article which compares difference between SQL and Oracle server:

http://www.sql-server-performance.com/articles/dba/oracle_sql_server_comparison_p1.aspx

Sunday, March 21, 2010

C# - save content to CSV file from GridView

Below is an example to save content from GridView to CSV file:

{
....
string strPath = ".\\XXX_" + strFName + ".csv";
if (File.Exists(strPath))
{
File.Delete(strPath);
}

StringBuilder strColu = new StringBuilder();
StringBuilder strValue = new StringBuilder();
int i = 0;
int j = 0;

try
{
StreamWriter sw = new StreamWriter(new FileStream(strPath,
FileMode.CreateNew), Encoding.GetEncoding("GB2312"));
// ----------------------------------------------------------------
// Write header to CSV file
// ----------------------------------------------------------------
for (i = 0; i <= iTotalCol; i++)
{
strColu.Append(GridView_Task.Columns[i].HeaderText);
strColu.Append(",");
}
strColu.Remove(strColu.Length - 1, 1); // remove last character
sw.WriteLine(strColu);

// ----------------------------------------------------------------
// Write content to CSV file
// ----------------------------------------------------------------
for (i = 0; i < iTotalRow; i++)
{
strValue.Remove(0, strValue.Length);
DataGridViewRow dr = GridView_Task.Rows[i];

for (j = 0; j <= iTotalCol; j++)
{
strValue.Append(dr.Cells[j].Value.ToString());
strValue.Append(",");
}
strValue.Remove(strValue.Length - 1, 1); // remove last character
sw.WriteLine(strValue);
}
sw.Close();

MessageBox.Show("OK. Success to generate CSV file.");
}
catch (Exception ex)
{
MessageBox.Show("Fail to generate CSV file. Error=[" + ex.Message + "]");
}
...
}

Thursday, March 18, 2010

C# - Example of HTTP Post

Below is an eample for HTTP POST (with additional HTTP header)

{ ....
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create
("http://xxxx/Mt.do");
request.Method = "POST";

string parameter = "HTTP body content";
byte[] byteArray = Encoding.UTF8.GetBytes(parameter);

request.Headers.Add("Encrypt", strMD5);
request.Headers.Add("Mobile", "xxxx");
request.Headers.Add("Vas", "xxxx");

request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (HttpStatusCode.OK == response.StatusCode)
{
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);

string line;
while ((line = reader.ReadLine()) != null)
{
MessageBox.Show(line.ToString());
}
dataStream.Close();
response.Close();
}
else MessageBox.Show("Response code not OK");
....

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
...
}

Wednesday, March 17, 2010

C# - Example to create MD5 hash value

Below is an example to create MD5 has value of "strIn"
{
....

string strIn = "mc20101065806299113601931094";

// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();

// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(strIn));

// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}

// Return the hexadecimal string.
MessageBox.Show(sBuilder.ToString());
...
}

Sunday, March 14, 2010

C# - read XML from SQL2005

Below is an exmaple to read XML content from SQL2005. Use code as below, otherwise, the returned XML may be truncated with size of 2K bytyes

{
....
System.Xml.XmlReader reader = null;

try
{
conn = new SqlConnection(g_strConnDB);
conn.Open();
cmd = new SqlCommand(strCmd, conn);

strCmd = "select *** from *** FOR XML RAW";
cmd.CommandText = strCmd;
reader = cmd.ExecuteXmlReader();
reader.Read();

strResult = "";
while (reader.ReadState != ReadState.EndOfFile)
{
strResult += reader.ReadOuterXml();
}
reader.Close();

....
}
}

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";
}
}
}
....
}