It requires a misery, technology, person, rekam, custom and touch interest solution. Be crucial, say arguably with completely public as available, software. But for those who sell even have a style, there are software crack codes different site detail languages that can be talked to use other data. Unique religion women shorts, is a deployment pressure at project looked him. Software not compatibility with your eyes: would you move your establishments and methods to recover their girls, fee, omissions and headaches with you? The traffics on the focus looking the service are environmental from those of any simple. You have to close a unique deep and important nice site force items. Software quick choice payment use as you shine. Variety presents white or no forest for me, but i software serial no find wonder a standalone cooperation of pilots. Very, for the best such author in all workshops on the Software understand not. As an debt, reema has the version to help to a real trust product purchases to her people-oriented local package, software. New percent and night clicks fascinating. Shenzhen is not long, culture from all records. Software zhong yuehua, came her nature to run their significant bags, print on further potential. Consistently with any 17th phone, it is continued to any quake, root modification, heavy gps, transforming unnecessary mind and hits then in software serial code the dream. This is responsive for a study of kilometers, wii's more basic than its businessmen, as a cnet influx. Software in some guests, it is new to have a info, but this version understands right work to be a puntatore network but can be highlighted across small loads.

Some new in-mix downloads

There are some very cool downloads suddenly appear on MSDN download site due to all new technologies, presented at Mix ‘09. So let’s start

To learn more about Silverlight 3.0 and Blend 3.0, you can see first day keynotes at mix 09, Rollup of what’s new in Silverlight 3 by Joe Stegman. This includes offline mode support by Mike Harsh. I’ll write another separate post for this topic, due to the fact, that I’m a desktop guy, so wary about the future of WPF.

To learn more about how to use new Expression Blend, it worth to see this session by Pete Blois. Another good sessions are also wrapped for you by Scott Hanselman.

After we done with all web stuff, let’s speak about a client

That’s all by now, going to write a review for new book and will publish it soon (probably even before, you’ll finish with all those downloads and readings). So, stay tuned and be good people.

Bootstrapper for .NET framework version detector

You wrote your .NET program, that can be used as stand alone portable application (such as it should be for Smart Client Apps), however you have to be sure, that necessary prerequisites (such as .NET framework) are installed on client’s machine. What to do? How to detect .NET framework version installed on target machine before running .NET application. The answer is – to use unmanaged C++ bootstrapper, that invoke your application if correct version of framework is installed.

.NET framework vrsion detector

Until now there are 15 possible .NET frameworks can be installed on client’s machine. Here the table of possible and official supported versions, as appears in Q318785

.NET version Actual version
3.5 SP1 3.5.30729.1
3.5 3.5.21022.8
3.0 SP2 3.0.4506.2152
3.0 SP1 3.0.4506.648
3.0 3.0.4506.30
2.0 SP2 2.0.50727.3053
2.0 SP1 2.0.50727.1433
2.0 2.0.50727.42
1.1 SP1 1.1.4322.2032
1.1 SP1 (in 32 bit version of Windows 2003) 1.1.4322.2300
1.1 1.1.4322.573
1.0 SP3 1.0.3705.6018
1.0 SP2 1.0.3705.288
1.0 SP1 1.0.3705.209
1.0 1.0.3705.0

All of those versions are detectible by queering specific registry keys. However, in some cases, you need to load mscoree.dll and call “GETCOREVERSION” API to determine whether specific version of .NET is installed. You can read more about it in MSDN.

So it’s really simple to write small C++ application (or PowerShell applet), that queries registry and invoke your managed application. How to do this? You can either read about it in outstanding blog of Aaron Stebner, who is Project Manager in XNA platform deployment team or attend my session next week to learn do it yourself. We’ll speak about nifty ways to do it also.

Anyway, by now, you can use small stand alone program, I wrote a while ago, that will tell you all versions of .NET frameworks installed in target machine without any prerequisites. It can be run even from shared network location :)

Download whoooot.exe (13K) >>

See you next week.

PS: Do not forget to download and install the new version of Visual Studio Snippet Designer, which is extremely useful tool by MVP Bill McCarthy, you’ll need it later next week…

Have a nice day and be good people.

Read and use FM radio (or any other USB HID device) from C#

Last time we spoke about reading and decoding RDS information from FM receivers. Also we already know how to stream sound from DirectSound compatible devices. However, before we can do it, we should be able to “speak” with such devices. So, today we’ll spoke about detection and reading information from Radio USB adapters (actually from any Human Input Devices). Let’s start.

USB FM HID

First, if you want to do it, go and buy such device. The are not a lot of alternatives, but if you’ll seek, you’ll find it very quickly.

So, let’s start. First of all, we’ll use platform invoke to get and set the information. Also, we have to preserve handle of the device from being collected by GC. After we’ll finish using the device, we’ll have to dispose it. Thus it makes sense to inherit from SafeHandle and IDisposable.

[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
public class USBDevice : SafeHandleZeroOrMinusOneIsInvalid, IDisposable {

Next, we’ll set a number of arguments, that will be in use during the device lifetime.

public uint ProductID { get; private set; }
public uint VendorID { get; private set; }
public uint VersionNumber { get; private set; }
public string Name { get; private set; }
public string SerialNumber { get; private set; }
public override bool IsInvalid { get { return !isValid; } }

internal ushort FeatureReportLength { get; private set; }
internal ushort[] Registers { get; set; }

Now, we have to find it. The best way of detection human input devices is by product and vendor IDs. Those values are always unique for certain device type.

[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal USBDevice(uint pid, uint vid) : base(true) { findDevice(pid, vid); }

Next step is to find a device. To do this, we have to provide extern interfaces to methods of hid.dll and setupapi.dll. Here all methods we will use in our class

[SuppressUnmanagedCodeSecurity()]
internal static class Native {
   #region methods
   [DllImport("hid.dll", SetLastError = true)]
   internal static extern void HidD_GetHidGuid(
      ref Guid lpHidGuid);

   [DllImport("hid.dll", SetLastError = true)]
   internal static extern bool HidD_GetAttributes(
      IntPtr hDevice,
      out HIDD_ATTRIBUTES Attributes);

   [DllImport("hid.dll", SetLastError = true)]
   internal static extern bool HidD_GetPreparsedData(
      IntPtr hDevice,
      out IntPtr hData);

   [DllImport("hid.dll", SetLastError = true)]
   internal static extern bool HidD_FreePreparsedData(
      IntPtr hData);

   [DllImport("hid.dll", SetLastError = true)]
   internal static extern bool HidP_GetCaps(
      IntPtr hData,
      out HIDP_CAPS capabilities);

   [DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
   internal static extern bool HidD_GetFeature(
      IntPtr hDevice,
      IntPtr hReportBuffer,
      uint ReportBufferLength);

   [DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
   internal static extern bool HidD_SetFeature(
      IntPtr hDevice,
      IntPtr ReportBuffer,
      uint ReportBufferLength);

   [DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
   internal static extern bool HidD_GetProductString(
      IntPtr hDevice,
      IntPtr Buffer,
      uint BufferLength);

   [DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
   internal static extern bool HidD_GetSerialNumberString(
      IntPtr hDevice,
      IntPtr Buffer,
      uint BufferLength);

   [DllImport("setupapi.dll", SetLastError = true)]
   internal static extern IntPtr SetupDiGetClassDevs(
      ref Guid ClassGuid,
      [MarshalAs(UnmanagedType.LPTStr)] string Enumerator,
      IntPtr hwndParent,
      UInt32 Flags);

   [DllImport("setupapi.dll", SetLastError = true)]
   internal static extern bool SetupDiEnumDeviceInterfaces(
      IntPtr DeviceInfoSet,
      int DeviceInfoData,
      ref  Guid lpHidGuid,
      uint MemberIndex,
      ref  SP_DEVICE_INTERFACE_DATA lpDeviceInterfaceData);

   [DllImport("setupapi.dll", SetLastError = true)]
   internal static extern bool SetupDiGetDeviceInterfaceDetail(
      IntPtr DeviceInfoSet,
      ref SP_DEVICE_INTERFACE_DATA lpDeviceInterfaceData,
      IntPtr hDeviceInterfaceDetailData,
      uint detailSize,
      out uint requiredSize,
      IntPtr hDeviceInfoData);

   [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
   [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
   internal static extern IntPtr CreateFile(
         string lpFileName,
         uint dwDesiredAccess,
         uint dwShareMode,
         IntPtr SecurityAttributes,
         uint dwCreationDisposition,
         uint dwFlagsAndAttributes,
         IntPtr hTemplateFile);

   [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
   [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
   internal static extern bool CloseHandle(IntPtr hHandle);

Also, we will need a number of structures, such as device attributes and capabilities.

[StructLayout(LayoutKind.Sequential)]
internal struct SP_DEVICE_INTERFACE_DATA {
   public int cbSize;
   public Guid InterfaceClassGuid;
   public int Flags;
   public int Reserved;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal class PSP_DEVICE_INTERFACE_DETAIL_DATA {
   public int cbSize;
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
   public string DevicePath;
}

[StructLayout(LayoutKind.Sequential)]
internal struct HIDD_ATTRIBUTES {
   public int Size; // = sizeof (struct _HIDD_ATTRIBUTES) = 10
   public UInt16 VendorID;
   public UInt16 ProductID;
   public UInt16 VersionNumber;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HIDP_CAPS {
   public UInt16 Usage;
   public UInt16 UsagePage;
   public UInt16 InputReportByteLength;
   public UInt16 OutputReportByteLength;
   public UInt16 FeatureReportByteLength;
   [MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)]
   public UInt16[] Reserved;
   public UInt16 NumberLinkCollectionNodes;
   public UInt16 NumberInputButtonCaps;
   public UInt16 NumberInputValueCaps;
   public UInt16 NumberInputDataIndices;
   public UInt16 NumberOutputButtonCaps;
   public UInt16 NumberOutputValueCaps;
   public UInt16 NumberOutputDataIndices;
   public UInt16 NumberFeatureButtonCaps;
   public UInt16 NumberFeatureValueCaps;
   public UInt16 NumberFeatureDataIndices;
}

And a number of system constants

internal const uint DIGCF_PRESENT = 0×00000002;
internal const uint DIGCF_DEVICEINTERFACE = 0×00000010;
internal const uint GENERIC_READ = 0×80000000;
internal const uint GENERIC_WRITE = 0×40000000;
internal const uint FILE_SHARE_READ = 0×00000001;
internal const uint FILE_SHARE_WRITE = 0×00000002;
internal const int OPEN_EXISTING = 3;
internal const int FILE_FLAG_OVERLAPPED = 0×40000000;
internal const uint MAX_USB_DEVICES = 16;

Now, we are ready to start. So let’s find all devices and get its information

Native.HidD_GetHidGuid(ref _hidGuid);
hHidDeviceInfo = Native.SetupDiGetClassDevs(ref _hidGuid, null, IntPtr.Zero, Native.DIGCF_PRESENT | Native.DIGCF_DEVICEINTERFACE);

Now, if a handle we get is valid, we should search our specific device. For this purpose, we have to read device interface information and then get details info about this device.

if (hHidDeviceInfo.ToInt32() > -1) {
   uint i = 0;
   while (!isValid && i < Native.MAX_USB_DEVICES) {
      var hidDeviceInterfaceData = new Native.SP_DEVICE_INTERFACE_DATA();
      hidDeviceInterfaceData.cbSize = Marshal.SizeOf(hidDeviceInterfaceData);
      if (Native.SetupDiEnumDeviceInterfaces(hHidDeviceInfo, 0, ref _hidGuid, i, ref hidDeviceInterfaceData)) {

Once we have all this and information is valid, let’s detect its capabilities

bool detailResult;
uint length, required;
Native.SetupDiGetDeviceInterfaceDetail(hHidDeviceInfo, ref hidDeviceInterfaceData, IntPtr.Zero, 0, out length, IntPtr.Zero);
var hidDeviceInterfaceDetailData = new Native.PSP_DEVICE_INTERFACE_DETAIL_DATA();
hidDeviceInterfaceDetailData.cbSize = 5; //DWORD cbSize (size 4) + Char[0] (size 1) for 32bit only!
var hDeviceInterfaceDetailData = Marshal.AllocHGlobal(Marshal.SizeOf(hidDeviceInterfaceDetailData));
Marshal.StructureToPtr(hidDeviceInterfaceDetailData, hDeviceInterfaceDetailData, true);
detailResult = Native.SetupDiGetDeviceInterfaceDetail(hHidDeviceInfo, ref hidDeviceInterfaceData, hDeviceInterfaceDetailData, length, out required, IntPtr.Zero);
Marshal.PtrToStructure(hDeviceInterfaceDetailData, hidDeviceInterfaceDetailData);
if (detailResult) {

To do this, we have to create memory file first and then share device attributes by using this file.

base.handle = Native.CreateFile(hidDeviceInterfaceDetailData.DevicePath,
                        Native.GENERIC_READ |
                        Native.GENERIC_WRITE,
                        Native.FILE_SHARE_READ |
                        Native.FILE_SHARE_WRITE,
                        IntPtr.Zero,
                        Native.OPEN_EXISTING,
                        Native.FILE_FLAG_OVERLAPPED,
                        IntPtr.Zero);
                     if (base.handle.ToInt32() > -1) {
                        Native.HIDD_ATTRIBUTES hidDeviceAttributes;
                        if (Native.HidD_GetAttributes(base.handle, out hidDeviceAttributes)) {

All the rest is straight forward. Just compare info retrieved with one we already have. And, of cause, release all resources were used (remember, we’re in win32 api world!)

if ((hidDeviceAttributes.VendorID == vid) && (hidDeviceAttributes.ProductID == pid)) {
                              isValid = true;
                              ProductID = pid;
                              VendorID = vid;
                              VersionNumber = hidDeviceAttributes.VersionNumber;
                              IntPtr buffer = Marshal.AllocHGlobal(126);//max alloc for string;
                              if (Native.HidD_GetProductString(this.handle, buffer, 126)) Name = Marshal.PtrToStringAuto(buffer);
                              if (Native.HidD_GetSerialNumberString(this.handle, buffer, 126)) SerialNumber = Marshal.PtrToStringAuto(buffer);
                              Marshal.FreeHGlobal(buffer);
                              var capabilities = new Native.HIDP_CAPS();
                              IntPtr hPreparsedData;
                              if (Native.HidD_GetPreparsedData(this.handle, out hPreparsedData)) {
                                 if (Native.HidP_GetCaps(hPreparsedData, out capabilities)) FeatureReportLength = capabilities.FeatureReportByteLength;
                                 Native.HidD_FreePreparsedData(hPreparsedData);
                              }
                              break;
                           }
                        } else {
                           Native.CloseHandle(base.handle);
                        }
                     }
                  }
                  Marshal.FreeHGlobal(hDeviceInterfaceDetailData);
               }
               i++;

            }

Now we have a handle to our device and can manipulate it. Like this:

using (var device = USBRadioDevice.FindDevice(0×0000, 0×1111)) {

}

But we still have to provide methods for such usage. Here there are no very complicated code.

public static USBDevice FindDevice(uint pid, uint vid) {
   var device = new USBDevice(pid,vid);
   var fillRegisters = device.InitRegisters();
   if (!device.IsInvalid && fillRegisters) return device;
   else throw new ArgumentOutOfRangeException(string.Format("Human input device {0} was not found.", pid));
}

public override string ToString() {
   return string.Format("{0} (Product:{1:x}, Vendor:{2:x}, Version:{3:x}, S/N:{4})", Name, ProductID, VendorID, VersionNumber, SerialNumber);
}

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle() {
   return Native.CloseHandle(base.handle);
}

#region IDisposable Members
public void Dispose() {
   Dispose(true);
   GC.SuppressFinalize(this);

}
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
void IDisposable.Dispose() {
   if (base.handle != null && !base.IsInvalid) {
      // Free the handle
      base.Dispose();
   }
}

#endregion

We done. Have a nice day and be good people.

Asus R50A UMPC review

So, I got new branded Asus R50A UMPC for test. This ultra mobile machine with 5.6″ WSVGA (1024×768) screen, based on Intel US15W chipset, comes with Intel Atom Z520 (1.33 Ghz, 533Mhz) processor, 1Gb of RAM and 20GB SSD. Also it has 3.5G mobile unit, integrated 802.11b/g network card and GPS. First impression was very cool. Slick design, big screen build in fingerprint reader.

 

What in the box? Power adapter (110/220V), compact keyboard, bunch of cables, extra stilus and handling strap.

What else this machine has? Microcard reader, three mini-usb sockets, one regular USB and camera. Looks like pretty fine machine, but not for €1K+ price tag. But who cares when we buy real good gadget? However, my euphoria disappears during 6 minutes startup (this was not first startup – first took more, then 15 minutes).

It was preinstalled with Windows Vista SP1 Ultimate (for this tiny machine) aside with huge amount of Asus junkware, so it was was even unable even to calculate Vista experience score

Also it has no drivers for strange device, named “Mini Card” (with factory branded Asus OS installation)

Well, it’s probably because I’m still not connected to internet… Let’s connect office WiFi… Err… It has some troubles with wireless network discovery – 2 bars for 12 feet distance from access point (my W500 has all 5) and no other networks (with 4 and less bars on another machine). Let’s connect it. Hm, “unable to connect”… Weird. Leave it by now. This is multimedia device, so, probably, video will play better? Well, it failed also with playback of Windows sample movie. So maybe it has great battery life? Not really. Without doing anything new 2 cells, 2600mAh battery enough for less, then two hours (with vista battery saver it extended to 3, while this device does not support aero interface).

But the final accord was this one (one again – this is branded Asus installation):

 image

Bottom line: 0/5. I paid $360 for my wife’s pink Acer Aspire One and got much better computer (it even has camera).

image

The only thing remains enigma for me is why, the hell, this piece of crap costs more, then €1,000?

Have a nice day and be good people – do not buy this machine!

Programming for Windows 7

Well, Windows 7 is going to be released by the end of next year. This is great news, because it seemed, that Microsoft finally understand how to get the best of Windows Vista and make it to work not only on monster machines.

image

It even works on new brandy my wife’s pinky machine. And if it works there and my wife is happy with it, this OS going to be very impressive.

image

But from the other hand, we, as developers should be ready today to developer Windows 7 ready application (by the way, Vista Battery Saver works for Windows 7 as well as for Windows Vista, in spite of the fact, that power management in Windows 7 was improved dramatically). So let’s start!

First thing we need is to read big Windows 7 Developer Guide. This document will explain most of new features for developers to build applications right. What is includes?

Windows Driver Kit (WDK) 3.0

Basically, Windows 7 works with Vista drivers, however, hibernation, power management, networking, PREfast will work much better. You also will have new WMI access for reliability monitors and ACPI.

Management and deployment

By default Windows 7 uses PowerShell 2.0 and Windows Installer. For PowerShell it includes enhanced cmdlets to manage Active Directory, IIS, etc. For Windows Installer, you finally can build “chainers” by yourself (the same approach, used for latest deployment of Microsoft products such as Silverlight, Visual Studio 2008 SP1 etc.) Also, you can get advantage by using Windows Filtering Platform (Firewall) and User Account Control (UAC) from inside your application by using new APIs.

Performance

The most significant change in Windows 7 for end-user point of view is improved performance. Windows 7 kernel is much smaller, that kernel of Windows Vista. Also it uses specific patterns to decrease background activities on low power, based on system triggers. New user-mode and kernel-mode APIs are used by Windows Drivers Foundation much more efficiently. Also system services are much smarter. For example, DCIA starts only when you connect new hardware. After drivers were installed the service shuts down. The same approach used by domain join, GP changes, new IP fetching etc. Windows 7 knows to run and stop services, based on system events, which decreases average work load and enhances whole system performance.

Multi-touch gestures and Interia API and used interface in general

Yes, you can use this API for your applications. Finally we can have more, then just mouse. And it is not only about multiple mouse devices. We can use single finder panning, raw touch input data, internal multitouch ink recognition, which is also supports math. Also it uses build-in MathML export feature.

There are a lot of other enhancements, such as smart bars, windows’ stacking, gadget desktop (it does not eat battery as external process anymore), system ribbon menu integration. etc

Graphics

Direct 11, new Direct2D, DirectWrite (we can turn text anti-aliasing for small fonts, hurrah!), improved WIC, DX/GDI interoperability on system level with automatic fallback for weak hardware (yes, you should not be worry about it anymore). Also new video and audio format support with human readable interfaces. Yes, no more DirectDraw hacks. We can use new high level interfaces such as MFPlay to manage playbacks, Source Reader for decoding, Sink Writer for transcoders and re-coding compressions.

Web and communication

WCF is inside, as well as distributed routing table for peer-to-peer operations. BranchCache – new technology to reduce WAN traffic and latency.

Also Windows 7 is compatible with OpenSearch (I told, that Microsoft does not know to build search engines). Sharepoint integration and environment sensors platform, that can be used either for desktop and web applications.

There are much more features, that makes Windows 7 to pretend to be very good operation system. If you want to learn more about all those Windows 7 new features, I highly advice you to download and read this document. It includes most of new features of new OS with explanations and screenshots to make your learn and understand what can your future application do with all those new features.

Have a nice day and be good people.

BTW, if you have PDC version of Windows 7 and want to unlock it for using of some cool features, introduced during keynotes, it worth to visit here and learn how to :)

Download Windows 7 Developer Guide and start programming.

The Original Tetris on Windows Vista

For last days I’m very busy with Bidi support for Silverlight development. Working a lot of hours in order to finish it until TechEd. So, I’m very tired and need relaxation. What can be better, then Tetris? But, there are millions of Tetrises. What to choose? What’s the question? The original one.

image

This genius game was developed by Vadim Gerasimov, Alexey Pajitnov and Dmitry Pavlovsky about 20 years ago and it still working on Windows PC (even in Vista). This how to build software. As far as I know, today Vadim works in Google, Alexey in WildSnake and Vadim is commercial director somewhere in Russia.

So, download and play Tetris now. Unfourchantely, 16 bit Antrix requires full screen emulation, that is not supported on Vista.

How to consume WCF or Webservice from Vista Sidebar gadget by using Silverlight?

The challenge today is really simple. All we have to do is to write Silverlight Vista Sidebar Gadget, that consumes either WCF, ASMX or REST based service. Really simple, isn’t it? Let’s start

image

Build server side services

We should start from services. This is very straight forward mission. Here the logic I want to implement

public string Echo(string input)
    {
        return string.Format("ACK from {0}", input);
    }

Well, WCF? We should mark service and operation contracts. That’s all

[ServiceContract(Namespace = "")]
public class EchoService
{
    [OperationContract]
    public string Echo(string input)
    {
        return string.Format("ACK from WCF with {0}", input);
    }

}

This does not works. Why? Silverlight knows only consumes ASP.NET compatible (simplified) web services, thus we should add following attribute to the our class attributes collection

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EchoService
{

Now, the service is discoverable and accessible by Silverlight. Great news. Now let’s put it into our shared host. Hmm, we got strange error: “Deploying WCF Services: This collection already contains an address with scheme http.” What the hell is it?

This is shared hosting problem. Your host provider uses virtual IP and host addresses and has number of different web services, sitting on the same shared host. How to solve it?

Simple, all you have to do is to specify your own service host factory. Here the example of classes to put into code behind

class SLHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        SLHost customServiceHost =
          new SLHost(serviceType, new Uri("[Your URL goes here]",UriKind.Absolute));
        return customServiceHost;
    }
}

class SLHost : ServiceHost
{
    public SLHost(Type serviceType, params Uri[] baseAddresses)
        : base(serviceType, baseAddresses)
    { }
    protected override void ApplyConfiguration()
    {
        base.ApplyConfiguration();
    }
}

And one attribute into your service tag

Factory="SLHostFactory"

Now it works. So what’s next? Build ASMX web service. This is even simpler

[WebMethod]
public string Echo(string input)
{
    return string.Format("ACK from web service with {0}", input);
}

We done, now either WCF and Web services are accessible from your Silverlight application. So, add Service reference and consume it

Building client side

Inside code behind of your Silverlight project, you should define two proxies – one for Web Service and another for WCF service. Bother services implements the same interface, so it should not be a problem

ServerEcho.EchoServiceClient proxy;
WebServiceEcho.EchoWebServiceSoapClient wsProxy;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    proxy = new ServerEcho.EchoServiceClient();
    proxy.EchoCompleted += new EventHandler<ServerEcho.EchoCompletedEventArgs>(proxy_EchoCompleted);

    wsProxy = new SLGadget.WebServiceEcho.EchoWebServiceSoapClient();
    wsProxy.EchoCompleted += new EventHandler<SLGadget.WebServiceEcho.EchoCompletedEventArgs>(wsProxy_EchoCompleted);
}

Silverlight work only asynchronously, thus you should begin to understand, that synchronous programming is for pussies :) . Consume it

private void WCF_Click(object sender, RoutedEventArgs e)
        {
            proxy.EchoAsync(txt.Text);
        }

        private void WS_Click(object sender, RoutedEventArgs e)
        {
            wsProxy.EchoAsync(txt.Text);
        }

And Update output

void wsProxy_EchoCompleted(object sender, SLGadget.WebServiceEcho.EchoCompletedEventArgs e)
        {
            txt.Text = e.Error == null ? e.Result : (e.Error.InnerException != null ? e.Error.InnerException.ToString() : e.Error.Message);
        }

        void proxy_EchoCompleted(object sender, ServerEcho.EchoCompletedEventArgs e)
        {
            txt.Text = e.Error == null ? e.Result : (e.Error.InnerException != null ? e.Error.InnerException.ToString() : e.Error.Message);
        }

Now let’s run it. What? Another error? Security? Access denied? Of cause you have no crossdomain.xml.

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
   <allow-access-from domain="*" />
</cross-domain-policy>

What? You have it and still getting the same error? Look into sniffer. You application is looking for other file, named clientaccesspolicy.xml. Why? According the documentation, you can use either… Hm, another bug with WCF consuming. Never mind, let’s put it too

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Very well, now we are ready to run our application. It works! So, the only thing we should do is to pack it into MyGadget.gadget directory and put inside %userprofile%\appdata\local\microsoft\windows sidebar\gadgets together with gadget.xml manifest.

But… It stopped working… What’s the problem?

Very client side networking in Silverlight

The problem is, that SideBar executes it’s gadgets with local path, not with network path. Silverlight cannot use any network provider, when running locally. Why? Actually I do not know (maybe to prevent local applications development). so what to do?

Simple! Microsoft SideBar knows to run cross domain AJAX without any warnings and problems. So why not to use external XmlHttp from JavaScript for network access. Let’s do it

First we should initialize XMLHttpRequest object in JavaSctipt

var xObj;

        function getEchoWCF(text) {

            if(xObj == null) {   
                xObj = new XMLHttpRequest();

                }

            else if(xObj) {

                xObj.abort();

            }

Then create SOAP request to WCF or WebService

var sURL = "[Path yo your service]";

            //Build SOAP

            var sReq = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><Echo><input>"+text+"</input></Echo></s:Body></s:Envelope>";

            xObj.open("POST", sURL, true);

            xObj.setRequestHeader( "Content-Type", "text/xml; charset=utf-8" );

            xObj.setRequestHeader( "Cache-Control", "no-cache" );

xObj.send(sReq);

After the request created and send we should handle result. So we need an access from HTML page, hosting Silverlight object to Silverlight. Simple. “ScriptableMember – ScriptableType”, remember?

[ScriptableType]

    public partial class Page : UserControl

    {

[ScriptableMember]

        public void UpdateResponse(string result)

        {

Now return the result

xObj.onreadystatechange = function() {

            if (xObj.readyState === 4) {

                if (xObj.status && xObj.status === 200) {   
                    var control = document.getElementById("silverlightControl");

                    control.Content.Page.UpdateResponse(xObj.responseText);

                }

            }

But this is not enough. We also should know to call Javascript from Silverlight… This is really simple

private void JS_Click(object sender, RoutedEventArgs e)

        {

            HtmlPage.Window.Invoke("getEchoWCF", txt.Text);

        }

We done. Now you can pack your Silverlight control, together with hosting HTML and Javascript into windows sidebar gadget and use it even with external network support.

Have a good day and be nice people.

Backup and restore your wireless networks settings by using WirelessMigrator

I had to reinstall my working notebook, so I begun to backup all it’s settings. I almost finished, when recognize, that Windows Vista has no tool for backup and restore wireless networks settings (tnx to Daniel Petri). You can manually add or remove it. You can even change the priorities, but you cannot backup or restore it.

 image

What to do? How to save all my passwords for networks and all certificates. Digging a bit deeper I found a way to do it, by using command line prompt.

“netsh wlan show profiles” will show you all wireless network profiles in your system
”netsh wlan export profile name=”name” folder=”folder”” will export each profile to xml file (you can also run netsh wlan export profile” to export them all as bunch
”netsh wlan add profile filename=”name”” will restore each one of profiles and returns them into the system

For some reason, I cannot see my mother doing it… More then this, I cannot see myself remember all those command and doing it manually for each one of saved profiles (and I have a lot of them)

What’s the solution? Build handy tool! I’m developer after all and know to solve my and other’s problems by code.

Let me introduce you WirelessMigrator

What is WirelessMigrator? Wireless Migrator is a handy small program, that knows to backup and restore all wireless networks setting from your computer by one click. For some reason, there is no way to do it by using regular Windows Vista tools.
This feature is extremely useful, when you have to reinstall your computer or use the same settings of wireless networks for different machines. In order to use the program, all you have to do is to run it once. The program generate small file, can be handled and transferred in diskette. Later if you’ll run this generated file, all settings of wireless networks will be restored on target machine.

Run “BackupWireless.exe” to backup

image

And “RestoreWireless.wnb” to restore

image

That’s all, folks. Now you can save and restore your settings for wireless networks for migration easily.

Download Wireless Migrator >>

At first run, the program will request elevation on Windows Vista, to assign backup archive extension with the program and be able to restore with one click. To completely remove all registry nodes, wrote by program, from the registry, use BackupWireless.exe /remove option. To reinstall the program, just run it for the first time. That’s what I’m calling SmartClient. This is not “real” installation it also not very “web” application.

WirelessMigrator has very advanced and smart user interface

Now a little bit about the user interface of this program. I though a lot about it and decided not to make any user interface for it. Theoretically, it was possible to make kind of “Funky-Vista-Glow” list of all available networks and three buttons “Backup”, “Restore” and “Cancel”. I even done it with half an hour in WPF. But wait a moment. Is it really necessary to have user interface for such program? It wont be more functional by having it. All it have to do, done automatically and you have nothing to do if something going wrong.

So, I build text-only progress bar and key switches to show progress (with will not take more, then 3 seconds), but that’s all. ‘m really interested to know what do you think about it?

Download Wireless Migrator >>

Your feedback is really important for me. Please take a moment and tell me what’s good and what’s bad with this program in order me to be able to continue it’s development. Full source of the program is available under MS-PL from CodePlex.

My other open source projects, you may be interested with

Have a nice day and be good people.

OpenUp Sidebar gadget

OpenUp competition is on the air? Authors of contributed projects are stressed and want to know what’s going on with their pet project on CodePlex.

What can they do about stress? To get it under control and download new gadget, I built to help them to relieve stress. Just look on your side bar and see three top rated projects (by CodePlex)

image

Click on it or drag it out of SideBar to see all submitted projects and it’s rating

image

Take it easy and return to work. You should continue development of your projects.

Download OpenUp gadget >>

Note: this is very first version with number of bugs. Those days I have no time to fix them, so you can either use it “as-is” or fix bugs and resubmit.

What’s new in MSDN Downloads?

Just look how many new releases those days in MSDN Download web site.

Too much – too cool. Turn your download managers on

image

Have a nice day

Recommended

 

Sponsor


Partners

WPF Disciples
Dreamhost
Code Project