Projections

  • Enabling network connectivity on a Windows Mobile device emulator

    I’ve been experimenting with writing programs for Windows Mobile. I write the code in Visual Studio and use it to run the program in a Windows Mobile device emulator. The app I’m working on needs an internet connection but it is not obvious on how to configure the emulator to make that happen. I came across the following instructions on how the emulator can access the same network connection as the host (dev) machine and though I’d share.

    Note: see the end of this post for info on prerequisites and even how to write a managed Windows Mobile application.

    Enabling Network Connectivity on the Device Emulator

    When Device Emulator is started, it starts like a device that is not cradled. In this state, it has no connectivity to the Internet. There is no data plan provided by a mobile operator. Therefore, the Device Emulator also lacks over-the-air connectivity. There are two ways to enable network connectivity by using Device Emulator:

    • By cradling it by using Windows Mobile Device Center (or ActiveSync in Windows XP)
    • By enabling virtual networking by using the virtual machine network services driver

    Note   If the emulator is running inside a virtual PC, see To enable network connectivity on an emulator running inside a Virtual PC.

    The following steps describe how to connect the emulator to the Internet by cradling it. This method connects to the Internet by using an ActiveSync pass-through.

    To cradle the emulator by using Windows Mobile Device Center (or ActiveSync)

    1. Start Windows Mobile Device Center (ActiveSync 4.5 in Windows XP).
    2. Under Mobile Device Settings, click Connection Settings.
    3. In the Connection Settings dialog box, make sure that the Allow Connections to one of the following check box is selected, and that DMA is selected as the option in the list.
    4. Click OK.
    5. On the Tools menu, click Device Emulator Manager.
      • A green arrow appears next to the emulator that is currently running.
    6. Right-click the emulator instance that is currently running and click Cradle.
    7. In Windows Mobile Device Center, create a guest partnership between the desktop and the device.

    - or -

    Select Setup your device.

    After it is connected, the emulator will have Internet connectivity.

    The following steps describe how to connect the emulator to the Internet by using the virtual machine network services driver.

    To connect to the Internet by using the virtual machine network services driver

    1. Install the Virtual PC 2007 SP1 client.
      • This installs the virtual machine network services driver and binds the driver to your primary network card.
    2. In Device Emulator, on the File menu, click Configure.
    3. Click the Network tab.
    4. Select the Enable NE2000 PCMCIA network adapter and bind to check box.
    5. In the list, select Connected network card.
    6. Click OK.

    If the emulator is running inside a virtual PC, you must perform additional steps to enable network connectivity. We will refer to the physical machine as the host machine and to the operating system running inside Virtual PC as the virtual machine. These instructions assume that the virtual machine is installed and ready to run on the host machine.

    To enable network connectivity on an emulator running inside a Virtual PC

    1. Install the Microsoft Loopback Adapter on the host machine.
    2. On the host machine, start Microsoft Virtual PC.
      • The Virtual PC Console appears.
    3. Click Settings to change network settings before starting the virtual machine.
      • The Settings dialog box appears.
    4. Select Networking and then enable two network adapters. Map one of the adapters to the Microsoft Loopback Adapter and the other to the normal adapter (the adapter that is connected to the network).
    5. Click Start to start the virtual machine.
    6. Install the Virtual PC 2007 SP1 on the virtual machine.                                                                                
      • This installs the virtual machine network services driver and binds the driver to your primary network card.
    7. Install the Microsoft Loopback Adapter on the virtual machine.

    Make sure that the host and virtual machines are now connected through the Microsoft Loopback adaptor. You can now to connect the emulator to the Internet by using the virtual machine network services driver.

     

    For reference, writing a managed Windows Mobile application can be done as follows:

    1. Install required software (these or the latest versions)
    2. Enable network connectivity
    3. Follow walkthrough on creating a simple app in managed code at http://msdn.microsoft.com/en-us/library/bb158524.aspx
  • Adding client-side helpers to service-defined contracts

    Summary: When a client adds a service reference to a service, the generated classes are marked as partial, which lets the client add additional helper methods and local functionality to the classes.

     

    When a client generates a contract from a service, only the data and method signatures are included (and not the method implementation). The constructor is not part of the contract either. Here’s an example:

     

    The service, running in Windows Azure, defines a LatLongLocation contract. It looks like

     

        [DataContract]
        public class LatLongLocation
        {
            public LatLongLocation(double latitude, double longitude)
            {
                this.Latitude = latitude;
                this.Longitude = longitude;
            }
     
            [DataMember]
            public double Latitude { get; set; }
            [DataMember]
            public double Longitude { get; set; }
        }

     

    The contract (as defined by the service) has a constructor to make it easy (for the service) to construct this object, however this constructor is never sent over the wire. When a client consumes this contract (by adding a reference to the service), only the data members (and method signatures) are generated (see below). Pay special attention to the fact that this is a partial class, which will be useful later on for the client.

     

        [System.Runtime.Serialization.DataContractAttribute(Name="LatLongLocation", Namespace="http://schemas.datacontract.org/2004/07/PresenceService")]
        [System.SerializableAttribute()]
        public partial class LatLongLocation : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
           
            [System.Runtime.Serialization.OptionalFieldAttribute()]
            private double LatitudeField;
           
            [System.Runtime.Serialization.OptionalFieldAttribute()]
            private double LongitudeField;
           
            [System.Runtime.Serialization.DataMemberAttribute()]
            public double Latitude {
                get {
                    return this.LatitudeField;
                }
                set {
                    if ((this.LatitudeField.Equals(value) != true)) {
                        this.LatitudeField = value;
                        this.RaisePropertyChanged("Latitude");
                    }
                }
            }
           
            [System.Runtime.Serialization.DataMemberAttribute()]
            public double Longitude {
                get {
                    return this.LongitudeField;
                }
                set {
                    if ((this.LongitudeField.Equals(value) != true)) {
                        this.LongitudeField = value;
                        this.RaisePropertyChanged("Longitude");
                    }
                }
            }

        }

     

    The client wants to consume the LatLongLocation contract. The client is a program running on a laptop with a GPS sensor. It can use the Windows 7 location platform to get the current location and then send it to the Azure service. The location platform returns data as a  LatLongLocationReport and this needs to be converted into a LatLongLocation so the service can consume it.

     

    The client program has added a reference to the Azure service. The service metadata is downloaded when adding a reference using Visual Studio and the contract is generated from it. To the client code, the following partial class is added as a convenience to construct LatLongLocation objects.

     

        // The LatLongLocation type is defined by the Presence Service, but
        // the generated reference to the service only contains data members (by design).
        // This adds a new type of constructor to use with data from
        // the Win7 location platform.
        public partial class LatLongLocation
        {
            public LatLongLocation(Windows7.Location.LatLongLocationReport report)
            {
                this.Latitude = report.Latitude;
                this.Longitude = report.Longitude;
            }
     
            public LatLongLocation(double latitude, double longitude)
            {
                this.Latitude = latitude;
                this.Longitude = longitude;
            }
        }

     

    (Note that the LatLongLocation (latitude, longitude) constructor is duplicated from the service definition out of necessity and is only added as a convenience for the client-side code. In fact the client may not even be aware that the same constructor ever existed on the service-side).

     

    This shows a client can add additional local functionality (LatLongLocationReport) to the service-side defined contract (LatLongLocation). The functionality added on the client side won’t be sent over the wire and affect the service either. In addition, if the generated contract ever needs to be regenerated, it won’t wipe out the additional code added on the client-side.

  • Adding a service reference for non-http bindings

    In Visual Studio it’s easy to add (or discover) a service that uses an http binding. What about adding a reference for some other binding (e.g. a TCP binding) that uses the .NET Service Bus? It’s easy – just add a reference to the MEX endpoint.

    For example, a reference may look like “sb://solutionname.servicebus.windows.net/ServiceName/mex”

  • Debugging FaultException: authN failed: ‘…’ of PasswordCredential

    Ever see “FaultException: authN failed: ‘…’ of PasswordCredential” when trying to call a method that uses Windows Azure and the Access Control Service? The issue is simply that the password is not correct.

    For example, here’s a snippet of a client trying to call a method in a Windows Azure service (“MyEndpoint”), which will throw the FaultException. (Assume that my solution name is “PineCreek”, and my Live Id account for the ACS control panel is timber@example.com).

    ServiceClient proxy = new ServiceClient("MyEndpoint");
    proxy.ClientCredentials.UserName.UserName = "PineCreek";
    proxy.ClientCredentials.UserName.Password = "badpassword";
    proxy.DoMethod(); // this will throw FaultException: authN failed

    As shown, the the wrong password was entered. The user name and password used here is the same as the .NET Services solution name and password (which is also different than the Live ID used to log in to the Access Control Service control panel).

    The fixed code is as follows:

    ServiceClient proxy = new ServiceClient("MyEndpoint");
    proxy.ClientCredentials.UserName.UserName = "PineCreek";
    proxy.ClientCredentials.UserName.Password = "ValidPassword";
    proxy.DoMethod(); // this will now succeed

    (Again, this also shows that the Live Id account doesn’t get used in the code).

    Note: the Access Control Service credential management page is at https://accesscontrol.ex.azure.microsoft.com/ManageAccount.aspx

    For reference, the exception is as follows:
    System.ServiceModel.FaultException was unhandled
    Message="authN failed: 'PineCreek' of PasswordCredential (#6a4d0ffb-4c3b-1cd8-d284-11660ae4cb08)"
    Source="mscorlib"
    Action="http://www.w3.org/2005/08/addressing/soap/fault"
    StackTrace:
    Server stack trace:
    at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)
    at System.ServiceModel.Security.IssuanceTokenProviderBase`1.GetTokenCore(TimeSpan timeout)
    at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)

  • Debugging FaultException: matched scope not found (Access Control Service)

    FaultException: matched scope not found: applies-to-address is ‘…’

    This can occur when trying to use a client that uses a service that uses the Access Control Service. The following snippet shows the code around the exception:

    ServiceClient proxy = new ServiceClient("CalculatorEndpoint");
    proxy.ClientCredentials.UserName.UserName = "user";
    proxy.ClientCredentials.UserName.Password = "pass";
    proxy.DoSomething(); // exception occurs here

    The issue is that the service that you’re writing still needs to be set up with the Access Control Service. The Access Control Service needs to know the “scope”, or address of the service for which the credentials apply.

    For example, if a service is hosted at http://example.com/MyService, then the scope is simply “http://example.com/MyService”. The address can even be your local machine (e.g. your dev machine), if that’s where the service is deployed (for example, “http://localhost:58260/Service.svc/ws”).

    Scopes can be set via the Access Control Service website at https://accesscontrol.ex.azure.microsoft.com/ManageScopes.aspx

    (Scopes can be set programmatically – see the Management\AtomClient sample in the .NET Services SDK for an excellent example. On my machine it’s located at C:\Program Files\Microsoft .NET Services SDK (July 2009 CTP)\Samples\AccessControl\ExploringFeatures\Management\AtomClient\CS35 )

    From the Access Control Service management page:

    clip_image001

    First add a new scope by going to the Scopes page in the Access Control Service and clicking “Add Scope”.

    clip_image002

    Add the scope name and save it. The scope URI is the same as the location of your service. (In this example, the address of the service is “http://localhost:58260/Service.svc/ws” so I enter that as the Scope URI).

    Don’t forget to add the encryption certificate if needed, otherwise you’ll see an unhandled “FaultException: cert not found: applies-to-address is 'http://localhost:58260/Service.svc/ws” when trying to call a method on the proxy.

    clip_image003

    I’ve been using the certificate that comes with the .NET Services SDK

    (on my machine it is located at C:\Program Files\Microsoft .NET Services SDK (July 2009 CTP)\Samples\AccessControl\GettingStarted\UserNamePasswordCalculatorService\CS35\Utils)

    When done, the scopes for your solution will list the newly-added scope

    clip_image004

    Note that once the service has been deployed to the cloud and has a public address that a new scope will need to be added to match the new address of the deployment.

    That’s it!

    For reference, the exception is as follows:
    Error
    System.ServiceModel.FaultException was unhandled
    Message="matched scope not found: applies-to-address is 'http://localhost:58260/Service.svc/ws' (#e2d1d0ef-df30-6681-e1ca-d4cd48e3cb08)"
    Source="mscorlib"
    Action="http://www.w3.org/2005/08/addressing/soap/fault"
    StackTrace:
    Server stack trace:
    at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)
    at System.ServiceModel.Security.IssuanceTokenProviderBase`1.GetTokenCore(TimeSpan timeout)
    at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
    [etc]

  • Dumping logs from the Azure Development Fabric

    How to view Azure logs (RoleManager.WriteToLog ) when running under the Development Fabric:

    1. Open the Development Fabric and get the deployment id. For example, if the deployment title reads "deployment(26)", the id is "26". 
      devfabric
    2. To dump the logs to an xml file, from a command prompt run csrun.exe with the dumplogs flag
      1. For example, "csrun /dumplogs:26;." will dump the logs for the deployment (26) into the current directory (.)
      2. A log file will be created for each role. For example:
        1. deployment(26).PresenceCloud.PresenceService.0.xml
        2. deployment(26).PresenceCloud.PresenceService_Worker.0.xml
      3. The log contains XML where each <Event> tag corresponds to the calls made by RoleManager.WriteToLog(). For example, the contents of the log look like:

        <?xml version="1.0" encoding="utf-8"?>
        <ServiceDiagnostics
        Service="deployment(26)"
        ServiceDeployment="deployment(26)"
        Role="PresenceService"
        RoleInstance="deployment(26).PresenceCloud.PresenceService.0">
        <Events>
        <Event
        Time="2009-08-13T19:03:11.7620594Z"
        Name="Information"
        Severity="Info"
        ThreadId="5676">
        <EventProperty
        Name="message">Entered Constructor()</EventProperty>
        </Event>
        <Event
        Time="2009-08-13T19:03:11.7645300Z"
        Name="Information"
        Severity="Info"
        ThreadId="5676">
        <EventProperty
        Name="message">Returned from Constructor()</EventProperty>
        </Event>
        </Events>
        </ServiceDiagnostics>

        Note: csrun.exe is a tool provided by the Windows Azure SDK. By default it is installed to C:\Program Files\Windows Azure SDK\v1.0\bin\csrun.exe

    3. Viewing the contents of a MUI file

      Need to look at the strings in a MUI file? Here's an easy was to do it with Visual Studio:
       
      In the VC file.open dialog boxes there is an "open as" or "open with" drop down.
      Select "resources" or "resource editor".
      It's also trivial to write a custom dumper yourself starting with  the EnumResource APIs...
       
    4. Investigation: Text Service Framework (TSF) and Keyboards

      Overview

      Windows has an entire API for text input and interaction.

      The Text Services Framework (TSF) is a COM framework and API that supports advanced text input and text processing. It is designed to offer advanced language and word processing features to applications. It supports features such as multilingual support, keyboard drivers, handwriting recognition, speech recognition, as well as spell checking and other text and natural language processing functions.

      Architecture

      The diagram is below but please see the details at http://msdn.microsoft.com/en-us/library/ms538050(VS.85).aspx

      Architecture of Text Services Framework

      Using TSF

      TSF can be implemented as an app or as a text service.

      For a keyboard, we’d be writing a TSF text service.

      • A text service can obtain text from, and write text to, an application. A text service can also associate data and properties with a block of text. A text service is implemented as a COM in-proc server that registers itself with TSF. When registered, the user interacts with the text service using the language bar or keyboard shortcuts. Multiple text services can be installed.
      • TSF-aware apps can provide the input context or scope (e.g. “url”, “name”, “address”)

      On the app side, extensibility is done by the app by implementing interfaces and registering them with TSF.

      TSF can read the current "context" from the application, which . The "context" is the characters on the screen around the insertion point.

      TSF and Managed Code:
      Difficult since text service gets loaded into arbitrary processes, so they need to be small and lightweight, among other reasons. http://blogs.msdn.com/tsfaware/archive/2007/04/19/tsf-and-managed-code.aspx

      Legacy apps:
      TSF has a table of controls for legacy apps that describes the input scope (e.g. the address bar control in IE5 takes a “url”)

      Other notes:
      The Tablet PC TIP uses TSF to provide text to apps.

      References

    5. Access Control Service and UserNamePasswordCalculatorService

      Having problems getting the Access Control Service UserNamePasswordCalculatorService sample to work due to certificate problems? The issue may be that InstallCerts.bat may not be installing the certificates correctly. See the following thread for how to fix it:

      http://social.msdn.microsoft.com/Forums/en-US/netservices/thread/1d09fc5e-fbbc-4e98-b14b-ab69c0d9e1c4/

      Also, if you're using a beta version of IE8 with Vista and get a blank screen when associating a CardSpace card with your account, see this thread on showing the site in compatibility mode:

      http://social.msdn.microsoft.com/Forums/en-US/netservices/thread/30ba7abe-5808-4acc-9d10-20c585b8f3e2/

    6. Media Center Gadgets Video Review

      jk on the Run points to a video review of the Media Center gadgets for Windows SideShow:http://www.jkontherun.com/2008/11/windows-mobil-1.html

      Have feedback about the gadgets? Please get in touch and let us know.

    7. Automatically implementing classes in Visual Studio 2008

      Automatically implementing classes in Visual Studio 2008

      VS2008 Tip:

      Automatically implement abstract interfaces

      1) Write derived class
      public class DerivedClass : BaseClass
      {
      }

      2) Right click on "BaseClass" and select "Implement Abstract Class"

      3) Fill in your code

    8. Binding to a MarkupExtension that Returns a Binding

      Is it possible to bind properties to a MarkupExtension that returns a Binding? Yes! The MarkupExtension just needs to return a BindingExpression by returning binding.ProvideValue(serviceProvider):

       

          [MarkupExtensionReturnType(typeof(BindingExpression))]

          public class PhysicalLengthMarkupExtension : MarkupExtension

          {

              public override object ProvideValue(IServiceProvider serviceProvider)

              {

                  Binding physicalLengthBinding = new Binding();

       

                  physicalLengthBinding.Source = _dpiProvider;

                  physicalLengthBinding.Path = new PropertyPath("DPI");

                  physicalLengthBinding.Converter = _dpiConverter;

                  physicalLengthBinding.ConverterParameter = _length;

       

                  return physicalLengthBinding.ProvideValue(serviceProvider);

              }

          }

       

      Which enables the ability to write

      <TextBlock Width="{Markup:PhysicalLengthMarkupExtension 3cm}"/>

       

      instead of the more verbose and redundant

       

              <TextBlock>

                  <TextBlock.Width>

                      <Binding

                        Source="{StaticResource DpiProvider}"

                        Path="DPI"

                        Converter="{StaticResource DpiConverter}"

                        ConverterParameter="2in"

                        />

                  </TextBlock.Width>

              </TextBlock>

       

      (Btw, I know that WPF takes DPI into account when doing layout calculations but let’s just use it as an example here.)

    9. Media Center Gadgets for SideShow released!

      We've just relased the Windows Media Center gadgets for SideShow!

      There are four gadgets – TV, Music, Pictures + Videos, and Now Playing – that let you browse and control your Media Center PC from any SideShow remote control or device, or even a Windows Mobile phone (if it has the platform installed). The gadgets let you browse the TV guide and details, recorded shows, your photos, music (with cover art), and have playback controls to start/stop/record/etc media.

      It was a pleasure to work with the SideShow team on this project. Thanks to everyone in the community for your feedback via Microsoft Connect and community sites. We read every comment and used them to make the gadgets better or just used as feedback for the future.

      Download locations:
      Install the 32-bit version
      Install the 64-bit version

      For more details, please see the SideShow blog at http://blogs.msdn.com/sideshow/archive/2008/10/21/media-center-gadgets-for-sideshow-released-available-on-the-windows-live-gallery.aspx

    10. Hidden Forms Windows

      Trying to hide your forms window? Here are a couple sample solutions:

      One cumbersome solution is to override WndProc, listen for any window position changing messages (which includes z-order), and then not pass any show window flag on.

      public class MyForm : Form
      {
          public MyForm()
          {
              // Ensure that this is a hidden window
              this.WindowState = FormWindowState.Minimized;
              this.ShowInTaskbar = false;
              this.FormBorderStyle = FormBorderStyle.None;
          }

          protected override void WndProc(ref Message m)
          {
              const uint WM_WINDOWPOSCHANGING = 0x0046; // WinUser.h
              const uint SWP_SHOWWINDOW       = 0x0040; // WinUser.h

              if (m.Msg == WM_WINDOWPOSCHANGING)
              {
                  // Ensure the window is hidden by consuming any "show window" requests
                  // (which can happen when pressing alt+tab)
                  Win32Api.WINDOWPOS windowPos = (Win32Api.WINDOWPOS)Marshal.PtrToStructure(m.LParam, typeof(Win32Api.WINDOWPOS));
                  windowPos.flags &= unchecked(~SWP_SHOWWINDOW);
                  Marshal.StructureToPtr(windowPos, m.LParam, true);
                  m.Result = (IntPtr)0;
              }

              base.WndProc(ref m);
          }
      }

      The better solution is to simply make the window not visible after it finishes loading:

      public class MyForm : Form
      {
          public MyForm()
          {
              // Ensure that this is a hidden window
              this.WindowState = FormWindowState.Minimized;
              this.ShowInTaskbar = false;
              this.FormBorderStyle = FormBorderStyle.None;

              this.Load += new EventHandler(MyForm_Load);
          }

          void MyForm_Load(object sender, EventArgs e)
          {
              this.Visible = false;
          }
      }

    11. Using IPC Channels and with Multiple Users

      When I'm working with a new technology or concept, I find that an ultra simple, bare bones code sample or app is one of the most useful things to use for getting started. When it comes to understanding how to work with IPC channels (named pipes), the best example I've see is at Ohad's blog at http://weblogs.asp.net/israelio/archive/2005/01/04/346180.aspx

      It is mentioned that config files can be used instead of manually coding up everything. In some cases writing up the code is necessary. For example, the project I'm working on can be run by multiple users and each user has both a IPC client as well as an app domain containing the IPC server. This means that multiple named pipes need to be created, and the channel names must be unique per user so that multiple users can run the program. (If the same pipe name is used for everyone then an AccessDenied remoting exception will be generated).

      From MSDN: "You cannot register a channel that listens on a specific port more than once. Even though channels are registered on a per-application-domain basis, different application domains on the same machine cannot register the same channel listening on the same port." http://msdn.microsoft.com/en-us/library/dkfd3wha(VS.80).aspx

      To keep the pipe names unique per user, I simply add the current user domain and name. For example,

      IDictionary props = new Hashtable();
      props["portName"] = "MyAppClientPort" + Environment.UserDomainName + Environment.UserName;
      props["name"] = "MyAppClientName" + Environment.UserDomainName + Environment.UserName;

      IpcChannel ipcChannel = new IpcChannel(props, null, null);
      ChannelServices.RegisterChannel(ipcChannel, false);

       

    More Posts Next page »

    © 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
    Microsoft
    Page view tracker