Author: admin

  • Visual studio 2015 – First App for Windows 8.1/10

    Gone are the days when you could pick up a copy of Delphi, drag a few widgets onto a form and have the beginnings of an application. Right now, I’m wrestling with creating a Windows app that will run on both phone and tablet (one app, two platforms). This post is an attempt to write down the steps I’m taking to create the skeleton of the app.

    The requirement

    The App will have several pages and you can swap between the pages by swiping left or right. The content of these pages is not important, so in this trial app, it will just be some plain text.

    I’m using Visual Studio 2015, writing in C# and initially targeting Windows 8.1.

    Beginning

    Create a solution, and a skeleton app: C#\Windows\Windows 8\Universal –> Blank App
    This creates two projects within the solution.

    If you want the template navigation (forward and back pages), you can follow (eg) Mike Taulty’s blog post. to change the MainPages from ‘Blank’ to ‘Basic’ pages (delete the MainPage and create a Basic Page called MainPage). This gives a simple way to change pages by calling:

     Frame.Navigate(typeof(TargetPage),"thisPageName");

    For ‘swipe’ navigation, we need to use Gestures, and the application framework support these ‘out of the box’.

    We have to catch the ManipulationStarted and ManipulationCompleted events. To do this:

    • name the outermost gird object: P1Grid
    • double click on the event: ManipulationStarted and code it as:
    private void P1Grid_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
    {
         startX = e.Position.X;
    }
    
    • double click on the event: ManipulationCompleted. In this example, startX > e.Position.X means swipe right to left. use < instead to swipe left to right:
    private void P1Grid_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
    {
        if (startX > e.Position.X)
           Frame.Navigate(typeof(SecondPage), this.pageTitle.Text);
    }
    • we also need to define a variable:
    private double startX;
    • finally we need to change the Manipulation Mode of P1Grid to TranslateX.

    Now, running the app lets you swipe from right to left to change the page.

    Visual Feedback

    Users like some feedback when they’re doing something like swiping left/right, and we can add an effect where the showing page is squashed in the direction of the swipe. The XAML objects have transformation built in that do what we want.

    • We need to modify the xaml code to give object names for the transformation controls. The following goes inside definition of P2Grid:
    <Grid.Projection>
        <PlaneProjection x:Name="P1Projection" GlobalOffsetX="0"/>
    </Grid.Projection>
    <Grid.RenderTransform>
        <CompositeTransform x:Name="P1Transform" ScaleX="1"/>
    </Grid.RenderTransform>
    • then we add an event handler for ManipulationDelta. We calculate how much to squash and then set the transform to both squash and then offset P1Grid:
    private void P1Grid_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
       double squash = (P1Grid.RenderSize.Width - (startX - e.Position.X) / 4) / P1Grid.RenderSize.Width;
        if (squash >= 1)
        {
            P1Projection.GlobalOffsetX = 0;
            P1Transform.ScaleX = 1;
        }
        else
        {
            P1Projection.GlobalOffsetX = P1Grid.RenderSize.Width * (1 - 1/squash);
            P1Transform.ScaleX = 1/squash;
    // or to animate in the opposite direction:
    //	P1Projection.GlobalOffsetX = P1Grid.RenderSize.Width * (squash-1);
    //	P1Transform.ScaleX = squash;
        }
    }
    • Finally, we need to reset the transformation when the swipe has finished. We add two lines to the ManipulationCompleted code:
    P1Projection.GlobalOffsetX = 0;
    P1Transform.ScaleX = 1;

    For two pages moving back and forth, or for more pages, just combine the two directions of swiping.

  • Windows Installer – free up disk space without losing anything

    It is possible to move the folder C:\Windows\Installer (which tends to get quite large). The process is to copy the folder to another drive, then create a link from the new location to the old location so Windows thinks nothing has changed.

    The process below does this ‘safely’ so you can reverse the change if something goes wrong. You can delete the Installer.X folder when you’re ready. x: can be any accessible drive.

    attrib -h -s C:\Windows\Installer
    xcopy /s /h /o  C:\Windows\Installer x:\Windows\Installer
    ren C:\Windows\Installer C:\Windows\Installer.X
    mklink /D C:\Windows\Installer x:\Windows\Installer
  • Knoppix 7.4 – How to create USB bootable disk

    Knoppix 7.4 has a desktop icon to create a flash disk.

    This in how do create the usb drive without creating a CD.

    1. Create a new virtual computer using the downloaded Knoppix .iso file

    2. Redirect a USB flash drive to the virtual computer and start the virtual computer.

    3. Click on the icon ‘Install KNOPPIX to flash disk’
    (as of Nov14) This only works if you select ‘Overlay partition’. You can reduce the size of the overlay partition to leave space on the first partition usable for general Flash Disk purposes. (If the partitioning on the USB disk is non-standard, you may need to clear it and then delete entries from /etc/fstab and then restart the virtual computer).

  • Microsoft Exchange Certificates

    The problem: How to use the Server’s CA to create a certificate with all the names you need included.

    Typically, an exchange certificate should have the names for the externally visible website and the autodiscover site – which may not match the actual name of the server.

    This is what you need to do.

    Create a .cer Certificate – using Powershell

    Using Powershell, you can run a script: CreateCertificate.ps1

    Param([Parameter(Mandatory=$true)] $f)
    $data = New-ExchangeCertificate -GenerateRequest -KeySize 2048 -SubjectName "c=GB, l=<location>, o=<organization>, cn=<website>" -includeAutoDiscover -includeAcceptedDomains -DomainName <domain-name> -privatekeyexportable $true
    Set-Content -path "$f.csr" -Value $data
    Certreq -submit -attrib "CertificateTemplate:WebServer" "$f.csr" "$f.cer"

    Then run the script with the parameter of the name of the certificate.

    Create a .cer Certificate Request – using a text file

    To avoid typing in all the details every time, create a file: CertificateData.inf (see http://technet.microsoft.com/en-gb/library/ff625722(v=ws.10).aspx for source):

    [Version]
    Signature="$Windows NT$"
    
    [NewRequest]
    Subject = "CN=<website>" ; Remove to use an empty Subject name.
    ;Because SSL/TLS does not require a Subject name when a SAN extension is included, the certificate Subject name can be empty.
    
    Exportable = FALSE   ; TRUE = Private key is exportable
    KeyLength = 2048     ; Valid key sizes: 1024, 2048, 4096, 8192, 16384
    KeySpec = 1          ; Key Exchange – Required for encryption
    KeyUsage = 0xA0      ; Digital Signature, Key Encipherment
    MachineKeySet = True
    ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
    
    RequestType = PKCS10 ; or CMC.
    
    [EnhancedKeyUsageExtension]
    ; If you are using an enterprise CA the EnhancedKeyUsageExtension section can be omitted
    OID=1.3.6.1.5.5.7.3.1 ; Server Authentication
    OID=1.3.6.1.5.5.7.3.2 ; Client Authentication
    
    [Extensions]
    ; If your client operating system is Windows Server 2008, Windows Server 2008 R2, Windows Vista, or Windows 7
    ; SANs can be included in the Extensions section by using the following text format. Note 2.5.29.17 is the OID for a SAN extension.
    2.5.29.17 = "{text}"
    _continue_ = "dns=<website>&"
    _continue_ = "dns=<website.autodiscover>&"
    ; Multiple alternative names must be separated by an ampersand (&).
    
    CertificateTemplate = WebServer  ; This is the template name used by the Cerficiate authority.

    Then run:

    certreq -new CertificateData.inf CertificateData.req
    certreq -submit CertificateData.req CertificateData.cer

    Convert .cer to .pfx and import into Exchange

    Convert .cer to .pfx by importing the .cer into a certificate store and then exporting it:

    Run mmc.exe, and Add the Certificates snap-in (Computer account, Local Computer).

    Import the certificate into the Personal\Certificates folder and then export it
    – export the private key, select PKCS#12 and include all certificates in the path and export all extended properties. You will need to provide a password.

    Next, run Exchange Management Console as Administator.

    Select Server Configuration, and under Exchange Cetrtificates, import the certificate you just exported. Then run Assign Services to Exchange and select all (except Unified Messaging).

    You may need to restart IIS for the certificate to be picked up.

  • Remove Windows 8 from a domain without the domain admin password

    There are situations where you need to break into Windows 8 (or 7, or XP).
    For example, when a domain controller has disappeared and there are no cached credentials on the computer.

    You will need:

    A windows 8 (or 7) installation disk.

    Here’s how:

    There are three steps:

    1. Break in to the computer so we have a command prompt where we can ‘do things’
    2. Create a new user with local administrator rights
    3. Remove the computer from the domain.

    Step 1: break in

    Boot the computer from the Windows 7/8 Install Disk (I’m using Window 8 for this example):

    Press any key to boot from CD or DVD

    Select the language appropriate for your computer/keyboard:

    Select Language Preferences and press Next

    If you have the Windows 8 installation disk, you can press Shift+F10 here and skip the next few screens – that brings up a command prompt immediately.
    Or click Next and then ‘Repair your computer’:
    Click 'Repair your computer'

    Then select: ‘Troubleshoot’:

    The select Advanced options:

    Finally, select Command Prompt:

    Then you need to check and select the drive letter where windows is installed (it is not always the C: you normally see within Windows). You can do this with ‘DISKPART’ and ‘LIST VOL’. The drive should be clear from what you see unless you have a complicated disk setup:

    Then we temporarily replace Utilmon.exe with cmd.exe and reboot:

    Step 2: Creating an user with administrator rights

    Then we let windows boot through to the sign-on screen. UtilMan is run by clicking on the Ease of Access button, which brings up our command line.

    If we don’t have a valid user, we can now create one:

    net user admin NewPass5 /add && net localgroup administrators admin /add

    Then close the window and log on with the newly created user: admin.

    Note: you do need to type the name of the computer in front of user name (COMPUTERNAME\admin). If you don’t know what the computer is called, just type ‘administrator’ as the username and Sign in to: will tell you the computer name.

    At this point, you can undo the ‘UtilMan.exe’ break-in by opening a command prompt (as admin) and undoing what we did before. [Windows]+X and select ‘Command Prompt (admin)’:

    Step 3: Forcefully removing the computer from the domain

    Bring up the system properties: Alt+X, System, and click on Computer name, domain and workgroup settings: Change settings:

    Then click ‘Change…’ to change the domain or workgroup:

    Set the computer to be in the Workgroup: WORKGROUP:

    Confirm that we know the local administrator password (set the admin user we created in step 2 is fine):

    You will be asked for credentials: use the credentials for the admin user we created:

    Then OK all the dialog boxes and reboot.
    Log back in as ‘admin’ and set up any users you need.

  • Fix a non-booting Linux disk

    If you boot from a Linux CD, you can switch to your non-booting disk as follows:

    1. Find the device that is your non-booting disk.
    This could be /dev/sda, /dev/sdb etc. (Disks presented as SCSI)
    This could be /dev/hda, /dev/hdb etc. (Disks presented old-style HDs)
    Or even /dev/vda etc. (Disks in virtual systems)
    2. Mount it, and then remound /dev, /proc, and /sys onto the non-booting disk

    mount /dev/sda2 /mnt
    mount --rbind /dev /mnt/dev
    mount --rbind /sys /mnt/sys
    mount --rbind /proc /mnt/proc

    3. Set your non-booting disk to root

    chroot /mnt

    Now you can run your normal commands to fix your boot

    grub2-install /dev/sda # restore grub
    # Note: you may need to update the Disk UUID in /boot/grub2/grub2.cfg
    # to the value returned by blkid /dev/sda2
  • Raspberry Pi WiFi Automatic Connection

    By default, RPi doesn’t connect to the WiFi automatically, which is annoying, especially when you don’t have keyboard/mouse/screen connected.

    You can fix this by:

    First connect to the WiFi using the WiFi app. This will include the following lines in /etc/network/interfaces:

    allow-hotplug wlan0
    iface wlan0 inet manual
    wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
    iface default inet dhcp

    Then edit /etc/wpa_supplicant/wpa_supplicant.conf

    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1
    network={
            ssid="SSID"
            psk="pre-shared-key"
            proto=RSN
            key_mgmt=WPA-PSK
            pairwise=TKIP
            auth_alg=OPEN
    } 

    You can repeat the network block for other networks you’d like to automatically connect to.

  • Raspberry Pi – easier access

    For the Debian builds (Raspbian), the default username/password is pi/raspberry.

    Once logged in, you can create new users by:

    sudo adduser yourname

    You can enable the root user by (the same procedure will reset any user’s password:

    sudo passwd root

    If you’re using ssh, then setting up keys saves a lot of time.

  • RGPIO and PiBoard

    How to use RGPIO with PiBoard.
    This guide uses a PiBoard with the following components:
    • EA DOG-M LCD (on pins 17,0,11,22,23,24,25) in 3.3V mode)
    • LCD Backlight (on pin 18)
    • Buttons connecting pins 7,8,9,10 to ground when pressed
    • PCF8563 I2C Real time clock (with super-capacitor power backup)
    • DS1621 I2C Temperature device
    • DS18B20 1-Wire Temperature device
    To use RGPIO from python, we open the /dev/rgpio device as an unbuffered file in r/w mode:
    rgpio=open('/dev/rgpio','r+',0)
    # r+ means read/write; 0 means unbuffered
    we can then write to and read from this file to control the PiBoard.

    LCD – EA-DOG-M

    RGPIO does the basic initialization from the C command to get the LCD running in 4-bit mode with the appropriate pins, but the EADOG-M screens need additional initialization according to whether you run in 3.3V or 5V mode.
    \C29 – Set 4-bit mode and instruction set 1
    \C15 – Set bias for 3-line LCD
    \C55 – Booster (for 3.3V) on, Contrast in follower mode
    \C6E – Follower ccontrol
    \C72 – Set Contrast
    \C28 – Set 4-bit more and instruction set 0
    rgpio.write('L17,0,11,22,23,24,25C')
    rgpio.write('LD\C29\C15\C55\C6E\C72\C28')

    LED Backlight (EA LED55x31-G)

    The EA LEDs are coordinated with the LCDs but use completely separate pins. The PiBoard lets you choose between a 3.3V or a 5V supply using the appropriate current-limiting resistor.
    The LED is controlled through a NPN transisitor driven by pin 18. The Raspberry Pi has hardware PWM enabled on pin 18 and this can be used to control the LED brightness. RGPIO supports both software and hardware (pin 18 only) PWM, but the hardware version is much more efficient.
    #Set LED to 50%
    rgpio.write('W50,18C')

    Buttons (Tyco 6x6mm)

    When the buttons are pressed, the GPIO port is shorted to GND. For the buttons to work, they need a pull-up resistor. The PiBoard has space for a separate pull-up resistor, or we can use the CPU’s internal pull-up capability using P7U8U9U10U.
    To get the pin settings we use RGPIO’s pin change interrupt to tell us when the pin is grounded.
    rgpio.write('P7U1,7L')  # Initialize pull
    rgpio.write('P8U1,7L')  # up and get repeated notifications
    rgpio.write('P9U1,7L')  # when pin Lo
    rgpio.write('P10U1,7L')
    To see what is going on, we have two options: read in a polling loop, knowing we may get a blank line because there is nothing waiting:
    while True:
        inLine=rgpio.readline()
        # Now process the line
    Or we can get RGPIO to send us a signal to tell us something is waiting.
    import signal,os
    def IOSignal(signum,frame):
        inLine=rgpio.readline()
        # Now process the line
    
    signal.signal(signal.SIGIO,IOSignal) # call IOSignal on SIGIO
    pid=os.getpid()                      # Get PID of this process
    rgpio.write('%dS'%pid)               # tell RGPIO to send SIGIO here
    while True:
        time.sleep(1)                    # just loop asleep waiting...

    I2C Clock

    To give the Raspberry Pi a clock, you can either be connected to the internet (in which case, the very accurate internet time is available), or you need to provide an external clock. We do this with an I2C Real Time Clock chip.
    The I2C bus is a very convenient mechanism to communicate between components. It needs 4 connections: VDD, GND, SCL, SLA. Many CPUs (including the Raspberry Pi’s) have I2C communications built in. On the Raspberry Pi the I2C components are connected to I2C channel 1. Each I2C component has an Id: the DS1307 and DS1337 are on 0x68, the PCF8563 is on 0x51.
    There are device drivers for many of the available RTC chips (and other I2C chips), and you can use these if you want to, but they are not always as flexible as you might want. RGPIO provides another interface.
    To set the clock on PCF8563 from the system time, use:

    t=datetime.datetime.today()
    sec=toBCD(t.second)
    min=toBCD(t.minute)
    hour=toBCD(t.hour)
    date=toBCD(t.day)
    month=toBCD(t.month)
    year=toBCD(t.year % 100)
    day=t.weekday()
    rgpio.write("I1N0x51D2,%d,%d,%d,%d,%d,%d,%dW"%(sec,min,hour,date,day,month,year))
    To get the clock from PCF8563 and set the system time, use:
    import re, os
    rgpio.write("I1N0x51D2,7R")
    reI2C=re.compile('I2C *([^@]*)@([^ ]*) *([^ ]*) *([^ ]*) *([^ ]*) *([^ ]*) *([^ ]*) *([^ ]*) *([^ ]*)')
    inLine=rgpio.readline()    # If using signal handling, this code goes there
    event=reI2C.search(inLine) # Use Regular expressions to unpack the input
    sec=int(g(3))&0x7f         # The PC8563 doesn't leave the unused bits zero
    min=int(g(4))&0x7f         # so we have to clear them ourselves
    hour=int(g(5))&0x1f
    date=int(g(7))&0x3f
    month=int(g(8))&0x1f
    year=int(g(9))+2000
    newDate=datetime.datetime(year,month,date,hour,min,sec)
    os.popen("date -s %s"%newDate)
    The DS13x7 series are similar but some detail differences. There are other I2C Real-time-clocks that can be used.

    I2C Thermometer (DS1621)

    The DS1621 needs initializing so it starts measuring the temperature. Thereafter the temperature can be read whenever required.
    rgpio.write('I1N0x48D0xEEW') # Command 0xEE starts conversion
    rgpio.write('I1N0x48D0xAA,2R') # Read 2 bytes to get the temperature
    inLine=rgpio.readline()
    event=reI2C.search(inLine) # Use Regular expressions to unpack the input
    temp=(event.group(3)+256*event.group(4))/256

    This temperature is accurate to 0.5C, and you can greater accuracy (about 1/16C) by reading from locations A8 and A9 and using a formula in the specification.
    Note: PiBoard has the DS1621 located next to the Timekeeping Crystal. Time Crystals typically have a fixed frequency that varies according to the temperature. This thermometer can be used to improve the accuracy of the clock.

    1-Wire Temperator sensor (DS18B20)

    The 1-Wire bus uses VDD, GND and DQ (the signal wire). (And some devices will work without the VDD connection.) Linux has 1-Wire modules available and you can use these, however, there are some problems with usability:

    1. The w1-therm module requires reading a file /sys/bus/w1/devices/28-xxxxxxxxxxxx/w1-slave. The problem is that reading this file takes a long time (about 1 second) – this is because it has to initiate a temperature conversion, and must when way for the conversion to complete – which is between 94ms and 750ms, depending on the conversion accuracy. 1 second is much too long to wait for a system with a user interface.
    2. the w1-gpio module can also be used but writing to and reading from /sys/bus/w1/devices/28-xxxxxxxxxxxx/rw. The problem here is that if the sensor goes off line, file operations to the rw file hang.
    3. The built-in support for 1-wire is only available on pin 4. You can have multiple devices on that one pin, but a single pin is still a little limiting.

    RGPIO provides an alternative interface to 1-Wire devices.

    rgpio.write('P4U')      # Set pin 4's pullup - essential for 1-wire operation
    rgpio.write('O4P')      # Set pin 4 as 1-Wire pin
    rgpio.write('O0D')      # Tell RGPIO there is only one 1-Wire device
    rgpio.write('O0x44C')   # Start temperature convertion
    rgpio.write('O0xBEC2W') # Read the temperature
    reW1=re.compile('W1(:[0-9a-fA-F\-\.]*)* *(=*) *([^ ]*) *([^ ]*) *([^ ]*)')
    inLine=rgpio.readline() # Get the result
    event=reW1.search(inLine)
    temp=(int(event.group(3),16)+256*int(event.group(4),16))/16.0

    If you have more than one device on the bus, you can do the following:

    rgpio.write('P4U')      # Set pin 4's pullup - essential for 1-wire operation
    rgpio.write('O4P')      # Set pin 4 as 1-Wire pin
    rgpio.write('OL')       # List available devices
    inLine=rgpio.readline() # Get the first found device (blank if none)
    event=reW1.search(inLine)
    w1Device=event.group(1)[1:]  # Get the device name
                                 # format is ff-nnnnnnnnnnnn.cc
                                 # ff is family, n..n is number, cc is checksum
    w1Family=w1Device[0:2]
    w1NC=w1Device[3:7]
    w1NB=w1Device[7:11]
    w1NC=w2Device[11:15]
    w1Id="%x,0x%x,0x%x,0x%xD"
    rgpio.write("O%s"%w1Id)      # Set this device as the one to use
    rgpio.write('O0x44C')        # proceed as above
    ...
  • PiBoard – an expansion board for Raspberry Pi

    PiBoard was designed to be a compact expansion for the Raspberry Pi with buttons, and LCD screen and space for time and temperature components and connectors for further expansion: PiBoard v1.0 Board, PiBoard v1.0 Schematic.

    Components

    • Full 26 pin connector
    • LCD
    • DisplayTech S162GOD with contrast potentiometer
    • Electronic Assembly EA-DOG-M with or without LED backlight in 5V or 3.3V mode
    • 4 Buttons (TYCO)
    • Reset button (not Raspberry Pi V1)
    • I2C clock chip eg DS1307, DS1337 or PCF8563
    • I2C temperature sensor eg DS1621
    • 1-Wire (eg for temperature sensor DS18B20)
    • External connector for Gnd, 5V, GPIOs 14, 15
    • Header and External connector for GPIOs 28,29,30,31
    • Zener diode protection for inputs

    V1.0 has a number of faults, but does work:

    1. Either (a) the Raspberry Pi RCA video connector needs to be trimmed; or (b) [if not using the EA-DOG-M LCD, the PiBoard need sto be trimmed.
    2. The capacitors across the buttons are best omitted
    3. The location of the 1-Wire (Gnd, 3.3V, GPIO4) connector is in the way of a PiBoard capacitor.
    4. The buttons are too close to the EA-DOG-M (placement is tricky, but not impossible)

    V1.0a is being designed to correct these and other shortcomings.