In this article, you will learn how to do convenient two-way data binding to an enumerated property in a Windows Phone app!
|
@using System.Net.Sockets;
@functions
{
// Wrap the response message in our pseudo XML tags.
private string formatResponse(string strResponse)
{
return String.Format("<response>{0}</response>", strResponse.Trim());
}
// Wrap the error message in our pseudo XML tags and add the ERROR prefix.
private string formatErrorResponse(string strErrMsg)
{
return formatResponse("ERROR: " + strErrMsg.Trim());
}
/// <summary>
/// Validates the presence of a URL argument during an HTTP GET request.
/// </summary>
/// <param name="strArgName">The name of the URL argument to validate</param>
/// <param name="bIsMandatory">If TRUE, an Exception will be thrown if the URL <br />
/// argument could not be found, or if it has an empty value.</param>
/// <returns>The trimmed value associated with the URL argument.</returns>
private string checkForValidURLArgument(string strArgName, bool bIsMandatory)
{
string str = Request.QueryString[strArgName];
// If a value was found for the desired URL argument, remove any whitespace
// to make sure we have a valid value.
if (str != null)
str = str.Trim();
if (String.IsNullOrWhiteSpace(str))
{
// Mandatory URL argument?
if (bIsMandatory)
{
// Throw an Exception.
throw new ArgumentNullException(String.Format("The {0} URL argument is missing.", strArgName));
} // if (bIsMandatory)
} // if (String.IsNullOrWhiteSpace(str))
// Return the argument value.
return str;
} // private bool checkForValidURLArgument(string strArgName)
}
@{
string strErrMsg = "(none)";
// This variable will be set to TRUE if an error occurs, FALSE if not.
bool bIsError = false;
// The message we will return to the caller as the response from the
// current chat session volley. It will be an error message if an
// error occurs.
string strResponseMsg = "(none)";
// This string will help build a better error message in case of an Exception.
string strCurrentOperation = "(none)";
TcpClient tcpCli = new TcpClient();
// There should be 3 URL arguments, one for each property in the ChatMessage
// object. The URL argument name is the same as the property name.
//
string strLoginName = "";
string strBotName = "";
string strMessage = "";
// An IP address object that will contain the IP address for the ChatScript
// server after we resolve the domain name of our ChatScript server.
IPAddress ipAddress = null;
// The network stream we will use to talk to the ChatScript server.
NetworkStream streamChatScript = null;
try
{
strCurrentOperation = "Resolving ChatScript server IP adddress.";
// CODEPROJECT MEMBERS: REMEMBER TO REPLACE [*** YOUR DOMAIN NAME HERE ***]
// BELOW WITH THE CORRECT VALUE FOR YOUR WEB SITE OR THE CONNECTION WILL
// FAIL!
// Lookup the IP address for our chatscript server. (Cache this value
// in a later build since GetHostEntry() is reportedly a slow call.)
ipAddress = Dns.GetHostEntry("[*** YOUR DOMAIN NAME HERE ***]").AddressList[0];
strCurrentOperation = "Validating URL arguments (parameters).";
// LoginName, is mandatory.
strLoginName = checkForValidURLArgument("LoginName", true);
// BotName, is optional.
strBotName = checkForValidURLArgument("BotName", false);
// User message (chat input), is optional. But remember,
// only send a blank message to start a new session
// with ChatScript! After that, send the user's input
// each time.
strMessage = checkForValidURLArgument("Message", false);
strCurrentOperation = "Connecting to ChatScript server.";
// OK, we're good to go. We have the 3 URL arguments we were expecting.
// Connect to the ChatScript server.
tcpCli.Connect(ipAddress, 1024);
strCurrentOperation = "Opening the stream for the ChatScript server.";
// Open the stream
streamChatScript = tcpCli.GetStream();
StreamReader sr = new StreamReader(streamChatScript);
BinaryWriter sw = new BinaryWriter(streamChatScript);
// Create a message to send to the server, using the URL argument values
// passed to us.
ChatMessage cm = new ChatMessage(strLoginName, strBotName, strMessage);
strCurrentOperation = "Sending the desired chat message the ChatScript server.";
// Send the message to the chat server.
string strSendChatMsg = cm.ToString();
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(strSendChatMsg);
for (int i = 0; i < strSendChatMsg.Length; i++)
{
data[i] = (byte)strSendChatMsg[i];
}
// Send the chat message.
streamChatScript.Write(data, 0, data.Length);
strCurrentOperation = "Waiting for and then reading the response from the ChatScript server.";
strResponseMsg = ChatMessage.readChatScriptMessage(streamChatScript);
}
catch (Exception exc)
{
// Store the error message and set the error flag.
strErrMsg =
String.Format(
"Exception occurred with the error message -> {0}"
+ " Current operation -> {1}",
exc.Message, strCurrentOperation);
bIsError = true;
}
finally
{
// Get rid of the stream if one was created.
if (streamChatScript != null)
{
streamChatScript.Close();
}
// Close the TCP connection and dispose of the TCP client.
tcpCli.Close();
} // try/catch
// If an error occurs, the response message, wrapped in <response></response tags,
// will be the error message preceded by the word ERROR followed by a colon.
// Otherwise it will be the same except instead of ERROR the prefix string will
// be SUCCESS.
//
// Did an error occur?
if (bIsError)
{
// Return the error message instead.
strResponseMsg = formatErrorResponse(strErrMsg);
}
else
{
// Return the response in our custom format.
strResponseMsg = formatResponse(strResponseMsg);
} // else - if (bIsError)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<!-- Just output the response message from the C# code above -->
@strResponseMsg
</body>
</html>
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Robert Oschler is a veteran artificial intelligence, robotics, natural language processing, and speech recognition programmer. His latest love is C#/.NET programming, especially on the Windows Phone platform. When not writing code you can find him playing guitar or watching the latest videos on MSDN's Channel 9. He is also a member of the incredible Nokia DVLUP program and owes much of his affection for Windows Phone programming to the wonderfully talented and enthusiastic Nokia Ambassadors.