Aug 26 2016

Old Windows Mobile devices and Windows 10

Category: — Duke @ 06:57

In case you need to work with windows mobile devices but you have windows 10 (Anniversary, in my case) there is no problem

Sync center is already installed and Windows Mobile Device Center is ready to be installed, it already sits in your disk at c:\Windows\WindowsMobile\setup.exe

But… but, some problem may arise if you have (like me) an Windows 10 N or KN

these version doesn’t have the media features like windows media player, which is required ( lol ) by the Device Center.

So first find the Media Feature Pack for N versions of Windows 10 (anniversary) and install it, or make sure it is already installed: in fact it looks like that any major release of windows 10 will destroy the media feature pack already installed bringing back windows to its N version without the added media feature, in that case simply reinstall the feature pack of your new windows version.

Then you can connect your Windows Mobile Device andif everything works, TADAA!! old windows mobile connected to new windows 10!

and if it doesn’t work?

ok that’s interesting: first start the Windows Mobile Device Center by hand at c:\Windows\WindowsMobile\setup.exe

the connect your device… and if it stay in “conenct state” but nothing happens open the windows device manager

you should see a device with a yellow exclamation mark near it.

right click and select “install driver”

this have worked for me and now i’ve the device connected and i’m able to manage it from windows 10

nice!

Tags:

May 16 2016

Turning on a led from powershell over wi-fi, i2c

Category: C# | Hardware | IoT | PIC | PowerShell | Raspberry | Robot — Duke @ 16:44

It is a couple of week i’ve started a new project, something i’ve always wanted to do, but i’ve never had time or resources or… the real will to complete it.

I’m not saying i will make it this time but certainly it is progressing.

Today i’ve reached a critic mass, something interesting and usefull enough to post about it, what the hispter and the millennials calls “minumum viable product”, it will be part of somthing bigger but i want to blog it to not forget it and, as i’ve found difficulties in it, maybe help someone else, who knows?

My project is very “hardware” oriented, something in the real “maker” area. I’m not an hardware guy, but i’ve the minimal skill required to play whit the modern electronics, that at my eyes looks like logo bricks for grown-up (while you treat them as black box).

So here is what i want to do:

I’ve a Raspberry Pi 2, a wi-fi dongle TP-link TL-WN725 (i also have the EDIMAX EW-7811Un but doesn’t work well with Win 10 IoT yet)  and the latest build of Windows 10 IoT (v.10.0.14328.1000, apparently, longer version are better….)

Then i’ve a breadboard, a bounch of headed cables, resistors and a led, plus a PIC16F18325 (in a PDIP14 package)

To complete this mini-lab i’ve a mini dso 203 oscilloscope and of course a PicKit3 programmer for the PIC

I want to type a command in my computer (any of the my computers) and have a led turned on or off, but not by the raspberry, on the PIC microcontroller instead.this because i’ll later need some of the advanced capabilities on the PIC, but for now for educational and demonstrative purposes, the led is well enough.

so my setup is the following:

image

So from wherever am i, i want to turn on that led with a command on my shell

that’s a lot of protocols and OS and software and languages together, from the very high level powershell to the closest possible to the metal +vcc signal,

I know, i know, it is called Internet Of Things, and it has already been invented by someone else, but who cares? I want to make my very own IoT.

so, first thing first:

Today we will cover how to connect from my pc to a raspberry who has in turn Win 10 iot on. If you are intereste on how to install Windows 10 Iot, the excellent Scott Hanselman has a blog post for this.

so i want to open powershell a type a command to connect to my raspberry, Win 10 IoT is already configured to receive powershell session (WinRM is turned on by default) all you need to know is your raspberry name and the root user’s credential

i’ve then a module called Connect-Raspberry.psm1 which loads automatically any time i open a PS session (thanks to an import-module in my $psprofile)

the code of the module is the following

$knownRaspberry = @{Jeeg=@{Username="Administrator";Password="mysecretpassword"}}

function Get-CredentialObject([string] $username, [string] $password){ 
    $encryptedPass = ConvertTo-SecureString $password -AsPlainText -Force 
    return new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $encryptedPass 
}

function Connect-Raspberry([string] $machine, [string] $username, [string] $password){    
   

    $trustedHosts = get-item  "WSMan:\localhost\Client\TrustedHosts" 
    if(!($trustedHosts.value -contains $machine)){ 
        Set-Item WSMan:\localhost\Client\TrustedHosts -Value $machine -Force 
    }

    if($machine -eq $null){ throw throw [System.IO.Exception] "Please specify Machine"} 
    if($knownRaspberry.ContainsKey($machine) -and (!$username) -and (!$password)) 
    { 
        $password = $knownRaspberry[$machine].password; 
        $username = $knownRaspberry[$machine].Username;        
    } 
    
    if($username) { 
        $username = "Administrator" 
    }    
    if(!$password){ 
        $cred = get-credential -Message "enter password" -UserName "$machine\$username" 
    } 
    else{ 
        $cred = get-CredentialObject -username "$machine\$username" -password $password 
    } 
    ############## 
    #the following line is an hack to workaround a bug, maybe in the future will not be required 
    #remove-module psreadline -force 
    ############## 
    Enter-PSSession -ComputerName $machine -Credential $cred 
}

 

if it is the first time you run it you may need to run as administrator as it will set the trustedhosts for the WSMan\client to trust the raspberry

given that i can connect to my  raspberry (it is called Jeeg as all the machine in my network have name of Gō Nagai’s robots)

connect

of course the script can take username and password but you can map in the $knownRaspberry variables all your frequently accessed raspberry

Obviously Jeeg is powered up and connecte to my Wi-Fi lan by the TP-Link Usb dongle

Now i have a shell on my Pc (Grendizer) that is actually a remote session on Jeeg and i can ask Jeeg to do anything it knows.

but now i want Jeeg to write a message on it’s I2C bus. Windows 10 IoT has the drivers, but powershell knows nothing about them.

The good thing is that Powershell understand .Net very well and that Windows 10 IoT can run .Net Universal Windows App!

so my idea was to write a simplified wrapper around the .Net API for the I2C to use as base for a Powershell Module

to do this you need Visual Studio 2015 Update 2 with the Windows 10 IoT SDK that match at best possible the version of Windows 10 IoT oon the raspberry. I’ve found that the SDK are usually a couple of versions behind the Raspberry Build but fortunately it doesn’t seems to be a problem!

so File>New>Project and select Universal Windows (dll)

image

you should have these references.

the wrapper’s code is the following:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Windows.Devices.Enumeration; 
using Windows.Devices.I2c;


namespace Bus 
{    
    public enum Speed 
    { 
        Standard = 0, 
        Fast = 1, 
    }

    public class I2CControllerAddressException : Exception 
    { 
        public I2CControllerAddressException(int address, string deviceId) 
            : base(string.Format("The address {0} on I2C Controller {1} is currently in use.", address, deviceId)) 
        { } 
    }

    public class I2CControllerFoundException : Exception 
    { 
        public I2CControllerFoundException() 
            : base("Could not find the I2C controller") 
        { } 
    }   

    public class I2c 
    { 
        private static I2cDevice Open(int targetAddress, Speed speed) 
        {

            var advancedQuerySyntaxString = I2cDevice.GetDeviceSelector(); 
            var controllerDeviceIds = DeviceInformation.FindAllAsync(advancedQuerySyntaxString).GetAwaiter().GetResult(); 
            if (controllerDeviceIds == null || controllerDeviceIds.Count == 0) 
            { 
                throw new I2CControllerFoundException(); 
            } 
            var i2cControllerDeviceId = controllerDeviceIds[0].Id;

            var i2cSettings = new I2cConnectionSettings(targetAddress); 
            i2cSettings.BusSpeed = (I2cBusSpeed)speed;

            // Create an I2cDevice with our selected bus controller ID and I2C settings 
            var I2cSalve = I2cDevice.FromIdAsync(i2cControllerDeviceId, i2cSettings).GetAwaiter().GetResult();

            return I2cSalve; 
        }

        public static void Send(int targetAddress, Speed speed, byte[] message) 
        { 
            var device = Open(targetAddress, speed); 
            device.Write(message); 
            
            device.Dispose(); 
        }

        public static byte[] Receive(int targetAddress, Speed speed, byte[] message, int expectedReplyLenght) 
        { 
            var device = Open(targetAddress, speed); 
            var reply = new byte[expectedReplyLenght]; 
            device.WriteRead(message, reply); 
            device.Dispose(); 
            return reply; 
        }

    } 
}

 

complie it and you will have a nice i2c.dll file

that is almost enough to play with the i2c bus from the command line.

why almost? because this file reference the System.Runtime.WindowsRuntime that you have to find out where it is, it will not copyed in the same folder of your dll, it is not the same mechanism of the old projects where you can specify “copy local”

the best way i’ve find is to make an universal windows app (.exe) wich refers this assembly and compile it, in the binary folder you’ll find also the the System.Runtime.WindowsRuntime.dll you need

 

now open the file explorer and type \\Jeeg\C$

you’ll see the “Jeeg” C disk, copy both the assembly in the path

\\jeeg\c$\Program Files\WindowsPowerShell\Modules\i2c

(you need to create the I2C folder of course)

so you will have the following

image

and you are ready!

from your remoted session on Powershell just type

Import-module i2c

to load the module and be able to send and receive date on i2c using powershell

and this ishow you send a command on the i2c bus

[bus.i2c]::Send(8,[bus.speed]::Standard,[byte[]](0xAA))

this command for example sends (master write on server, in the i2c terminology) on the address 8 the byte 0xAA, using the standatd speed (100KHz)

Raspberry is also able to use the fast mode (400KHz)

I2C has also two speed,Full Speed 1MHz and High Speed 3,2MHz but Raspberry is not able (at the moment at least) to use these speed, in any case the PIC16F series doesn’t have enough processing power to handle these clocks, i think it is necessary at least 16bit PIC to work with these speed, but i’ve not investigated.

 

next time i'll talk about the PIC firmware, that's the most interesting part to me and there are many tricks that may be useful to any hobbist that may face these topics for the first time :)

Tags:

Nov 5 2015

Claning VisualStudio build files with PowerShell

Category: PowerShell | Visual Studio — Duke @ 09:23

These days i've starting using PowerShell, it is a pleasure!

it is a long time that i want to learn PowerShell and finally i've found some occasion to give it a try.

It is like a drug, i can't stop using it!

 

despite the fact that my company have lent to me a new laptop, a shiny i5 with SSD disk, this new hardware has a 128GB disk, that it is ok for the OS only in these days.

Considering that my phone has 32 and my next one probably 128... basically i'm doing my company business by phone :(

ok stop ranting and let's go to the point.

i've to clean all the cap that VisualStudio 2010 produces when compiles.

I've a big solution with 70+ projects, belive me or not, the amount of DLL plus OBJ and pdb it produces it is more or less 400Mb some day more some day less

 

then i've created this nice script

dir -Recurse -Attributes Directory |`
 where -Property Name -ne 'Packages' |`
 dir -Recurse -Attributes Directory |`
 where {($_.Name -match 'bin') -or ($_.Name -match 'obj')} |`
 remove-item -Recurse -force


dir -Recurse -Attributes Directory |`
 where -Property Name -eq 'TestResults' |`
 remove-item -Recurse -force

basically it starts from the root you launch it in and search for all the BIN or OBJ folder not under packages (in great respect of nuget) and delete the entire hierarchy under BIN and OBJ

it frees up a lot of space and it took me 5 minutes to write it.

 

I LOVE POWERSHELL!

 

Tags:

Sep 23 2013

Extending extension methods

Category: — Duke @ 08:25

C# has extension methods, and together with lambdas they provide an incredible amount of power in our hands.

They way extension methods are implemented is very smart and makes them measy to write new ones, and even better, they provide a superior ide integration.

That’s all fantastic, but sometime i’ve found myself in the situationwhere i have to Extend the extension methods.

Let me explain my problem: consider a a program that makes use of linq over the abstraction of the unit of work. That is really really cool because if you write your generic UOW, you are basically decoupling your logic from the hard implementation of the database.

This saved me one time already, with this system i was able to switch from Oracle to SqlServer in minutes, literally, without chaning any of my business logic code.

That was easy because i was using NHibernate that already implements query providers for all the databases and dialects that i was interested to use at that time.

Now I have a new problem. I want to have the ability to switch between RavenDb and ordinary Sql databases.

Obviously the  query provider are different, and i want to have the ability to switch without hard modifying the dependencies of my project

i want to depend al my code just on my persistence layer, and this in turn have to map to the correct provider

I also want to not change the persistence code to accomodate a new provider, basically i want to plug insupport for new query provider without recompiling, at the extreme i just want to drop a dll in a folder and set up a new connection string in the config file.

Possible? Yes!

i’ve wrote a little helper project based on MEF that discovers new mapper and provides usitilities to plug them into your own set of extension methods, so all your code uniquelly depends by your persistence layer with no dependencies to particular implementations of the db.

It will up to you to provide the correct mapping for all the extension methods you want to support, or simulate them (in case of async method for example) or throw exceptions and handle the situation in your business logic code.

 

the trick is simple, let’s say i want to implement the SingleOrDefaultAsync method for all the provider i want to support.

I want to just write something like this

public static class QueryableAsyncExtensions 
{ 
    
    public static Task<TSource> SingleOrDefaultAsync<TSource>(this IQueryable<TSource> source) 
    { 
        return Extensions 
            .Of<IQueryableAsyncExtensions>(source.Provider.GetType()) 
            .SingleOrDefaultAsync<TSource>(source); 
    } 
}

 

and i want that the system automagically find outs all the mapper that implements IQueryableAsyncExtensions and for these one, pick the one that has the same provider of source.Provider

finally on this it will have to invoke the method i want as extension method, in this case SingleOrDefaultAsync<TSource>(source)

the implementation maybe something like

 

[Export (typeof(IQueryableAsyncExtensions))] 
[ExtensionMetadata(Provider=typeof(IRavenQueryProvider))] 
class TestExtensionForQueryableAsyncBool : IQueryableAsyncExtensions 
{

    public Task<TSource> SingleOrDefaultAsync<TSource>(IQueryable<TSource> source) 
    { 
          //Call the native RavenDb’s SingleOrDefaultAsync here

    } 
}

Note that  you have two attributes that decorate this class: one is the usual MEF Eport attribute, the second tells to the library for which provider this extension implementation should be used for

Tags:

Jul 24 2013

Null safe accessor

Category: C# | Visual Studio — Duke @ 06:54

It is happened to me many time to have to accesso a long hierarchi of object just to display a value to the user, and possibly this hierarchy contains null values

So the case is a.B.C.D.E.F where a is my object reference B, C, D, E are child of a in a long hierarchy of property accessor, and finally F is a simple integer o a string that i don't care about but the user want to see (if present)

 

It turns out that some languages have the so called  Groovy's safe dereferencing operator  (see http://stackoverflow.com/questions/10815641/elegant-way-to-avoid-nullreferenceexception-in-c-sharp)

but C# have not :(

 

Stack overwlow is full of smart solutions, some very elegant (see some here http://stackoverflow.com/questions/4244225/c-sharp-if-null-then-null-expression) but allof these are in someway suboptimal

 

the one i like more is

 

bossName =Employee.NullSafe( e => e.Supervisor).NullSafe( s => s.Boss).NullSafe( b => b.Name);

 

but is too verbose :(

 

so i've ended up with an alternate solution (that cames in two flavours to tell the true)

More...

Tags:

Jan 22 2013

Many news!

Category: C# | General — Duke @ 16:55

Wow! these are busy days! full of news and awesomeness!

First things first! finally i managed to get hold of a new domain name for my site PhotoAtomic.com

Thanks to everyone who have supported me, expecially Lilla <3

 

Second: i've published a new project on codeplex about setting the precision of decimal numbers. It is quite Amazing to me how many people have downloaded it in 4 days... SyncWcf was much more slower...

probably people prefer simple project?

Anyway i'm happy, i've also started working on a new electronic project and i'm Learning lot of things (a nice way to say that nowthing works as intended for now... but it is proceeding quite well, i've to say!)

Stay tuned probably i'll post something in the near future about this project!

 

Busy days... i love these!

 

Tags:

Sep 10 2012

Recover the windows 8 bootloader

Category: — Duke @ 16:45

Yesterday I was preparing a laboratory pc that has windows 8 installed.

In the lab I need windows 7 to work with some tools not yet ported to windows 8, so I decided to setup a .VHD and install windows 7 on it.

-Dual Boot will make the trick and I will be able to choose the operating system trough the beautyful windows 8 bootloader interface “bootim.exe”

True, but the sad part of the story is that once I’ve installed windows 7 the beauty win8 bootloader was replaced by the old and crappy windows7/vista bootloader

Too bad!

I’ve tried several thing: recover mode, bootrec/fixmbr; bootrec/fixboot etc… in all the order that cames into my mind also

nothing.

at the end I figured out how to replace the win7 bootloader with the new win8 bootim, and it is much more easy than I’ve thought

  1. coold boot the pc, so the windows 7 bootloader will pop up, you should see multiple choice anyway, one for each OS installed
  2. select windows 8 and at that point press F8 to have more tool
  3. once in the tool page the first choice should be Repair, choose it
  4. NOW bootim will popup in all its graphical glory, navigate to more options ad find the command console, then start it
  5. now you are in the windows 8 recover model, and it is great, you should be in disk x:\sources or something like this( forgive me , it was late night, yesterday….)
  6. in the directory you are placed, there should be an utility called bcdboot.exe  

Now the fun part, you should notice that your usual C: disk is not in C: anymore while you are in this recover mode, for some reason I don’t want to know mine was in F:

anyway search your primary disk somewhere, it is the one that have the \Windows folder in it .

at this point run bcdboot.exe /?

The help should appear, and at the bottom of the help page there should be 3 examples, I think the right one is the first one… or the last one? who knows? certainly not the one in the middle…

so, long story short, the command should be something like this

bcdboot F:\Windows /l en-us 

where F:\Windows is the root folder where Windows 8 is installed, you can omit /l en-us option if you want english language

(useful reference page here)

lunch it and once it have finished reboot your pc

now BootIm is again at its place, ready to display your OS choice in a graphical manner.

Thanks god it had worked, and I was able to go to sleep!

Tags:

Aug 5 2012

I’m on the clouds

Category: C# | Virtual Machines | ASP.NET | Cloud | Azure — Duke @ 17:47

Great! the blog is online again! finally it is persistent! I mean.. it will stay online 24/7,because it is on azure!

I’ve tried several solution but at the end I’ve found the most suitable for me.

A virtual machine instance with IIS installed on it. then an endpoint opened on the port 80, and finally  my lovely DynDNS that routes my domain name with an A record on the VIP address of the Virtual Machine.

I’m happy

it works

and the database is hosted on a separate instance of SqlServer!

some may ask why to not use the web instances (shared or reserved) available in azure, they should be ideal to host a simple blog

yes they are but….

shared instances doesn’t allow custom DNS (still wondering why)

reserved instances have a price that is too higher

and last but not least. a virtual machine allows you to do what you want on it… that is not exactly what one need in case of production website (because it force you to do all the maintenance, antivirusing, patching etc…) but it is ideal for a small experimental site.

Azure is amazing, especially the new HTML portal, I’ve done everything in 3 hours without no training at all, and I’ve tried several solution (also the shared sites, yes….)

great job MS, now lover the price of the reserved site instances or allow custom dns on the shared ones.

Tags:

Dec 30 2011

Simple ASP.NET MVC script manager

Category: ASP.NET | C# | MVC3 — Duke @ 15:57

I remember that some months ago I’ve found a beauty video of a beauty component that allows to manage .js and .css files from an MVC application.

Unfortunately I’ve lost the link and I don’t remember the name of the component.

I’ve searched the seven seas of the internet but… nothing. Things went worst today when I realized I need a script manager.

I’ve searched, browsed and digged the internet again but the best I’ve found is the “Simple script manager” on codeplex, that is well far from being “beauty”

So, I’ve started my own simple script manager. for now it is very basic. it does almost nothing but at least it is in full “MVC” style, by using and respecting the existing design of MVC3, differently from the other things I’ve found.

 

so: here is the code More...

Tags: , ,

Dec 22 2011

Compare two objects’ hierarchy

Category: C# | Linq — Duke @ 17:47

I think that everyone sometime is in the situation to understand which are the difference between two objects.

Sometime it is easy but sometime is not. Imagine that you have to prepare for your user a log of all the difference and changes that has been applied on a complex document object model.

I’m in this situation: I have NHibenrate that maps a database. As usual the principal entity of the domain have dozens and dozens of sub entities.

This complex structure is subject to revision from the user. There is a workflow to generate and approve a newer version of the object graph, but as the graph is complex, the user want to have a report of what is changed. from the last approved version. ok: now I have an graph of objects that represent the current situation, and a graph of objects that represent the last approved version.

How to solve this issue? Next: once you have discovered where the objects differs, you maybe want to see which is the actual value and understand which was the old value and which is the new one. Finally, maybe you want to revert some of the difference…. how you can do it in an efficient and powerful way? the reply is EXPRESSIONS From linq on, .NET have gained one of the best thing I ever seen in a programming language, the ability to manipulate code as it is data.

This possibility is SIMPLY AMAZING. I’ve already used this in SyncWcf and now I’ve another clue that makes me love expression more and more. so what I’ve done? give a look at the code below: More...

Tags: , , , ,