15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

674 ❘ ChaPTer 25 windOws services<br />

the Click event assigned to the method OnGetQuote <strong>and</strong> the TextBox has the x:Name property set to<br />

textQuote.<br />

Server <strong>and</strong> port information to connect to<br />

the server is configured with settings of the<br />

application. You can add settings with<br />

the Settings tab inside the properties of the<br />

project (see Figure 25-5). Here, you can define<br />

the ServerName <strong>and</strong> PortNumber settings, <strong>and</strong> figure 25-5<br />

define some default values. From here, with<br />

the Scope set to User, the settings go into a<br />

user-specific configuration file, <strong>and</strong> every user of the application can have different settings. This Settings<br />

feature of Visual Studio also creates a Settings class so that the settings can be read <strong>and</strong> written with a<br />

strongly typed class.<br />

You need to add the following using directives to your code:<br />

using System;<br />

using System.Net.Sockets;<br />

using System.Text;<br />

using System.Windows;<br />

using System.Windows.Input;<br />

code snippet QuoteClient/MainWindow.xaml.cs<br />

The major functionality of the client lies in the h<strong>and</strong>ler for the click event of the Get Quote button:<br />

protected void OnGetQuote(object sender, RoutedEventArgs e)<br />

{<br />

const int bufferSize = 1024;<br />

Cursor currentCursor = this.Cursor;<br />

this.Cursor = Cursors.Wait;<br />

string serverName = Properties.Settings.Default.ServerName;<br />

int port = Properties.Settings.Default.PortNumber;<br />

var client = new TcpClient();<br />

NetworkStream stream = null;<br />

try<br />

{<br />

client.Connect(serverName, port);<br />

stream = client.GetStream();<br />

byte[] buffer = new byte[bufferSize];<br />

int received = stream.Read(buffer, 0, bufferSize);<br />

if (received

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!