Prepared by Namra tariq goraya. Chapter 8: Networking Understanding Complications of Networking and Mobile Devices: Writing networking code for mobile devices can be much more difficult than it is for a static computer. You have to work around the fact that network availability will be intermittent, and often there are costs involved based on the volume of network traffic. For example, many mobile networks calculate their bills for data services by the number of kilobytes transferred. You can mitigate these issues by implementing your own scheme for encoding your data to be as efficient as possible. The Microsoft .NET Compact Framework doesn't include binary serialization, so you must implement something specific to your needs or use a third-party solution. One such solution is the CompactFormatter, which is designed to work similarly to the desktop BinaryFormatter class. You may not necessarily choose a binary solution. If your data can be represented purely as alphanumeric characters, you can encode it as American Standard Code for Information Interchange (ASCII) text rather than the default Unicode, and this will halve the size of your data. To combat the cost issue, you can build your application to send data only if the user initiates the operation, or only at certain times or when a specific network connection is active. Problem: Initiating a connection from the server to a device can be made difficult by constantly changing IP addresses, which in most cases are not assigned from a public range. Sol: There are two ways to overcome this: You can invest in a third-party middleware product such as Broadbeam or IBM WECM, or you can write your own mechanism. You might do this by having your client devices establish a connection to the server and wait for a response. Prepared by Namra tariq goraya. Microsoft is aware of the challenge, and in the forthcoming version 3.5 of the Compact Framework it will add an e-mail-based provider for Windows Communication Framework (WCF), a fully managed extensible mechanism for messaging. Using Web Services: Web services are self-describing, platform-independent remote method calls. Microsoft Visual Studio and the .NET Framework are designed so that you can call a Web service from your code very easily. You can browse to your chosen Web service through the Visual Studio integrated development environment (IDE) and have the necessary device-side code generated for you. This generated code then makes calling a Web service just the same as calling a local method in your own code. Because of the nature of mobile devices, you have to design your application so that it can gracefully fail if no network connection is currently available. You must also understand that many devices will be connected to lowbandwidth connections, and so operations may take considerably longer than they would for a desktop computer application connected to broadband. As well as the apparent speed of the operation, you should also be aware that most mobile networks are charged by the volume of data transferred, so it is probably in your interest to look carefully at reducing the volume of data sent and received in a Web service call. Understanding System.Net: Networking functionality is housed in the System.Net namespace, which in turn is in System.dll. This is a subset of the functionality available in the full .NET Framework. The two main areas of networking functionality are the WebRequest classes, which perform Hypertext Transfer Protocol (HTTP) request/response communication, and the Socket Prepared by Namra tariq goraya. class, which allows a lower level of two-way communication. WebRequest: The WebRequest and associated WebResponse classes provide a base implementation for performing operations over a number of network technologies. You can use specific derived classes for working with different protocols such as http://, ftp://, and file://. The Compact Framework has only a limited implementation and doesn't have any built-in File Transfer Protocol (FTP) support. You can extend the support to additional protocols by writing your own class derived from WebRequest, and this can be registered to a particular Uniform Resource Identifier (URI) scheme so that your class is created from a call to WebRequest. A new HttpWebRequest is created either by calling WebRequest.Create with the URI or by using the HttpWebRequest constructor. The advantage of the latter is that you don't need to cast from the base WebRequest class to use HTTP-specific properties of the class. By default, you don't need to set any other properties on the request object. The default operation is a GET, which you can use to retrieve content. After it is created, you call GetResponse on the WebRequest and it returns a WebResponse object. This includes a stream to allow you to read from the response. Sockets: Sockets represent a lower-level method of sending and receiving data over a network connection. The System.Net.Sockets namespace contains the Socket class and associated classes and enumerations. Under the hood, this uses the Windows Sockets (winsock) implementation on the host operating system, which in turn is modeled on the Berkeley Sockets architecture for UNIX. Differences Between the Desktop Framework and the Compact Framework: Prepared by Namra tariq goraya. (1) The Compact Framework implementation of Socket includes a subset of the features contained in the desktop version because of differences in the underlying native Windows Sockets functionality. The Compact Framework socket doesn't support the Disconnect method and subsequent reuse of the same Socket object. (2) Finally, the desktop version has a method to send an entire file over the Socket. This method is not included in the Compact Framework, but it is easy to work around that fact: The file can be read into a buffer and this buffer written to the socket in a loop until the entire file has been read. SocketException: errors encountered are raised in the form of exceptions. In the case of the Socket class, the majority of possible exceptions will be caused by Windows Sockets errors returned from the native functions. A specialized exception type, the SocketException, is provided to encapsulate these errors. The ErrorCode property returns the socket error message. Issue: A transfer can fail for numerous reasons, such as inability to contact the remote computer or a connection breaking partway through the transfer. This is especially an issue on a mobile device where a continuous network connection cannot be relied upon. Sol: You can handle these issues by wrapping your network code in try..catch blocks to catch SocketExceptions. You can then make informed decisions about the reason for the exception. E,g://very interesting must read it, but not compulsory so you can skip it. For example, a Connect attempt may fail if the specific port you are using is blocked, the remote computer is unavailable, or the network connection has been lost. If an exception occurs during data transfer, it is often because of a network problem, or possibly the remote computer disconnected because it Prepared by Namra tariq goraya. did not receive the expected data. Probably the most common socket exception has the code 10054 and message "An existing connection was forcibly closed by the remote host." This can commonly occur after you open a connection to a remote device and then first try sending data to it or reading from it. This is because a TCP socket doesn't throw an exception at the time you connect, even if the remote computer is unreachable or not listening on the specified port. Using Sockets: By using sockets, we send data to a colleague or the central server. e.g://not compulsory to read. Related to the Socket class, there are a number of helper classes to do some of the common tasks. For TCP networking, these are the TcpClient and TcpListener classes. These are also found in the System.Net.Sockets namespace and wrap a Socket instance. TcpClient is used to establish an outgoing connection over TCP/IP, and TcpListener contains the functionality to listen for incoming connections from remote devices. A Simple Server: In our sample, we create a TcpListener and run a background thread to listen for incoming connections. In a production system, the server would create a new thread to handle each incoming connection. Client Connections: To allow the user to send an outgoing prospect record, we use a text box to accept the IP address (for example, of the server). and our own application will receive the incoming connection. When the Share button is tapped, a Socket is created to connect to the remote device, and then the Prospect details are sent over the Socket as a string. We wait for a response from the remote device and record whether the transfer was successful or not. Because any network communication is potentially a slow operation, you would typically perform such tasks in a background thread so that your application remains responsive. Prepared by Namra tariq goraya. Using IrDA and Bluetooth: The Compact Framework provides an IrDA library; however, there is no matching library in the full framework. The main difference is that IrDA has the ability to search for nearby devices using the IrDAClient.DiscoverDevices method. The IrDADeviceInfo class groups together information on a specific device such as its address, display name, and hint bits, which are used to describe the type of device. The address is not a fixed identifier and is valid only for the current session because it is created during negotiation between devices. Because IrDA requires a clear line-ofsight connection to a nearby device, you can use it only for exchanging data with one device at a time. it's very important to handle connection errors gracefully in your applications because an IrDA connection can easily be broken. There is no inbuilt support for Bluetooth in the .NET Framework, desktop version or Compact Framework. An added complication is that the device manufacturer can choose to use a Bluetooth networking stack, which may either be the Microsoft version, which is part of the Windows CE modular operating system, or be from a third-party provider. Using Serial Ports: Serial ports are a communications technology that you can use to talk to peripheral devices attached to your device. The technology is tried and tested, and lots of specialist hardware sensors and accessories such as Global Positioning System (GPS) receivers communicate by using serial ports. .NET Compact Framework version 2.0 supports the SerialPort component, which was also introduced in version 2.0 of the full framework.The key port properties exposed are listed Property Description PortName: This is the full name for the port without the trailing colon. BaudRate :Physical baud rate in bits per second; this must match that used on the remote device. StopBits: Number of stop-bits transmitted, usually 1. Prepared by Namra tariq goraya. NewLine: Determines the character used to represent a new line. Used by the ReadLine() method. Examples are \r and \r\n. We demonstrate using the SerialPort component by stepping through the process of building a simple terminal application designed to connect to a serial port and send and receive data. The SerialPort component has defined buffers that are used for both incoming and outgoing data. Virtual Serial Ports: Most devices support serial port emulation to expose Bluetooth devices to legacy applications that support only serial ports. in the case of a Bluetooth receiver, you must assign a virtual serial port that can be selected from in the navigation software. Because the way these are configured can vary between devices and the Bluetooth networking stack used on the device, it is not possible to provide definitive instructions. After a virtual port is set up on your device, you use it programmatically just as you would a connected by a serial cable. Understanding System.Messaging: Although System.Messaging is a new set of functionality in .NET Compact Framework 2.0, it wraps a technology called Microsoft Message Queuing (MSMQ), which has been available to native code developers for some time and is present in the desktop .NET Framework. MSMQ provides loosely coupled store-andforward messaging between applications and different computers. API that is exposed as a set of Component Object Model (COM) interfaces and C functions. The System.Messaging namespace removes all complexities of calling into this native code and provides a subset of the System.Messaging namespace that is present in the full .NET Framework. Installing MSMQ: Prepared by Namra tariq goraya. MSMQ is an optional component of Windows CE: It can be built into a custom platform by the operating system developer, or in the case of Windows Mobile, it is shipped separately to be installed in device memory. The standalone Windows Mobile 2003 software development kit (SDK) includes the required files to be installed manually on the target device. The Windows Mobile 5.0 SDK does not include the MSMQ components, but instead they are deployed separately You can use the Msmqadm.exe application to control the service, and you must issue it with a number of commands to register the service correctly on the device. These can be calledfrom your managed application using the System.Diagnostics.Process.Start method and checking the process ExitCode for status. The Windows CE version of MSMQ doesn't support reading from remote queues, and neither does it support some of the more advanced security features such as encryption and access control lists (ACLs) for queues. It is not possible to search for public queues published in the Microsoft Active Directory directory service. Queues must be created as private queues on the server to be used by Message Queuing on Windows CE. Set Up a Private Queue: The Windows operating system doesn't have MSMQ installed by default, so you must add it by using Add/Remove Programs in Control Panel and selecting Add/Remove Windows Features. After it is installed, you can manage message queuing from Computer Management in Administration Tools in Control Panel. Transaction Support: Message queuing on Windows CE supports only basic transaction support to ensure onceonly delivery in the order the messages were originally sent. It doesn't support multimessage transactions using Microsoft Transaction Coordinator (MTC). You can set transaction support on a server queue simply by selecting the option when creating the Prepared by Namra tariq goraya. queue. You can't change this setting once the queue has been created. Formatters: Formatters are used to convert your data into a form that can be sent in an MSMQ message. The desktop .NET Framework has three built-in formatters: ActiveXMessageFormatter, BinaryMessageFormatter, and XmlMessageFormatter. Because the Compact Framework includes no support for Microsoft ActiveX or binary serialization, it's no surprise that it supports only XmlMessageFormatter. This uses the Extensible Markup Language (XML) serialization built into the framework to produce an XML fragment that on the receiving computer can be deserialized into the same object type. This does, however, mean that individual messages are quite large in comparison with a binary representation of an object, which can be a concern when run over slow and expensive networks. You must make sure you use the same formatter on both ends of the same queue. You are not, however, limited to the single MessageFormatter provided by the Compact Framework because it is possible to implement your own custom MessageFormatter. Nothing is stopping you from implementing your own version of the missing BinaryMessageFormatter or other missing features such as encryption. Queuing Messages from the Device: After MSMQ is installed on the device and the server queue is created, you can start to queue some messages. You can use the MessageQueue class to do this. You must supply the queue name. Queue names are similar in concept to Uniform Resource Locators (URLs), but the format is different; the target computer can be addressed either by IP address or by machine name. MSMQ uses the Domain Name System (DNS) and Windows Internet Name Service (WINS) as available to determine the target computer.