DNS

The DNS is capable of translating a server name like www.google.com into a real IP address, and it can be used with the .NET Micro Framework, like in the full .NET Framework, with the static System.Net.Dns class.

Dynamic DNS, which is enabled by default, attempts to automatically discover the DNS servers. You can verify if dynamic DNS is enabled by checking the read-only IsDynamicDnsEnabled property. You can also explicitly specify a list of DNS server IP addresses on your network using the EnableStaticDns method.

DHCP Service

You need not set the IP address, gateway address, and subnet mask explicitly. If your local network provides a reachable DHCP service, you can let the DHCP service automatically configure these parameters. The EnableDhcp method enables the DHCP service, which is the default setting.
Alternatively, calling EnableStaticIP will deactivate the usage of DHCP.
Dynamic IP addresses are assigned temporarily. You can release a dynamic IP address with ReleaseDhcpLease or renew it with RenewDhcpLease. The IsDhcpEnabled property indicates if DHCP is currently enabled.

What is Gateway Address?

When you send an IP packet to an endpoint outside of your local subnet, it must pass a gateway (typically a router). You can set the gateway address explicitly as part of an EnableStaticIP call or let the DHCP (Dynamic Host Configuration Protocol) service automatically configure it, as described in the next section.

What is Subnet Mask?

A subnet is a part of the overall address space. A subnet mask indicates to which subnet a device belongs. A common subnet mask is 255.255.255.0, which indicates that the last byte of an IP address contains host information. You can obtain the actual subnet mask as a string with the read-only SubnetMask property. You can set the subnet mask explicitly with the EnableStaticIP method.

What is MAC Address?

The Media Access Control (MAC) address is a globally unique identifier for your network adapter on its network. You can obtain it with the PhysicalAddress property of the NetworkInterface instance. Although changing the physical address is possible, you should use the unique
identifier provided by default, and you should ensure that all devices on your network have a unique identifier.

UDP protocol

UDP is a connectionless protocol that is lightweight and faster than TCP, but it's error prone because data can be lost in transmission or arrive more than once. UDP is used for streaming services such as Voice over IP, where real time matters but dropping packets just affects the sound quality.

One of the additional advantages of using UDP is the ability to broadcast or multicast data across a network. The DNS service to resolve Internet addresses and the discovery service of the Device Profile for Web Services use the broadcast feature of UDP.

With UDP, a client does not need to connect to a server. Connectionless transmission takes place with the SendTo and ReceiveFrom methods. ReceiveFrom returns an endpoint object that is populated with the actual sender information. Listing 6-4 shows a UDP client and Listing 6-5 a UDP server. They demonstrate the usage of a connectionless end-to-end transmission but are not using the broadcast feature.

If you want to send a broadcast message that theoretically all network nodes will get, you can use the IP address 255.255.255.255. There is no predefined broadcast address like Any or Loopback as there is with the full .NET Framework. You can also create a broadcast IP address object using new IPAddress(0xFFFFFFFF);.

Transmitting Data with a Socket

Once you have a connection, you can send data synchronously with the socket's Send method:
clientSocket.Send(Encoding.UTF8.GetBytes("Hello World!"));

And you can receive data with the Receive method. The maximum number of bytes the Receive method reads is limited by the amount the specified buffer can hold. The method returns the actual number of bytes that were read:

byte[] inBuffer = new byte[100];
int count = clientSocket.Receive(inBuffer);
char[] chars = Encoding.UTF8.GetChars(inBuffer);
string str = new string(chars, 0, count);
Debug.Print(str);

You can poll the socket to test if data has been received. The first polling parameter specifies the amount of time, in microseconds, you want your application to wait for a response. Set it to –1 or System.Threading.Timeout.Infinite to let your application to wait an infinite amount of time:
if (communicationSocket.Poll(-1, //timeout in microseconds (-1 = infinite)
SelectMode.SelectRead))
{
...//read data here
}
Using the Available property of the Socket class, you can determine the number of bytes that are available to read before receiving them, which allows you to allocate a buffer that can hold all available bytes before reading the data.

Addressing NET Micro Framework

An IP version 4 address is coded as 4-byte integer value but usually indicated in the more legible dotted decimal notation, for example, 192.168.101.100. When creating an instance of the IPEndPoint and IPAddress classes, you need to specify the address coded as a long value.
You cannot directly parse an IP address from a string with the Parse method of IPAddress as you can with the full .NET Framework; the .NET Micro Framework does not provide a Parse method for IPAddress. You can indirectly parse using the System.Net.Dns class, but first, take a look at the following code snippet, which demonstrates how you can convert a dotted decimal IP address to an IP address of the long value type.

public static long DottedDecimalToIp(byte a1, byte a2, byte a3, byte a4)
{
return (long)((ulong)a4 << 24 | (ulong)a3 << 16 | (ulong)a2 << 8 | (ulong)a1);
}

Using the preceding snippet, you can easily create an endpoint with legible decimal notation:
IPEndPoint ep = new IPEndPoint(DottedDecimalToIp(192, 168, 101, 100), 80);

As I said, there is a way to convert the IP address using the System.Net.Dns class, which allows you to use the Internet Domain Name System (DNS). The Dns class is responsible for resolving server names. Server addresses can be specified either in decimal notation or as a server name like www.microsoft.com. The GetHostEntry method returns a collection of the entries found in the DNS database. If you pass a particular address in decimal notation, you will always get one entry in the form of an IPAddress object:
IPHostEntry entry = Dns.GetHostEntry("192.168.101.100");
IPAddress ipAddr = entry.AddressList[0];
IPEndPoint ep = new IPEndPoint(ipAddr, 80);

Passing an empty string ("") to the GetHostEntry method will deliver the local IP address of the device.
The IPAddress class possesses two predefined static addresses properties: IPAddress.Loopback and IPAddress.Any IPAddress.Loopback describes the address 127.0.0.1, which is used if the client and server are on the same PC or device. IPAddress.Any is 0.0.0.0 and does not have a meaning for client applications; we will discuss that parameter in detail later, with server
applications.
For example, to connect with a server at the address 192.168.101.100 on the port 80, you need the following code:
Socket clientSocket = new Socket(Addressfamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint serverEndPoint = new IPEndPoint(DottedDecimalToIp(192, 168, 101, 100),
80); // port no
clientSocket.Connect(serverEndPoint);
You can obtain the two endpoints of the socket when a connection is available with the RemoteEndPoint and LocalEndPoint properties. Casting these into an IPEndPoint object will make the IP address available over the Address property.

You can determine the individual bytes of an IP address with the GetAddressBytes method, which supplies a byte array. With IP version 4, GetAddressBytes returns a byte array of 4 bytes.

In addition, the ToString method provides a string displaying the IP address in dotted decimal notation.
IPEndPoint remoteIPEndPoint = (IPEndPoint)communicationSocket.RemoteEndPoint;
byte[] addressBytes = remoteIPEndPoint.Address.GetAddressBytes();

TCP Programming


A TCP/IP connection is the right choice when you need a reliable two-way, connection-based communication that ensures that data packets will be received in the correct order and that no data  will be lost or transferred multiple times. You can create a TCP/IP socket with the following code:

Socket socket = new Socket(Addressfamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

Connecting to a Server as a Client

After you have created a socket object, you are able to initiate a connection to a (remote) server with the Connect method of your socket. Your .NET Micro Framework application is thereby  the client application. The connection establishment takes place synchronously, so your client application will be blocked until a connection is available.

public void Connect(EndPoint remoteEP);

Take note of the remoteEP parameter of the abstract type System.Net.EndPoint in the signature of the Connect method. For IP connections, you need to pass an instance of the System.Net.IPEndPoint class to the Connect method. IPEndPoint contains the IP address and the communication port, and it is derived from EndPoint.

You can create an IPEndPoint object with one of the following two constructors:
public IPEndPoint(long address, int port)
public IPEndPoint(IPAddress address, int port)

Sockets Programming

Programming applications that access a network was originally a complicated affair, but with the .NET Framework, this is no longer the case. The .NET Framework provides classes that substantially simplify complex network programming. These classes are in the System.Net and System.Net.Sockets namespaces in the System.dll assembly.

The most important class for network programming is System.Net.Sockets.Socket. The Socket class abstracts and implements the Socket API and/or Berkeley socket interface standard.

The Socket API was developed at the beginning of the 1980s at the University of California,Berkeley for Berkeley Software Distribution (BSD) UNIX.

A socket is an endpoint of a connection. With sockets, you can read and send data to and from a network on both the client and server sides. To send or receive data from a socket, you need to know the IP address of the other communication partner (endpoint) and one agreedupon port number, which can vary depending on application purposes. A client application, thus, must know the IP address of the server and connect with that server on a particular port.

The server listens on the agreed port or ports and accepts incoming connections from one or more clients.

Accessing SPI Devices with the .NET Micro Framework

The .NET Micro Framework. SPI devices are represented by the Microsoft.SPOT.Hardware.

Why Reserve Pins?

By reserving CPU pins, you can explicitly control the usage of the pins. By registering a hardware provider, you are able to reserve the required pins for the serial interface and the I²C and SPI busses to detect multiple usage of a pin and to avoid the resulting conflicts. The use of hardware providers is optional, but they provide simple and central management of shared pins.

The RS232 Serial Port

Even though the concept of the serial interface has been around for years and USB is becoming more and more established, there are still many devices that need to be interfaced with a serial port, for example, measuring instruments and GPS receivers. In addition, the Bluetooth standard defines several protocols (profiles) to access different devices like head sets and printers, and it also has a communication profile via Bluetooth named Serial-Port. Some serial-to-Bluetooth adapters exist already. If such an adapter is connected to the serial interface of the microcontroller, a .NET Micro Framework application can communicate wirelessly with a PC, PDA,smartphone, or other microcontroller (see Chapter 7).

Together with the serial interface, you quite often hear the terms "UART," "USART," and "RS232." UART and USART are names for the serial hardware component, the Universal (Synchronous) Asynchronous Receiver Transmitter. The RS232 standard describes how data will be physically transferred over the cable. Further standards are RS422 and RS485.

What Are GPIO Ports?

General purpose input/output (GPIO) ports are probably the most frequently used way for a microcontroller to contact its environment. A GPIO port can be initialized and used either as an input or output line. A typical example of an output line is one to control a light-emitting
diode (LED). Monitoring a push button or a switch is the function of an input line.

A GPIO port can have either a low (0 volts) or high (a positive voltage, usually 3.3 volts) status. In the .NET Micro Framework, the status of a GPIO port is represented as a Boolean value. The value false corresponds to low status and true to high.

TFConvert Tool

The .NET Micro Framework uses the .tinyfnt file format to work with fonts. This special format uses fixed size bitmaps for a simpler way to render fonts. Two sample .tinyfnt fonts are included in the Fonts subdirectory of your .NET Micro Framework installation. To create other fonts in the size, style, and language tailored to your application, you can use the TFConvert tool to create a .tinyfnt font from TrueType or OpenType font files. That enables you to select character sets and even create fonts for displaying Cyrillic and Chinese characters.
In the Tools\Fonts subdirectory, you can find some sample TrueType fonts from Ascender Corporation, which you can convert to meet your needs. These free sample fonts provide a reduced character set; the full versions can be purchased from the company.

The TFConvert command line tool is located in the Tools subdirectory of your .NET Micro Framework installation. TFConvert accepts a path to a font definition file that describes the font's size, style, and characters to convert.

The system tool character map (charmap.exe) provided with your Windows installation can help you determine which characters or character ranges to convert.

To get more information about creating .tinyfnt fonts with the TFConvert tool, please see the .NET Micro Framework SDK documentation, where this is described in detail.

In addition, on the SJJ Embedded Micro Solutions web site, you can find a great article that describes how to convert fonts with TFConvert (www.sjjmicro.com/SJJ_Articles.html).

On the web site of a Czech .NET Micro Framework enthusiast, Jan Kucera, at www.microframework.eu, you can find the Tiny Font Tool GUI. This tool provides a graphical user interface that assists you in creating the font definition files.

MFDeploy [.NET Micro Framework Deployment Tool ]

The .NET Micro Framework provides the .NET Micro Framework Deployment Tool (MFDeploy), which you can find in the Tools subfolder of the SDK. The primary purpose of MFDeploy is to copy your application to devices. MFDeploy provides a GUI (see Figure 3-5), can be invoked from the command line, and provides a .NET API, and thus allows you to use MFDeploy in your production environment to replicate a standard deployment on your devices without Visual Studio.

The features of MFDeploy include the following:

• Discovering and pinging devices to test if they are responsive
• Creating a standard deployment from a master device
Copying your application to the device
• Upgrading firmware
• Creating and updating device keys
• Signing code
• Setting network parameters and USB names
• Use via a UI or automatically via the command line or programmatically

.NET Micro Framework Base Class Library

The Base Class Library Runtime Assemblies
The runtime libraries that you can find in the Assemblies subdirectory of your .NET Micro Framework installation include the following:
• Mscorlib.dll: A subset of the core .NET classes.
• System.dll: Only the System.Net namespace.
• System.Xml.dll: A subset of the core .NET XML classes necessary to read XML files.
• Microsoft.SPOT.Native.dll: Core .NET Micro Framework classes.
• Microsoft.SPOT.Hardware.dll: Managed hardware drivers.
• Microsoft.SPOT.Graphics.dll: Low-level graphics classes.
• Microsoft.SPOT.TinyCore.dll: User interface elements for complex WPF GUIs.
• Microsoft.SPOT.Net.dll: Internal socket drivers.

When using network sockets, you need to include System.dll and Microsoft.SPOT.Net.dll.
Further assemblies for the Device Profile for Web Services (DPWS) stack are also included.

Although provided with the .NET Micro Framework 2.5 SDK release, the implementation of the DPWS stack is still in beta, and therefore, the DPWS libraries are not installed by default with the .NET Micro Framework SDK. When installing the SDK you need to choose either the Install All option or the Custom Installation option with DPWS selected.

.NET Micro Framework System Requirements

System Requirements

Developing for the .NET Micro Framework requires the following:
• Microsoft Windows XP or Vista
• Microsoft Visual Studio 2005 Standard Edition or better, with Service Pack 1
• .NET Micro Framework SDK version 2 with Service Pack 1 or version 2.5

The free Express editions of Visual Studio cannot be used with the .NET Micro Framework,because they do not allow installing extensions at all. Do not forget to install Visual Studio 2005 Service Pack 1.

What Is the .NET Micro Framework?

The Microsoft .NET Micro Framework is a small and efficient .NET runtime environment used to run managed code on devices that are too small and resource constrained for Windows CE and the .NET Compact Framework.

The .NET Micro Framework enables you to write embedded applications for small, connected, embedded devices with Visual Studio and C#. That means you can now use the same development tools and language that you use to build desktop and smart device (PDA and smartphone) applications to develop applications for microcontrollers. The .NET Micro Framework also provides an extensible hardware emulator for rapid prototyping and debugging.

The .NET Micro Framework requires no underlying operating system. A scaled-down version of the Common Language Runtime (TinyCLR) sits directly on the hardware, so the framework is often called a bootable runtime. The runtime has a small footprint; it uses only a few hundred kilobytes of RAM and does not require the processor to have a memory management unit (MMU).

Therefore, the .NET Micro Framework can run on small and inexpensive 32-bit processors without consuming a lot of power.

How to: Improve the Startup Time of WCF Client Applications using the XmlSerializer

Services and client applications that use data types that are
serializable using the XmlSerializer generate and compile
serialization code for those data types at runtime, which can result
in slow start-up performance.

Note:
Pre-generated serialization code can only be used in client
applications and not in services.


The ServiceModel Metadata Utility Tool (Svcutil.exe) can improve
start-up performance for these applications by generating the
necessary serialization code from the compiled assemblies for the
application. Svcutil.exe generates serialization code for all data
types used in service contracts in the compiled application assembly
that can be serialized using the XmlSerializer. Service and operation
contracts that use the XmlSerializer are marked with the
XmlSerializerFormatAttribute.

To generate XmlSerializer serialization code
Compile your service or client code into one or more assemblies.

Open an SDK command prompt.

At the command prompt, launch the Svcutil.exe tool using the following format.

svcutil.exe /t:xmlSerializer <assemblyPath>*


The assemblyPath argument specifies the path to an assembly that
contains service contract types. Svcutil.exe generates serialization
code for all data types used in service contracts in the compiled
application assembly that can be serialized using the XmlSerializer.

Svcutil.exe can only generate C# serialization code. One source code
file is generated for each input assembly. You cannot use the
/language switch to change the language of the generated code.

To specify the path to dependent assemblies, use the /reference option.

Make the generated serialization code available to your application by
using one of the following options:

Compile the generated serialization code into a separate assembly with
the name [original assembly].XmlSerializers.dll (for example,
MyApp.XmlSerializers.dll). Your application must be able to load the
assembly, which must be signed with the same key as the original
assembly. If you recompile the original assembly, you must regenerate
the serialization assembly.

Compile the generated serialization code into a separate assembly and
use the XmlSerializerAssemblyAttribute on the service contract that
uses the XmlSerializerFormatAttribute. Set the AssemblyName or
CodeBase properties to point to the compiled serialization assembly.

Compile the generated serialization code into your application
assembly and add the XmlSerializerAssemblyAttribute to the service
contract that uses the XmlSerializerFormatAttribute. Do not set the
AssemblyName or CodeBase properties. The default serialization
assembly is assumed to be the current assembly.

Example
The following command generates serialization types for XmlSerializer
types that any service contracts in the assembly use.

svcutil /t:xmlserializer myContractLibrary.exe

How to: Use Svcutil.exe to Download Metadata Documents

You can use Svcutil.exe to download metadata from running services and
to save the metadata to local files. For HTTP and HTTPS URL schemes,
Svcutil.exe attempts to retrieve metadata using WS-MetadataExchange
and XML Web Service Discovery. For all other URL schemes, Svcutil.exe
uses only WS-MetadataExchange.

By default, Svcutil.exe uses the bindings defined in the
MetadataExchangeBindings class. To configure the binding used for
WS-MetadataExchange, you must define a client endpoint in the
configuration file for Svcutil.exe (svcutil.exe.config) that uses the
IMetadataExchange contract and that has the same name as the Uniform
Resource Identifier (URI) scheme of the metadata endpoint address.

To download metadata using Svcutil.exe
Locate the Svcutil.exe tool at the following location:

C:\Program Files\Microsoft SDKs\Windows\v1.0.\bin

At the command prompt, launch the tool using the following format.

svcutil.exe /t:metadata <url>* | <epr>


You must specify the /t:metadata option to download metadata.
Otherwise, client code and configuration are generated.

The <url> argument specifies the URL to a service endpoint that
provides metadata or to a metadata document hosted online. The <epr>
argument specifies the path to an XML file that contains a
WS-Addressing EndpointAddress for a service endpoint that supports
WS-MetadataExchange.

For more options about using this tool for metadata download, see
ServiceModel Metadata Utility Tool (Svcutil.exe).

Example
The following command downloads metadata documents from a running service.

svcutil /t:metadata http://service/metadataEndpoint

How to: Use Svcutil.exe to Validate Compiled Service Code

You can use the ServiceModel Metadata Utility Tool (Svcutil.exe) to
detect errors in service implementations and configurations without
hosting the service.

To validate a service
Compile your service into an executable file and one or more dependent
assemblies.

Open an SDK command prompt

At the command prompt, launch the Svcutil.exe tool using the following format.

svcutil.exe /validate /serviceName:<serviceConfigName> <assemblyPath>*


You must use the /serviceName option to indicate the configuration
name of the service you want to validate.

The assemblyPath argument specifies the path to the executable file
for the service and one or more assemblies that contain the service
types to be validated. The executable assembly must have an associated
configuration file to provide the service configuration. You can use
standard command-line wildcards to provide multiple assemblies.

How to: Use Svcutil.exe to Export Metadata from Compiled Service Code

Svcutil.exe can export metadata for services, contracts, and data
types in compiled assemblies, as follows:

To export metadata for all compiled service contracts for a set of
assemblies using Svcutil.exe, specify the assemblies as input
parameters. This is the default behavior.

To export metadata for a compiled service using Svcutil.exe, specify
the service assembly or assemblies as input parameters. You must use
the /serviceName option to indicate the configuration name of the
service you want to export. Svcutil.exe automatically loads the
configuration file for the specified executable assembly.

To export all data contract types within a set of assemblies, use the
/dataContractOnly option.

Note:

Use the /reference option to specify the file paths to any dependent assemblies.

How to generating a WCF Client from Service Metadata

Metadata documents can be on a durable storage or be retrieved online.
Online retrieval follows either the WS-MetadataExchange protocol or
the Microsoft Discovery (DISCO) protocol. Svcutil.exe issues the
following metadata requests simultaneously to retrieve metadata:

WS-MetadataExchange (MEX) request to the supplied address.

MEX request to the supplied address with /mex appended.

DISCO request (using the DiscoveryClientProtocol from ASP.NET Web
services) to the supplied address.

Svcutil.exe generates the client based on the Web Services Description
Language (WSDL) or policy file received from the service. The user
principal name (UPN) is generated by concatenating the user name with
"@" and then adding a fully-qualified domain name (FQDN). However, for
users who registered on Active Directory, this format is not valid and
the UPN that the tool generates causes a failure in the Kerberos
authentication with the following error message: The logon attempt
failed. To resolve this problem, manually fix the client file that the
tool generated.

svcutil.exe [/t:code] <metadataDocumentPath>* | <url>* | <epr>

ServiceModel Metadata Utility Tool (Svcutil.exe)

The ServiceModel Metadata Utility tool is used to generate service
model code from metadata documents and metadata documents from service
model code.