Tuesday, April 20, 2010

C# - Example of using Web Application for HTTP POST request

Below is an example of using ASP.NET (with C#) to create Web Application (.ASPX file, with code-behind DLL written in C#) for HTTP POST command:

1) HTTP Post Request (from a windows form application)

string strResult = "";
string strXML = "";
string strMD5 = "key";
string strUserID = "12345678";

try
{
// ----------------------------------------------------------------
// Send HTTP POST command
// ----------------------------------------------------------------
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
"http://172.18.2...../Test_HTTPPost.ASPX");
request.Method = "POST";

// additional parameters for HTTP header
request.Headers.Add("Encrypt", strMD5);
request.Headers.Add("UserID", strUserID);

// encode HTTP POST data in base-64 format
byte[] szBase64Bytes;

strXML = "....";

szBase64Bytes = new System.Text.UTF8Encoding().GetBytes(strXML);
strXML = System.Convert.ToBase64String(szBase64Bytes);
byte[] byteArray = Encoding.UTF8.GetBytes(strXML);

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

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

// Get response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);

string strTemp = "";
while ((strTemp = reader.ReadLine()) != null)
{
strResult = strResult + strTemp;
}
dataStream.Close();
response.Close();

MessageBox.Show("Result=[" + strResult + "]");
}
catch (Exception ex)
{
MessageBox.Show("Fault. Error=[" + ex.Message + "]");
}

2) Retrieve data for HTTP Post Request (from a ASPX Web Application)

protected void Page_Load(object sender, EventArgs e)
{
string strLogDir = this.Server.MapPath(".\\") + "Log";
Directory.CreateDirectory(strLogDir);
strLogDir = strLogDir + "\\";

LogToFile(strLogDir, "Load Page");

// get request information
int iSize = Request.ContentLength;

// get HTTP header
string strMD5 = Request.Headers["Encrypt"];
string strUserID = Request.Headers["UserID"];

// get HTTP post data
Stream dataStream = Request.InputStream;
StreamReader reader = new StreamReader(dataStream);

string strTemp = "";
string strResult = "";
while ((strTemp = reader.ReadLine()) != null)
{
strResult = strResult + strTemp;
}
dataStream.Close();

if (strResult != "")
{ // Base64 decode of input parameter
byte[] byteArray = System.Convert.FromBase64String(strResult);

System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
strResult = enc.GetString(byteArray);
}

LogToFile(strLogDir, "Size=[" + iSize + "]");
LogToFile(strLogDir, "MD5=[" + strMD5 + "]");
LogToFile(strLogDir, "UserID=[" + strUserID + "]");
LogToFile(strLogDir, "Data=[" + strResult + "]");

// response for testing purpose
Response.Write("Test");
Response.End();
}

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

string REQUEST_LOG = strURL + "XXX" + strNow + ".txt";

StreamWriter sr = File.Exists(REQUEST_LOG) ? File.AppendText(REQUEST_LOG) : File.CreateText(REQUEST_LOG);

strLog = Now.ToString("yyyy-MM-dd HH:mm:ss:") + Now.Millisecond.ToString() + "," + strMess;
sr.WriteLine(strLog);

sr.Close();
}

ASP.NET - Web Application

Types of ASP.NET project:

1. ASP.NET Server Control: A custom control which can be added by developer in web site through Visual Studio

2. ASP.NET Web Service: Web Service programming, access APIs through reference of ASMX file

3. ASP.NET Web Application: access C# code-behind function through access of .ASPX file. "Page load" function of code behind C# file will be invoked while the .ASPX page is accessed.

For both of "Web Service" and "Web Application", need to build / convert and / publish the files to server. Also, need to use IIS to create "Virtaul Directory" and select property to create "application" for the two functions.

Thursday, April 8, 2010

ASP.NET - client script to pop-up window

Below is an example to use C# and client script to pop-up an explorer
{
....

string strCmd = "window.open('admin_report_mms_view.aspx?start=" + str_from + "&end=" + str_to + "&CID=" + cid + "', 'window', config='height=450,width=800,resizable=yes,toolbar=0,menubar=0,location=0')";

((ImageButton)e.Row.Cells[4].FindControl("btn_mms")).Attributes.Add("onclick", "return " + strCmd);

//((ImageButton)e.Row.Cells[4].FindControl("btn_mms")).Attributes.Add ("onclick", "return confirm('Test');"); ....

}

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