Monday, February 6, 2012

Steps to Setup the Windows Phone 7

Steps to Setup the Windows Phone 7

Open Visual Studio 2010 Express for Windows Phone. File > New Project - Rename the Name: and Solution name: (before clicking OK)
And double click Windows Phone Application In Solution Explorer – click MainPage.xaml
Change the Supported Orientations to “PortraitOrLandscape”

Copy/ Paste the code below into the second <Grid> block:
<!--ContentPanel - place additional content here-->
 <Grid x:Name="ContentPanel" Margin="12,57,12,12" Grid.RowSpan="2">
          <TextBox Height="61" HorizontalAlignment="Right" Name="txtRemoteHost" Text="TextBox" VerticalAlignment="Top" Width="320" FontFamily="Portable User Interface" FontSize="20" Margin="0,0,-4,0" />
            <TextBox Height="68" HorizontalAlignment="Left" Margin="12,245,0,0" Name="txtLCDMessage" Text="TextBox" VerticalAlignment="Top" Width="438" FontFamily="Portable User Interface" FontSize="20" />
            <Button Content="Send LCD Message" Height="72" Margin="12,304,210,0" Name="btnMessage" VerticalAlignment="Top" Click="btnSend_Click_1" FontFamily="Portable User Interface" FontSize="20" />
            <TextBlock Height="30" HorizontalAlignment="Left" Margin="11,8,0,0" Name="textBlock1" Text="Netduino IP" VerticalAlignment="Top" />
            <TextBlock Height="30" Margin="27,218,284,0" Name="textBlock2" Text="LCD Message" VerticalAlignment="Top" />
            <TextBox FontFamily="Portable User Interface" FontSize="20" Height="68" HorizontalAlignment="Left" Margin="11,81,0,0" Name="txtBlinkRate" Text="TextBox" VerticalAlignment="Top" Width="438" />
            <Button Content="Change Blink Rate" FontFamily="Portable User Interface" FontSize="20" Height="72" HorizontalAlignment="Left" Margin="11,140,0,0" Name="btnBlinkRate" VerticalAlignment="Top" Width="254" Click="btnBlinkRate_Click" />
            <TextBlock Height="30" Margin="26,54,40,0" Name="textBlock3" Text="Blink Rate  Milliseconds (bet. 100 - 1000)" VerticalAlignment="Top" />
            <TextBlock Height="294" HorizontalAlignment="Left" Margin="26,382,0,0" Name="textBlockOutput" Text="TextBlock" VerticalAlignment="Top" Width="409" TextWrapping="Wrap" />
        </Grid>
        <TextBlock x:Name="ApplicationTitle" Text="Netduino Blinker and LCD" Style="{StaticResource PhoneTextNormalStyle}" Height="67" Margin="24,12,12,36" />
    </Grid>

CLick on the uper left corner - And select “Add class…”
Name the class “SocketClient” and click “Add”.
Copy the code from below into the code window in VS2010.

SocketClient Class

namespace WPSocketPutNetduino {
    public class SocketClient {
        // Cached Socket object that will be used by each call for the lifetime of this class
        Socket _socket = null;
        // Signaling object used to notify when an asynchronous operation is completed
        static ManualResetEvent _clientDone = new ManualResetEvent(false);
        // Define a timeout in milliseconds for each asynchronous call. If a response is not received within this
        // timeout period, the call is aborted.
        const int TIMEOUT_MILLISECONDS = 5000;
        // The maximum size of the data buffer to use with the asynchronous socket methods
        const int MAX_BUFFER_SIZE = 2048;

        /// <summary>
        /// Attempt a TCP socket connection to the given host over the given port
        /// </summary>
        /// <param name="hostName">The name of the host</param>
        /// <param name="portNumber">The port number to connect</param>
        /// <returns>A string representing the result of this connection attempt</returns>
        public string Connect(string hostName, int portNumber) {
            string result = string.Empty;
            // Create DnsEndPoint. The hostName and port are passed in to this method.
            DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
            // Create a stream-based, TCP socket using the InterNetwork Address Family.
            _socket =
            new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // Create a SocketAsyncEventArgs object to be used in the connection request
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = hostEntry;
            // Inline event handler for the Completed event.
            // Note: This event handler was implemented inline in order to make this method self-contained.
            socketEventArg.Completed +=
            new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) {
                // Retrieve the result of this request
                result = e.SocketError.ToString();
                // Signal that the request is complete, unblocking the UI thread
                _clientDone.Set();
            });
            // Sets the state of the event to nonsignaled, causing threads to block
            _clientDone.Reset();
            // Make an asynchronous Connect request over the socket
            _socket.ConnectAsync(socketEventArg);
            // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
            // If no response comes back within this time then proceed
            _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
            return result;
        }

        /// <summary>
        /// Send the given data to the server using the established connection
        //static Socket Connect(string host, int timeout)
        //{
        // // look up host's domain name to find IP address(es)
        // IPHostEntry hostEntry = Dns.GetHostEntry(host);
        // // extract a returned address
        // IPAddress hostAddress = hostEntry.AddressList[0];
        // IPEndPoint remoteEndPoint = new IPEndPoint(hostAddress, 80);
        // // connect!
        // Debug.Print("connect...");
        // var connection = new Socket(AddressFamily.InterNetwork,
        // SocketType.Stream, ProtocolType.Tcp);
        // connection.Connect(remoteEndPoint);
        // connection.SetSocketOption(SocketOptionLevel.Tcp,
        // SocketOptionName.NoDelay, true);
        // connection.SendTimeout = timeout;
        // return connection;
        //}
        /// </summary>
        /// <param name="data">The data to send to the server</param>
        /// <returns>The result of the Send request</returns>
        public string Send(string data) {
            string response = "Operation Timeout";
            // We are re-using the _socket object that was initialized in the Connect method
            if (_socket != null) {
                // Create SocketAsyncEventArgs context object
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                // Set properties on context object
                socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
                socketEventArg.UserToken =
                null;
                // Inline event handler for the Completed event.
                // Note: This event handler was implemented inline in order to make this method self-contained.
                socketEventArg.Completed +=
                new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) {
                    response = e.SocketError.ToString();
                    // Unblock the UI thread
                    _clientDone.Set();
                });
                // Add the data to be sent into the buffer
                byte[] payload = Encoding.UTF8.GetBytes(data);
                socketEventArg.SetBuffer(payload, 0, payload.Length);
                // Sets the state of the event to nonsignaled, causing threads to block
                _clientDone.Reset();
                // Make an asynchronous Send request over the socket
                _socket.SendAsync(socketEventArg);
                // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                // If no response comes back within this time then proceed
                _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
            } else {
                response =
                "Socket is not initialized";
            }
            return response;
        }

        /// <summary>
        /// Receive data from the server using the established socket connection
        /// </summary>
        /// <returns>The data received from the server</returns>
        public string Receive() {
            string response = "Operation Timeout";
            // We are receiving over an established socket connection
            if (_socket != null) {
                // Create SocketAsyncEventArgs context object
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
                // Setup the buffer to receive the data
                socketEventArg.SetBuffer(
                new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
                // Inline event handler for the Completed event.
                // Note: This even handler was implemented inline in order to make this method self-contained.
                socketEventArg.Completed +=
                new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) {
                    if (e.SocketError == SocketError.Success) {
                        // Retrieve the data from the buffer
                        response =
                        Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
                        response = response.Trim(
                        '\0');
                    } else {
                        response = e.SocketError.ToString();
                    }
                    _clientDone.Set();
                });
                // Sets the state of the event to nonsignaled, causing threads to block
                _clientDone.Reset();
                // Make an asynchronous Receive request over the socket
                _socket.ReceiveAsync(socketEventArg);
                // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                // If no response comes back within this time then proceed
                _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
            } else {
                response =
                "Socket is not initialized";
            }
            return response;
        }
        /// <summary>
        /// Closes the Socket connection and releases all associated resources
        /// </summary>
        public void Close() {
            if (_socket != null) {
                _socket.Close();
            }
        }

    }
}

Go back to the Solution Explorer and open the MainPage.xaml.cs
Copy/Paste the code from below.

MainPage.xaml.cs

namespace WPSocketPutNetduino  {
    public partial class MainPage : PhoneApplicationPage {
        // Constants
        const int myPORT = 80; // This is the variable myPort set to 80, 7, or 14
        string message;
        string header;

        // Constructor
        public MainPage() {
            InitializeComponent();
            Log("started", true);
            txtRemoteHost.Text = "192.168.1.242";
            txtBlinkRate.Text = "250";
            txtLCDMessage.Text = "Hello World from WP7!";
        }
        #region UI Validation
        /// <summary>
        /// Validates the txtInput TextBox
        /// </summary>
        /// <returns>True if the txtInput TextBox contains valid data, False otherwise</returns>
        private bool ValidateInput() {
            // txtInput must contain some text
            if (String.IsNullOrWhiteSpace(txtBlinkRate.Text) && String.IsNullOrWhiteSpace(txtLCDMessage.Text)) {
                MessageBox.Show("Please enter some text to send");
                return false;
            }
            return true;
        }
        /// <summary>
        /// Validates the txtRemoteHost TextBox
        /// </summary>
        /// <returns>True if the txtRemoteHost contains valid data, False otherwise</returns>
        private bool ValidateRemoteHost() {
            // The txtRemoteHost must contain some text
            if (String.IsNullOrWhiteSpace(txtRemoteHost.Text)) {
                MessageBox.Show("Please enter a host name");
                return false;
            }
            return true;
        }
        #endregion

        #region Logging
        /// <summary>
        /// Log text to the textBlockOutput textBlock
        /// </summary>
        /// <param name="message">The message to write to the textBlockOutput textBlock param>
        /// <param name="isOutgoing">True if the message is an outgoing (client to server) message, False otherwise</param>
        /// <remarks>We differentiate between a message from the client and server
        /// by prepending each line with ">>" and "<<" respectively.</remarks>
        private void Log(string message, bool isOutgoing) {
            string direction = (isOutgoing) ? ">> " : "<< ";
            textBlockOutput.Text += Environment.NewLine + direction + message;
        }
        /// <summary>
        /// Clears the txtOutput TextBox
        /// </summary>
        private void ClearLog() {
            textBlockOutput.Text = String.Empty;
        }
        #endregion

        private void btnSend_Click_1(object sender, RoutedEventArgs e) {
            SendMessage("LCD");
        }

        private void btnBlinkRate_Click(object sender, RoutedEventArgs e) {
            SendMessage("LED");
        }

        private void SendMessage(string type) {
            const string CRLF = "\r\n";
            switch (type) {
                case "LED":
                    header = "PUT /blinkingPeriod/target HTTP/1.1" + CRLF;
                    message = txtBlinkRate.Text;
                    break;
                case "LCD":
                    header = "PUT /lcdMessage/target HTTP/1.1" + CRLF;
                    message = txtLCDMessage.Text;
                    break;
                default:  return;
            }

            // Clear the log
            ClearLog();
            // Make sure we can perform this action with valid data
            if (ValidateRemoteHost() && ValidateInput()) {
                byte[] payload = Encoding.UTF8.GetBytes(message);
                header += "Content-Type: text/plain" + CRLF +
                    "Content-Length: " + payload.Length + CRLF + CRLF;
                message = header + message;

                // Instantiate the SocketClient
                SocketClient client = new SocketClient();
                // Attempt to connect to the server
                Log(String.Format("Connecting to server '{0}' over port {1} (send) ...", txtRemoteHost.Text, myPORT), true);
                string result = client.Connect(txtRemoteHost.Text, myPORT);
                Log(result, false);
                // Attempt to send our message to be echoed to the echo server
                Log(String.Format("Sending '{0}' to server ...", message), true);
                result = client.Send(message);
                Log(result, false);
                // Receive a response from the echo server
                Log("Requesting Receive ...", true);
                result = client.Receive();
                Log(result, false);
                // Close the socket connection explicitly
                client.Close();
            }

        }    
    }
}

Save all.
Click on Debug> Start Debugging
The emulator will show up in several seconds with the program -
Finished!

No comments:

Post a Comment