Author: vletroye

  • Create a Shared Folder and Set permissions in C#

    Here is my code to share a folder, remove that share and set permissions using the System.Management library in C#.

    Click to Read More

    [csharp] using System;
    using System.ComponentModel;
    using System.IO;
    using System.Management;
    using System.Reflection;
    using System.Security.Principal;
    namespace Fortis.Framework.Services.Config
    {
    internal static class ManagementHelper
    {

    internal enum MethodStatus : uint
    {
    [Description("Operation succeeded")] Success = 0,
    [Description("Access denied")] AccessDenied = 2,
    [Description("Unknown failure")] UnknownFailure = 8,
    [Description("Invalid name")] InvalidName = 9,
    [Description("Invalid level")] InvalidLevel = 10,
    [Description("Invalid parameter")] InvalidParameter = 21,
    [Description("Duplicate share")] DuplicateShare = 22,
    [Description("Redirected path")] RedirectedPath = 23,
    [Description("Unknown device or directory")] UnknownDevice = 24,
    [Description("Net name not found")] NetNameNotFound = 25
    }

    internal enum ShareType : uint
    {
    [Description("Disk Drive")] DiskDrive = 0x0,
    [Description("Print Queue")] PrintQueue = 0x1,
    [Description("Device")] Device = 0x2,
    [Description("IPC")] IPC = 0x3,
    [Description("Disk Drive Admin")] DiskDriveAdmin = 0x80000000,
    [Description("Print Queue Admin")] PrintQueueAdmin = 0x80000001,
    [Description("Device Admin")] DeviceAdmin = 0x80000002,
    [Description("IPC Admin")] IpcAdmin = 0x80000003
    }

    internal enum ControlFlags : uint
    {
    SE_OWNER_DEFAULTED = 0x1, //Indicates an SD with a default owner security identifier (SID). Use this bit to find all of the objects that have default owner permissions set.
    SE_GROUP_DEFAULTED = 0x2, //Indicates an SD with a default group SID. Use this bit to find all of the objects that have default group permissions set.
    SE_DACL_PRESENT = 0x4, //Indicates an SD that has a DACL. If this flag is not set, or if this flag is set and the DACL is NULL, the SD allows full access to everyone.
    SE_DACL_DEFAULTED = 0x8, //Indicates an SD with a default DACL. For example, if an object creator does not specify a DACL, the object receives the default DACL from the access token of the creator. This flag can affect how the system treats the DACL, with respect to access control entry (ACE) inheritance. The system ignores this flag if the SE_DACL_PRESENT flag is not set.
    SE_SACL_PRESENT = 0x10, //Indicates an SD that has a system access control list (SACL).
    SE_SACL_DEFAULTED = 0x20, //Indicates an SD with a default SACL. For example, if an object creator does not specify an SACL, the object receives the default SACL from the access token of the creator. This flag can affect how the system treats the SACL, with respect to ACE inheritance. The system ignores this flag if the SE_SACL_PRESENT flag is not set.
    SE_DACL_AUTO_INHERIT_REQ = 0x100, //Requests that the provider for the object protected by the SD automatically propagate the DACL to existing child objects. If the provider supports automatic inheritance, the DACL is propagated to any existing child objects, and the SE_DACL_AUTO_INHERITED bit in the SD of the parent and child objects is set.
    SE_SACL_AUTO_INHERIT_REQ = 0x200, //Requests that the provider for the object protected by the SD automatically propagate the SACL to existing child objects. If the provider supports automatic inheritance, the SACL is propagated to any existing child objects, and the SE_SACL_AUTO_INHERITED bit in the SDs of the parent object and child objects is set.
    SE_DACL_AUTO_INHERITED = 0x400, //Indicates an SD in which the DACL is set up to support automatic propagation of inheritable ACEs to existing child objects. The system sets this bit when it performs the automatic inheritance algorithm for the object and its existing child objects. This bit is not set in SDs for Windows NT versions 4.0 and earlier, which do not support automatic propagation of inheritable ACEs.
    SE_SACL_AUTO_INHERITED = 0x800, //Indicates an SD in which the SACL is set up to support automatic propagation of inheritable ACEs to existing child objects. The system sets this bit when it performs the automatic inheritance algorithm for the object and its existing child objects. This bit is not set in SDs for Windows NT versions 4.0 and earlier, which do not support automatic propagation of inheritable ACEs.
    SE_DACL_PROTECTED = 0x1000, //Prevents the DACL of an SD from being modified by inheritable ACEs.
    SE_SACL_PROTECTED = 0x2000, //Prevents the SACL of an SD from being modified by inheritable ACEs.
    SE_SELF_RELATIVE = 0x8000, //Indicates an SD in self-relative format with all the security information in a contiguous block of memory. If this flag is not set, the SD is in absolute format. For more information, see Absolute and Self-Relative Security Descriptors.
    }

    internal enum FileAccessMask : uint
    {
    FILE_READ_DATA = 0x1, //Grants the right to read data from the file.
    FILE_WRITE_DATA = 0x2, //Grants the right to write data to the file.
    FILE_APPEND_DATA = 0x4, //Grants the right to append data to the file.
    FILE_READ_EA = 0x8, //Grants the right to read extended attributes.
    FILE_WRITE_EA = 0x10, //Grants the right to write extended attributes.
    FILE_EXECUTE = 0x20, //Grants the right to execute a file.
    FILE_DELETE_CHILD = 0x40,//Grants the right to delete a directory and all the files it contains (its children), even if the files are read-only.
    FILE_READ_ATTRIBUTES = 0x80, //Grants the right to read file attributes.
    FILE_WRITE_ATTRIBUTES = 0x100, //Grants the right to change file attributes.
    DELETE = 0x10000, //Grants delete access.
    READ_CONTROL = 0x20000, //Grants read access to the security descriptor and owner.
    WRITE_DAC = 0x40000,//Grants write access to the discretionary access control list (ACL).
    WRITE_OWNER = 0x80000,//Assigns the write owner.
    SYNCHRONIZE = 0x100000,//Synchronizes access and allows a process to wait for an object to enter the signaled state.
    }

    internal enum FolderAccessMask : uint
    {
    FILE_LIST_DIRECTORY = 0x1, //Grants the right to list the contents of the directory.
    FILE_ADD_FILE = 0x2, //Grants the right to create a file in the directory.
    FILE_ADD_SUBDIRECTORY = 0x4, //Grants the right to create a subdirectory.
    FILE_READ_EA = 0x8, //Grants the right to read extended attributes.
    FILE_WRITE_EA = 0x10, //Grants the right to write extended attributes.
    FILE_TRAVERSE = 0x20, //Grants the right to traverse the directory.
    FILE_DELETE_CHILD = 0x40,//Grants the right to delete a directory and all the files it contains (its children), even if the files are read-only.
    FILE_READ_ATTRIBUTES = 0x80, //Grants the right to read folder attributes.
    FILE_WRITE_ATTRIBUTES = 0x100, //Grants the right to change folder attributes.
    DELETE = 0x10000, //Grants delete access.
    READ_CONTROL = 0x20000, //Grants read access to the security descriptor and owner.
    WRITE_DAC = 0x40000,//Grants write access to the discretionary access control list (ACL).
    WRITE_OWNER = 0x80000,//Assigns the write owner.
    SYNCHRONIZE = 0x100000,//Synchronizes access and allows a process to wait for an object to enter the signaled state.
    }

    internal const uint FolderAccessFullControl = (uint)
    (FolderAccessMask.FILE_LIST_DIRECTORY | FolderAccessMask.FILE_ADD_FILE |
    FolderAccessMask.FILE_TRAVERSE | FolderAccessMask.FILE_ADD_SUBDIRECTORY |
    FolderAccessMask.FILE_READ_EA | FolderAccessMask.FILE_WRITE_EA |
    FolderAccessMask.FILE_DELETE_CHILD | FolderAccessMask.FILE_READ_ATTRIBUTES |
    FolderAccessMask.FILE_WRITE_ATTRIBUTES | FolderAccessMask.DELETE |
    FolderAccessMask.WRITE_DAC | FolderAccessMask.READ_CONTROL |
    FolderAccessMask.WRITE_OWNER | FolderAccessMask.SYNCHRONIZE);

    internal enum AceFlags : uint
    {
    OBJECT_INHERIT_ACE = 0x1, //Noncontainer child objects inherit the ACE as an effective ACE. For child objects that are containers, the ACE is inherited as an inherit-only ACE unless the NO_PROPAGATE_INHERIT_ACE bit flag is also set.
    CONTAINER_INHERIT_ACE = 0x2, //Child objects that are containers, such as directories, inherit the ACE as an effective ACE. The inherited ACE is inheritable unless the NO_PROPAGATE_INHERIT_ACE bit flag is also set.
    NO_PROPAGATE_INHERIT_ACE = 0x4, //If the ACE is inherited by a child object, the system clears the OBJECT_INHERIT_ACE and CONTAINER_INHERIT_ACE flags in the inherited ACE. This prevents the ACE from being inherited by subsequent generations of objects.
    INHERIT_ONLY_ACE = 0x8, //Indicates an inherit-only ACE which does not control access to the object to which it is attached. If this flag is not set, the ACE is an effective ACE which controls access to the object to which it is attached. Both effective and inherit-only ACEs can be inherited depending on the state of the other inheritance flags.
    INHERITED_ACE = 0x10, //The system sets this bit when it propagates an inherited ACE to a child object.
    SUCCESSFUL_ACCESS_ACE_FLAG = 0x40, //Used with system-audit ACEs in an SACL to generate audit messages for successful access attempts.
    FAILED_ACCESS_ACE_FLAG = 0x80 //Used with system-audit ACEs in an SACL to generate audit messages for failed access attempts.
    }

    internal enum AceType : uint
    {
    Access_Allowed = 0,
    Access_Denied = 1,
    Audit = 2
    }

    internal static string GetDescription(this Enum value)
    {
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
    (DescriptionAttribute[])fi.GetCustomAttributes(
    typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0)
    return attributes[0].Description;
    else
    return value.ToString();
    }

    /// <summary>
    /// Add a Share on a folder.
    /// </summary>
    /// <param name="folderPath">Path of the folder to be shared.</param>
    /// <param name="shareName">Name to be given to the share.</param>
    /// <param name="description">Description to be set on the share.</param>
    /// <param name="securityDescriptor">Security to be set on the share, including username and access rights.</param>
    /// <remarks>The folder is created if it does not yet exist.</remarks>
    internal static void AddSharedFolder(string folderPath,
    string shareName, string description,
    ManagementObject securityDescriptor)
    {
    try
    {
    // Create the folder if required
    var folder = new DirectoryInfo(folderPath);
    if (!folder.Exists) folder.Create();

    // Create a ManagementClass object
    ManagementClass managementClass = new ManagementClass("Win32_Share");

    // Create ManagementBaseObjects for in and out parameters
    ManagementBaseObject inParams =
    managementClass.GetMethodParameters("Create");
    ManagementBaseObject outParams;

    // Set the input parameters
    inParams["Description"] = description;
    inParams["Name"] = shareName;
    inParams["Path"] = folderPath;
    inParams["Type"] = ShareType.DiskDrive;
    //inParams["MaximumAllowed"] = 20;
    inParams["Password"] = null;
    inParams["Access"] = securityDescriptor;

    // Invoke the "create" method on the ManagementClass object
    outParams = managementClass.InvokeMethod("Create", inParams, null);

    // Check the result
    var result =
    GetMethodStatus(outParams.Properties["ReturnValue"].Value);
    Console.WriteLine("Create Share: " + result.GetDescription());
    }
    catch (Exception ex)
    {
    Console.WriteLine("Error: " + ex.Message);
    }
    }

    /// <summary>
    /// Get security settings required to grant access rights on Files of Folders to a user account.
    /// </summary>
    /// <param name="domain">Domain of the User account</param>
    /// <param name="username">Name of the User account.</param>
    /// <param name="accessMask">Requested Access Rights.</param>
    /// <returns>A security Descriptor with the requested access right for the provided user account.</returns>
    internal static ManagementObject GetSecurityDescriptor(string domain, string username, object accessMask)
    {
    var everyoneAccount = new NTAccount(domain, username);
    var sid = everyoneAccount.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
    var sidArray = new byte[sid.BinaryLength];
    sid.GetBinaryForm(sidArray, 0);

    ManagementObject everyone = new ManagementClass("Win32_Trustee");
    everyone["Domain"] = domain;
    everyone["Name"] = username;
    everyone["SID"] = sidArray;

    ManagementObject dacl = new ManagementClass("Win32_Ace");
    dacl["AccessMask"] = accessMask;
    dacl["AceFlags"] = AceFlags.OBJECT_INHERIT_ACE | AceFlags.CONTAINER_INHERIT_ACE;
    dacl["AceType"] = AceType.Access_Allowed;
    dacl["Trustee"] = everyone;

    ManagementObject securityDescriptor = new ManagementClass("Win32_SecurityDescriptor");
    securityDescriptor["ControlFlags"] = ControlFlags.SE_DACL_PRESENT;
    securityDescriptor["DACL"] = new object[] { dacl };
    return securityDescriptor;
    }

    /// <summary>
    /// Delete a Share.
    /// </summary>
    /// <param name="shareName">The name of the share to be deleted.</param>
    internal static void RemoveSharedFolder(string shareName)
    {
    try
    {
    // Create a ManagementClass object
    ManagementClass managementClass = new ManagementClass("Win32_Share");

    // Get all existing shares and find the one to be deleted
    ManagementObjectCollection shares = managementClass.GetInstances();
    foreach (ManagementObject share in shares)
    {
    if (Convert.ToString(share["Name"]).Equals(shareName, StringComparison.InvariantCultureIgnoreCase))
    {
    // Invoke the "delete" method on the Share object
    var outParams = share.InvokeMethod("Delete", new object[] { });

    // Check the Result
    var result = GetMethodStatus(outParams);
    Console.WriteLine("Delete Share: " + result.GetDescription());

    break;
    }
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine("Error: " + ex.Message);
    }
    }

    private static MethodStatus GetMethodStatus(object outParams)
    {
    MethodStatus result = MethodStatus.UnknownFailure;
    Enum.TryParse<MethodStatus>(Convert.ToString(outParams), out result);
    return result;
    }
    }
    }
    [/csharp]

    And here is a code sample I am using:

    [csharp] var path = @"C:\Users\Public\Documents\SomeFolder";

    var folder = new DirectoryInfo(path);
    if (!folder.Exists) folder.Create();

    ManagementHelper.RemoveSharedFolder("MyShare");

    // Get the security Descriptor
    ManagementObject securityDescriptor = ManagementHelper.GetSecurityDescriptor(null, "everyone", ManagementHelper.FolderAccessFullControl);

    // Create the Share
    ManagementHelper.AddSharedFolder(path, "MyShare", "My Shared Folder", securityDescriptor);
    [/csharp]

    Loading

  • TP-LINK 300Mbps Wireless N Range Extender: TL-WA850RE

    TP-LINK Wireless N Range Extender TL-WA850RE
    TP-LINK Wireless N Range Extender TL-WA850RE

    Finally a Wireless Range Extender which is as nice as cheap and easy to configure!

    Click to Read More

    My wifi router is on the first floor and wifi connections from both the ground floor and the second floor are really poor due to the large concrete slab between each floor.

    I didn’t want to pay (a lot) for a new wifi routers which would offer much more features than actually required, have useless Ethernet ports (switch), be large and ugly/inappropriate in the landscape, …

    So, I decided to give a try to the nice and discrete TL-WA850RE sold for 38€.

    The connection with my Buffalo WZR-HP-G300NH was straightforward and went seamlessly.

    1. Plug the TL-WA850RE in a electrical outlet close to the wifi router to be extended
    2. On a laptop, open the pane to select a Wifi Network and pick the “TP-LINK_Extender_xxxxxx network”
    3. Start a browser and navigate to “http://tplinkextender.net”. It’s the url of the embedded administration website.
    4. Log in using the username ‘admin’ and password ‘admin’
    5. Follow the wizard to configure the TP-LINK Range Extender as described in the Quick Installation Guide. PAY ATTENTION: you have to disable your popup blocker or allow that website. Otherwise, the final status windows will be blocked and the process won’t complete.
    6. Once the wizard completed, go to the router configuration website and look for the IP assigned to the TP-Link device (on the WOL page of my Buffalo, I found it’s IP for the hostname = *). The best would be to assign a fix IP to the TP-Link’s Mac Address!
    7. Restart a Browser and navigate to the TP-Link’s IP address.
    8. Back to the TP-Link administration website, change the default username/password via System Tools > Password.
    9. Now, the device can be unplugged and moved into a electrical outlet of a room where the wifi signal is currently poor.

    There is a DHCP server embedded in the device as well as some other basic wireless features (relate to security, statistics…) that I won’t use as far as everything is managed by/on my Buffalo.

    So far, the TP-Link works really well to extend the range of my Buffalo 🙂

    The only “issue” is the blue leds shining too much in the dark which prevent me to sleep in my room if I use the repeater there 🙁

    TP-Link: http://www.tp-link.com/en/products/details/?model=TL-WA850RE

    Loading

  • Upgrade firmware of Buffalo WZR-HP-G300NH

    Buffalo WZR-HP-G300NH v1
    Buffalo WZR-HP-G300NH v1

    I have upgraded the firmware of my Buffalo WZR-HP-G300NH (v1) with the latest version of dd-wrt… seamlessly !

    Click to Read More

    My Buffalo bought end of 2010 was pre-installed with a version of dd-wrt (a.k.a the “Pro” firmware of Buffalo which was installed by default as of the second half of 2010 instead of their ‘friendly’ firmware).

    1. In the dd-wrt router database, I have searched for WZR-HP-G300H and found it was supported by v24-preSP2.
    2. I went to the file server where dd-wrt firmwares v24-preSP2 are available.
    3. On that file server, I went to the more recent sub-folder (/2013/02-11-2013-r20675) and looked for the folder “buffalo_wzr-hp-g300nh” and fetched the firmware “wzr-hp-g300nh-dd-wrt-webupgrade-MULTI.bin” (The other one “buffalo_to_ddwrt_webflash-MULTI.bin” is to upgrade from the Buffalo ‘Friendly’ firmware – which used to be installed by default before the second half of 2010).
    4. Using my laptop connected via wifi, I went to the “firmware update” page of my Buffalo, via its web interface menu “Administration > Firmware Upgrade”.
    5. I chose “don’t reset”  after flashing, selected the firmware downloaded previously on my laptop and clicked “Upgrade”. It took quite a few minutes.
    6. Next, the countdown being completed, I have refreshed my browser and the new interface appeared. The previous one was red with “Buffalo” displayed on top. The new one is mainly black/blue and yellow without Buffalo displayed anymore.

    Everything was still working fine immediately after the upgrade, without any lost of settings. I.e. mainly (from my point of view):

    • The Buffalo IP address, which was a custom one, didn’t change.
    • The Port Forwarding where still configured in NAT/QoS > Port Forwarding.
    • The wol addresses where still available in Administration > Wol.
    • The Static Leases of the DHCP Server where still configured in Services > Services.

    dd-wrt wiki for WZR-HP-G300NH : http://www.dd-wrt.com/wiki/index.php/Buffalo_WZR-HP-G300NH

    Buffalo : http://www.buffalotech.com/products/wireless/single-band-wireless-routers/airstation-highpower-n300-gigabit-dd-wrt-wireless-router

    Loading

  • A HTPC for 35€: Raspberry Pi + XBMC

    Raspberry Pi Model B

    I have just received the “Raspberry Pi Model B” I ordered two weeks ago on “RS Components” website. It rocks !!!

    Within 30 minutes, I was watching on my HD TV a 1080p movies streamed from my NAS :p

    Click to Read More

    Mine is in a black case bought from RS components. I also bought there a power supply and a HDMI cable. The big advantage of using a Raspberry pi is that

    • It has a very low power consumption (about 1-2 watts at idle)
    • It is really small 85.60mm x 53.98mm x 17mm (invisible behind the TV)
    • It has a HDMI with Audio with CEC support (you can pilot XBMC on the Raspberry Pi with the TV remote control)
    • It comes with codec license for MPEG4 & H.264 (hardware accelerated)
    • Licenses can also be bought here to play back MPEG2 or VC1.
    • The Model B comes with 512MB Ram (Only 256 on the Model A)
    • It boots a Linux from a SD card (= silent) in about 50 seconds (depending on the distribution). There are 3 distributions of Linux with XBMC targeting the Raspberry Pi (see the wiki here). Some Install Guides:
    • A 2GB SD is enough, but I use a 16GB class 6, the only SD I had
    • There are 2 USB slots that I use for a keyboard and a mouse. That can be expanded with a USB hub (There is only one USB port on the Model A). A USB HDD can be plugged to add extra storage if required.
    • There is a 10/100Gbs Ethernet Port (No Ethernet port on the Model A) with supports of various power management wakeup features, including Magic Packet™, Wake-on LAN (WOL) and Link Status Change. UNFORTUNATELY, albeit Pi’s Lan chipset does support WOL, the Pi’s lack of power management (ACPI) means it doesn’t support this Lan chipset features 🙁
    • It does not need a fan cooler (= silent)
    • The Model B uses a standard power supply capable of supplying 5V 700ma (the Model A requires 5V 300ma)
    • The GPU is capable of 1Gpixel/s
    • It can be easily overclocked (and overvolted to increase stability) up to 1000MHz (without making the warranty void !). By default the Raspberry Pi runs as 700Mhz and is overclocked at 800Mhz by RaspBmc…
    • Overall real world performance is something like a 300MHz Pentium 2 with great graphic performances.
    As mentioned, I decided to install RaspBmc. It’s really straightforward [EDIT: RapsBmc is now deprecated and replaced by Osmc).
    1. Plug the SD card in a PC (I am using Windows 8 )
    2. Format the SD card, e.g. using a tools dedicated to SD/SDHC/SDXC like “SD Formatter“.
    3. Download the raspbmc installer (Not available anymore on the official webstite) and “run As Administrator” the setup.exe . It will automatically download an image and copy it to the SD card.
    4. Plug next the SD card in the Raspberry Pi, plug the HDMI cable on the TV (I didn’t test the RCA/Audio output), plug an Ethernet cable and plug the power supply. Select the right HDMI input on your TV and you should see the Raspberry PI display. It will configure itself (get an IP address from DHCP server, download the latest release/updates, etc…) and after about 20 minutes, it should start XBMC.
    5. In XBMC, go to the main menu > System > Lower submenu > System info and take note for your URL. You can also get there the MAC Address if you prefer like me to configure your DHCP server to assign a fix IP to the Raspberry PI (recommended to remote control XBMC or configure NFS access to Synology – reboot required).
    6. On your PC, run a Browser and type the IP address of the Raspberry PI to get access to the XBMC web control UI (on the port 80 configured by default in Raspbmc). It can be used to remote control XBMC.
    7. On your Android Phone, install the XBMC official Remote Control (Not available anymore) and configure it with the IP address of the Raspberry Pi with port 80 (this is the default of RaspBmc). There is neither a username nor a password defined by default in RaspBmc for accessing the Web Control UI (Another good remote for Android is Yatse Widget).
    8. On Synology, enable the “guest” account and grant read access on the shared folders “music”, “video” and “photo” (I still have to find where I can configure a username in raspbmc to access smb/nfs – I know I could at least do it on the smb/nfs sources configured in XBMC: protocol://user:pass@synoIP/sharename)
      • The default username is “pi” and the default password is “raspberry”, but for some reasons, adding such a user on the Synology with adhoc rights on the shares does not grant raspbmc access on those ?!
    9. On XBMC, add video, music and photo sources. I am not using “uPnP” as it does not support use of metadata stored next to the media files. Instead I am currently using smb.
    10. On XBMC, you can go to the menu “Programs” to get access to the RaspBmc settings.
    The Android Remote Control for XBMC works really fine, as well as controlling XBMC with the TV Remote, which makes this HTPC from far the greatest for that price: ~35€!
    A few notes:
    • WOL does not work because the lack for “power management” on Raspberry Pi. The only other way to “power on” the device remotely is to plug its power cable into a USB port on the TV (USB voltage is standardized at 5.0v, so you only have to check the max A supported by your TV). When you turn on the TV the pi powers on too. However, the Pi draws less power when turned on then many Tvs do when off, so there is really no reason to ever turn it off. Turning it off would not significantly reduce power consumption unless it is also unplugged.
      • So, don’t ever use the “Power Off” button of XBMC. The only way to restart the Raspberry Pi would be to unplug and plug back in the power supply.
      • Power over Ethernet (PoE) is not yet supported. Maybe in a future version of the Raspberry Pi.
    • In XBMC, go to the main menu > System > Lower submenu > Settings > Apparence > Region. Set e.g. the “Langue of the interface” or your language as “Preferred Language for audio” although you like to watch the movies in O.V.
    • In XBMC, go to the main menu > System > Lower submenu > Settings > Services > SMB Client. Change the name of the Workgroup to match your.
    • Login on the Raspberry Pi via SSH (using Putty, username “pi”, password “raspberry”. Note: “root” user is disabled by default on RaspBmc) and Raspbmc will prompt you to choose your keyboard layout – use the space bar to select a layout and Tab to move the cursor onto the Ok button. On the next screen, set your layout as the default one and wait until it’s “generated” (can be a long process). Continue the configuration with the selection of your region and country. Type “exit” to close the SSH session.
    • Raspbmc overclocks the Raspberry Pi to a safe clock frequency (from the default 700MHz to 800Mhz). Notice that a change of the clock frequency does not blow the OTP (Over Temperature Protection). It is overvolting that does this. Overclocking is therefore not making the warranty void while overvolting will permanently set a bit which invalidates the warranty. Overvolting will also reduce the lifespan.
      • Here is a tutorial to overclock the Raspberry Pi with RaspBmc via SSH
      • Here is a tutorial to overvolt the Raspberry Pi with RaspBmc via SSH
      • Here is a tutorial to do the same with the Raspbery config tool (if not using RaspBmc
      • And here are more details on possible values for the overclocking/overvolting.
    • With RaspBmc, there is no need to manually update the firmware (via SSH). This is done automatically by RaspBmc, insuring that the kernel is fully compatible.

    site: http://www.raspberrypi.org (Look at the quick-start-guide and the FAQ)

    RaspBmc: http://www.raspbmc.com (Look at the FAQ)

    XBMC for Raspberry: http://wiki.xbmc.org/index.php?title=Raspberry_Pi/FAQ

    buy: http://raspberrypi.rsdelivers.com/default.aspx?cl=1

    Loading

    ,
  • Fuhu Nabi 2 with Google Apps – Great tablet for kids and dad

    I have just bought a Nabi 2, a tablet for kids which costed me only 155€ (+ 12€ for delivery from Ireland to Belgium) although it’s a quad-core 1.3GHz Nvidia Tegra 3 processor and 7-inch 1024-by-600-pixel Capacitive Multi-Touch display running Android 4.0.

    Fuhu Nabi 2 Kids tablet
    Fuhu Nabi 2 Kids tablet

    It could be the perfect tablet for dad and kids it it was not missing the Google Play Store, which may not be installed due to Google’s policies (Nabi having its own store)… (and maybe a GPS). Fortunately, if you are not afraid of rooting the device, all the Google Apps can be installed…

    Click to Read More

    The Nabi 2 is really great and fast.

    • It connects to 802.11b/g/n Wi-Fi networks on the 2.4GHz frequency.
    • It comes with Bluetooth 3.0 integrated (useful to connect with wireless headphones).
    • It has 1GB of RAM
    • It comes with 8GB of built-in storage of which 4.49GB are free
    • It has a microSD slot to increase capacity (support 64GB microSD without issues).
    • It has a mini HDMI out for playing videos on an HDTVs at up to 1080p.
    • The battery can last up to 7h30 while running a video with screen brightness set to maximum and Wi-Fi switched on.
    • It has a 2-megapixel front-facing camera above the screen.
    • It has an accelerometer
    • It comes with a thick red rubber silicone case that can be removed but is well protecting the tablet. Really let the kids play with it without much concern 😉
    • It has a proprietary Monarch OS UI.

    It’s built by a Los Angeles-area startup called Fuhu. You will find plenty of reviews on the web looking for “Fuhu Nabi 2”.

    Unfortunately, it does not come with Google Play and generally speaking, Google Apps (“gapps”) may not be installed. This was really an hold-back for me as I have already a lot of paid softwares bought on Google Play for my Android phone that I wanted to reused them on that tablet. Fortunately, a known “exploit” of Android has been used to root the device and add all the Google Apps as explained on XDA-developers forum.

    How to root the Nabi 2 is really best explained here (EDIT: see at the bottom for another improved package containing the “gapps”). Each manual steps are detailed here.

    It’s really clear and did work quite well for me.. Quite well because it appeared that at the step where I had to select the gapps.zip file and install it, this one was not available… I think that the problem that I didn’t have a microSD card in the slot… I would recommend to have one plugged before rooting the device… What I did to solve that issue: I copied the file manually from my PC on a microSD card, I did plug the card in the device and I used the “Mount” menu of TWRP to make the SD card acessible from TWRP. Finally, I could select  gapps.zip on the external SD.

    A last fright however. After the installation of the Google Apps (when TWRP says “Installation Complete!”) and before clicking “Reboot System” in the lower right, I noticed error messages in the logs: failed to mount \data.. Gasp !! I did try to mount it manually without success. As I still didn’t find a solution after one hour spent googling, I decided to reboot the device and pry…. And  fortunately, although it took a few minutes to restart and complete the update, everything appeared to be running really fine !

    Next, I had access to all the Google apps, including  Google Play. I did installed successively on the Nabi all the application I already paid and installed in the past on my Galaxy SII…

    There was however a remaining “issue” (neither blocking nor critical), the gapps package was giving a message ‘Android Upgrading’ on every boot. But there is a new package here that solves this issue. Simply copy it on your nabi 2 (E.g.: on the microSD – or download it directly on the internal storage). Next go to the recovery mode in TWRP 2.2.2.1 and install it:

    • While the nabi is turn on, press the “Power off” button for a few seconds to get the “shutdown” prompt.
    • Press next the “Volume +” and the “Power Off” buttons together for a few second to get the boot menu. You should see soon the following entries in the top left corner, is small fonts.
      • Boot normally
      • Fastboot Protocol
      • Recovery Kernel
      • Forced Recovery
    • Select “Recovery Kernel” with the “Volume -” button
      • Don’t wait too long before starting to select this entry or the device starts to “Boot Normally”
    • Confirm the selection with the “Volume +” button
      • The menu becomes brighter
    • Wait for a some long seconds and here it is: the TWRP menu
    • Select Install and browse to find the “gapps.zip” file.
    Another option is to copy the new gapps into the setup of jmztaylor and rerun the script. You may also replace the recovery.img (TWRP) with a more recent one (Read this thread)…

    IMPORTANT NOTICE. If like me you have the UK version (NABI2-NV7A-UK) don’t try to install more recent TWRP like the 2.3.3.0 or 2.4.4.0. They have a bug with the touch screen calibration. you won’t be able to touch and select menu/items/etc… anymore in TWRP 🙁 Really a nightmare. So stick to TWRP 2.2.2.1.

    So, as I had to redo the whole process several times, here is a resume (every info taken from xda-developers!):

    • On the Nabi 2
      • Power it on (Press the “Power” button for 5 seconds).
      • Go into the Daddy/Momy mode
      • Verify that “USB Debugging” is enabled in Settings > System\Developer Options.
      • Check also that you have at least the version 1.9.23 in Settings > System\About.
      • To update the nabi 2, go to Settings > System\ About, Update and click the “Check update” button.
    • On the PC:  Go to Control Panel, Device Manager and look for the Nabi tablet device.  If it has an exclamation mark next to it, install the PDANet software to get the required drivers. The Nabi 2 should next be properly listed.
    • Open a dos command prompt Run As Administrator
    • Go to the location where you have unzipped the jmzrootpackage
    • Replace the files\gapps.zip file with t499users_fuhu_nabi2_gapps.zip
    • Possibly replace files\recovery.img with the one from NabiTWRP244.zip
    • Run install.bat
    • Choose option 1. The ADB server used to communicate with the nabi 2 will start. Press any key to continue
    • The device will reboot and display a menu in the top left corner :
      • Bootloader
      • Continue
      • Reboot-bootloader
      • Reboot
      • Poweroff
    • Press any key in the dos command prompt to continue. The TWRP  will be copied on the nabi 2.
    • Press the “Volume +” button on the nabi to enter the “Bootloader” menu
    • Press next the “Volume -” button until the “Recovery Kernel” menu is selected
    • Press finally the “Volume +” button to confirm the selection. The whole menu appears next much brighter and a few long seconds later you enter the TWRP  UI.
    • In the dos command prompt, press any key to continue. The gapps.zip and root.zip files will be uploaded and the device will reboot and reenter TWRP.
    • In TWRP, press Install
      • If you have difficulties to Press the button, you possibly have the “touchscreen calibration” bug. Bad luck. It’s a real nightmare to use TWRP with that bug. Check the version displayed on the top. I had no issue with TWRP 2.2.2.1
      • I was unable to select the “internal storage” as source for the files to be installed
      • I didn’t find the files pushed from the dos command prompt and had to copy them manually on the microSD. (Visible from TWRP under /external_sdcard)
    • Select both root.zip and gapps.zip (add them in the queue) and proceed
    • During the installation, you could see like me a lot of “E:Unable to mount ‘/data’” and “E:failed to mount /data (Invalid argument)” errors…
    • After the installation press “Wipe Cache/Dalvik” and once done, press “Back”
    • Press “Reboot” and select “System” in the reboot menu. The nabi 2 power off
    • Power on you nabi 2
    • It will take quite a long time to boot. Eventually, it will be “updating Android”
    • Enter the Daddy/Momy mode and go to the Play Store to get “Root Checker”  (e.G.: from free Android tools) to see if the device is rooted properly.
    • You should also have an application named “SuperSU” available
    • You can now also delete the Fuhu apps that you don’t like
      • Use e.g.: ES File Explorer (as far as you already checked all the options in Settings > Root Settings) to delete the relevant .apk files under /vendor/app/. Pay attention that if you delete all of them, you will get a blank welcome screen. If you really want that, make sure that you hat set “Parent Mode as Default Mode” in the Settings > Personal/Security.
      • NvCPLSvc.apk, fuhu_AddApps.apk, fuhu_AppZone.apk, fuhu_Books.apk, fuhu_ChoreList.apk, fuhu_Crafts.apk, fuhu_Fan-a-tech.apk, fuhu_KidzMode.apk, fuhu_NabiCare.apk, fuhu_NabiCloud.apk, fuhu_NabiSpinletsPlusICS.apk, fuhu_NabiSpinletsPlusParentICS.apk, fuhu_NabiSync.apk, fuhu_OOBE.apk, fuhu_ParentalDashboard.apk, fuhu_SpinletPlusVideo.apk, fuhu_SwitchKids.apk, fuhu_TreasureBox.apk, fuhu_University.apk, fuhu_Videos.apk, fuhu_Web.apk, fuhu_nabiMD.apk
    • If you still get the “Android Upgrading” message every time you reboot (as I had… although using the new gapps.zip), it is said that you have to delete manually the two following .odex files (I did renamed them, but as it didn’t work for me, I finally  restored them)
      • /system/app/Gallery2.odex
      • /system/framework/com.google.widevine.software.drm.odex
    • I did notice that although I had update the device from version 1.9.36 to  1.9.37-release-keys , there was still OTA updates available (version v2.0.5)… So I did download and install them and the device did reboot in TWRP mode. As I didn’t know what I had to do, I did “install” again the root.zip and the gapps.zip (in that order!), press again “Wipe cache/Dalvik” and press “Reboot System”… The funny thing is that the update didn’t complete successfully as it is still in the list if I do a “check update”. But instead, the “Updating Android” message is gone 😀

    site: http://www.nabitablet.com

    xda-developers page: http://forum.xda-developers.com/wiki/Fuhu_nabi_2

    Automated scripts: http://forum.xda-developers.com/showthread.php?p=36758895

    Loading

  • Remove Print Jobs stuck in Queue with state Deleting

    I have time to time Print Jobs stuck in the Print Queue that cannot be canceled or deleted. It’s always very frustrating as it blocks other Print Jobs which are usually quite urgent… The only solution is to stop the spooler and delete its content from a command prompt.

    Click to Read More

    Often, it starts with a Job stuck in the Print Queue and not printing. For some reason, although I restart both the PC and the Printer, the Job never starts. So, I try to cancel it but the Job does not disappear from the Queue and keeps displaying the status “Deleting-Printing…” for ever.

    I think that the problem occurs when the PC goes into the Sleep state while the Print Job is not yet completed (But I am quite sure there are other causes). When the PC is waked up, the Job appears stuck for ever.

    Here are the commands  to stop, clean and restart the spooler:

    [bash]net stop spooler
    del %systemroot%\system32\spool\printers\*.shd
    del %systemroot%\system32\spool\printers\*.spl
    net start spooler[/bash]

    Loading

  • Control Windows 8 from Android: Win8 Controller

    Windows 8 Controller

    This software turns an android phone into a multitouch controller for windows 8. It’s however not free except the very basic features – those being enough to take control of the mouse and access the Start Screen and the Desktop.

    Click to Read More

    Win8 Controller comes with a client part to be installed on the Android, and a server part to be installed on the remote Windows 8 PC.  Using this software you control the remote PC as if it is a tablet.

    It works quite fine for most features:

    • Move the mouse
    • Click, double-click, right-click
    • Access the Start Screen, Swipe to the left or to the right (you have put your finger at the very bottom of the Android screen), Tap or Drag tiles, …
    • Use the keyboard of the Android

    I have the following issues:

    • I can’t switch to the Start Screen touching the Android screen with four (or five) fingers.
    • I loose control of the mouse as soon as the “Task Manager” is open on the remote PC and has the focus. I re-gain the control if I run another application which fakes the focus. However, I can’t close the “Task Manager” clicking its close button.
    • Win8 Controller doesn’t run as a service and I can’t use it as long as I am not logged on the remote PC with a user. This is mainly a blocking issue on my HTPC where I have replaced the Windows Shell with Media Center. Indeed, only services can run in the background if the Shell is not run.

    Details: http://www.win8controller.com/

    Download: http://www.win8controller.com/#&download

    Loading

  • Status of FlexRAID Jobs currently running

    While you manually trigger a FlexRAID job using the client FlexRAIDcmd.exe or when a FlexRAID Scheduled Job is started, its status is not displayed automatically in the Web UI currently opened.

    Click to Read More

    The Web UI needs to be reloaded in the Browser (Ctrl + F5). Doing so,

    • A status windows should now be displayed for the current process and
    • The job should also now appear in the “Command Execution Center” (FlexRAID UI > Your Configuration > Tool Box).
      • In that “Command Execution Center”, the “Pause”, “Resume” and “Abort” buttons should now be accessible.
    To get the status of the current job, using the FlexRAID client (FlexRAIDcmd.exe), type in a command prompt: [ps]FlexRAIDcmd.exe localhost – – status[/ps]

    Loading

  • WCF Services – The request failed with HTTP status 405: Method Not Allowed.

    This error occurred while testing WCF services moved from old Windows Servers 2003 on some of our new Windows Server 2008 R2 with IIS 7.5 (not on all). It appeared that depending on the setup sequence, .Net features were not all correctly configured, a.o. the .svc handlers…

    Click to Read More

    Here is the commands to be used in order to fix the setup:

    [bash]

    “C:\Windows\Microsoft.NET\Framework64\v2.0.50727\aspnet_regiis.exe” -i -enable
    “C:\Windows\Microsoft.NET\Framework64\v3.0\Windows Communication Foundation\servicemodelreg.exe” -i
    “C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe” -i -enable
    “C:\Windows\Microsoft.NET\Framework64\v4.0.30319\servicemodelreg.exe” -ia

    [/bash]

    Loading

  • Use FlexRAIDCmd within PowerShell scripts to gracefully stop FlexRAID

    When using FlexRAID in Real-Time mode, the Pool must be stopped before stopping the service, i.e., also before shutting down the server. The best approach is to define a Shutdown Task in Windows to manage this…

    Click to Read More

    The Shutdown Task will run a Powershell Script using the FlexRaidClient to query the state of FlexRAID and trigger actions…

    The FlexRaidClient for windows, named FlexRaidCmd.exe, is not installed by default with the service. It must be downloaded as an Option here.

    The syntax is: FlexRAIDClient Host Port Timeout Command

    Once installed, one can use the Command “view” in a cmd prompt RUN AS Administrator on the server to Start/Stop the pool:

    FlexRAIDCMD localhost - - view class1_0 start
    FlexRAIDCMD localhost - - view class1_0 stop

    The – –  are used as “default values” for the Port and Timeout parameters
    class1_0 must be used for the new driver (=> class1) and to access the first pool (=> ID = 0).

    Starting the pool takes about ~50 seconds.
    Stopping the pool takes less than 10 seconds.

    If the command fails due to a syntax error, the error message can be found in the file log.log
    If the command succeed, there is nothing logged at all in the log file but a message displayed in the console (cmd prompt)

    Quote

    {“success”: true, “status”: null, “commandMessages”: [{“messageCode”: “successStoragePoolStarted”, “messageData”: [“V”]}], “serverMessages”: null}
    => Le pool de stockage est bien démarré pour le volume: V:…

    Notice: In a normal cmd prompt (not run as admin), the command returns an error due to an access denied on the log file:

    Quote

    log4j:ERROR setFile(null,true) call failed.
    java.io.FileNotFoundException: log.log

    Notice: if the Web UI was open before executing a Start/Stop, it must be reopened (or refreshed: CTRL-F5) otherwise it does not display the new state of the pool.

    Regarding the log.log file, this one has better be located in a fix location. Edit the file log4j.properties and set a path like:

    log4j.appender.default.File=C:/FlexRaid/FlexRAIDCmd.log

    Pay attention to the path separator! It’s not the one used by Windows but the one used in Java!

    To shutdown the FlexRaid server after stopping the pool, use the command shutdown-server.

    FlexRaid localhost - - shutdown-server

    If the pool is still running, we get the following response:

    Quote

    {“success”: false, “status”: null, “commandMessages”: [{“messageCode”: “errorShutdownNotAllowedStoragePoolServiceRunning”, “messageData”: []}], serverMessages”: null}
    => Pour pouvoir arrêter le service “host”, le service de pool de stockage doit être arrêté!

    If the service stops successfully, we get :

    Quote

    {“success”: true, “status”: null, “commandMessages”: [{“messageCode”: “successServerShutingDown”, “messageData”: []}], “serverMessages”: null}
    => Arrêt du serveur en cours…

    To restart the service, we can use:

    net start "FlexRaid"

    Notice: I didn’t find yet on the forum the difference between ‘FlexRaid localhost – – shutdown-server’ and ‘net stop “FlexRaid’. To my knowledge ‘net stop’ is synchronous and therefore maybe preferred to stop the service properly before shutting down ?! (FlexRaid message seems to indicate it’s asynchronous)

    Notice: If I run “FlexRaid localhost — shutdown-server” while the service is not running, I get obviously an exception “Connection refused: connect : ConnectException” but also this message in the log file (log.log):

    Quote

    ERROR: Unexpected character (‘A’ (code 65)): expected a valid value (number, String, array, object, ‘true’, ‘false’ or ‘null’)
    at [Source: java.io.StringReader@2f3d698; line: 1, column: 2] org.codehaus.jackson.JsonParseException: Unexpected character (‘A’ (code 65)): expected a valid value (number, String, array, object, ‘true’, ‘false’ or ‘null’)
    at [Source: java.io.StringReader@2f3d698; line: 1, column: 2]

    Now, here is how to create a “shutdown task” in the Local Group Policies of a Windows Server 2012:

    1) Enable script execution on the server
    a) On the Start Screen right-click the Windows PowerShell tile and run it As Administrator
    b) execute “Set-ExecutionPolicy RemoteSigned” in that shell and answer “Y”

    2) Create the script
    a) Create a file “StopFlexRaid.ps1” in your “FlexRaid Client” folder (e.g.).
    b) Type the script found bellow in the file (change the path to FlexRaidCmd)

    3) Use the script as Shutdown Script
    a) On the Start Screen, type “gpedit.msc” and run it.
    b) Go to the node “Computer Configuration\Windows Settings\Scripts (Startup/Shutdown)”.
    c)  Edit “Shutdown” and in the tab “PowerShell script”, “Add” StopFlexRaid.ps1

    Notice:
    – Shutdown scripts are run as Local System, and they have the full rights that are associated with being able to run as Local System.
    – Shutdown scripts are run synchronously. The Server should wait on the script before shutting down.

    Here is the StopFlexRaid script:

    [ps]

    $srvName = "FlexRAID"
    $flexCmd = "C:\Program Files (x86)\FlexRAID 2.0 Client\FlexRAIDCMD.exe"
    $servicePrior = Get-Service $srvName
    #"$srvName is currently " + $servicePrior.status

    function ExitWithCode
    {
    param
    (
    $exitcode
    )
    "Exit with code $exitcode"
    #$host.SetShouldExit($exitcode)
    #exit
    }

    $flexCmd = "C:\Program Files (x86)\FlexRAID 2.0 Client\FlexRAIDCMD.exe"

    function ExecuteFRCmd([string]$cmd, [string]$hostname="localhost", [string]$port="-", [string]$timeout="-")
    {
    $error.clear()

    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = $flexCmd
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = "$hostname $port $timeout $cmd"
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    $p.WaitForExit()
    $output = $p.StandardOutput.ReadToEnd()

    if ( $error.count -eq 0)
    {
    # Clean the JSON message (remove the trailing text (=> blabla))
    $output = $output -replace ‘(?<First>.*)=>.+’, ‘${First}’
    }
    else
    {
    $output = $null
    }

    return $output
    }

    function IsAnyTaskRunning()
    {
    $running = $FALSE

    $state = ExecuteFRCmd("status")

    if ($state -eq $null)
    {
    throw "Command failed to execute"
    }
    else
    {
    #Write-Host "States: $state"

    $process = $state | ConvertFrom-Json

    $message = $process.commandMessages.messageCode
    if ($message -eq "successNoProcessSinceServerStartup")
    {
    #Write-Host "No Process started since Server startup"
    }
    else
    {
    $processID = $process.status.referenceCode

    do {
    $state = ExecuteFRCmd("status "+$processID)
    $process = $state | ConvertFrom-Json

    switch ($process.status.status)
    {
    { @("STATUS_STARTED", "STATUS_PROCESSING", "STATUS_PAUSING", "STATUS_RESUMED", "STATUS_RESUMING") -contains $_ }
    {
    #Write-Host task $processID – $process.status.task – is running
    $running = $TRUE
    }
    { @("STATUS_COMPLETED", "STATUS_ABORTED", "STATUS_ABORTING", "STATUS_PAUSED") -contains $_ }
    {
    #Write-Host task $processID – $process.status.task – is not running
    }
    }

    $processID -=1
    } while (($processID -gt 0) -and ($running -eq $FALSE))
    }
    }

    return $running
    }

    Write-Eventlog -Logname ‘Application’ -source ‘FlexRAID’ -eventID 1 -EntryType Warning -Category 0 -message "Graceful FlexRAID Shutdown triggered"

    $wid = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $prp = new-object System.Security.Principal.WindowsPrincipal($wid)
    $adm = [System.Security.Principal.WindowsBuiltInRole]::Administrator
    $IsAdmin = $prp.IsInRole($adm)
    if (-not $IsAdmin) {
    write-host "Current powershell process is not running with Administrator privileges"

    $message = "Graceful FlexRAID Shutdown not running with adhoc rights…"
    Write-Eventlog -Logname ‘Application’ -source ‘FlexRAID’ -eventID 1 -EntryType Error -Category 0 -message $message
    cmd /c shutdown -a
    ExitWithCode -exitcode 2
    }
    elseif ($servicePrior.status -eq "Stopped")
    {
    "$srvName is already " + $servicePrior.status
    }
    elseif ($servicePrior.status -ne "Running")
    {
    "$srvName is not Running but " + $servicePrior.status
    }
    else
    {
    $running = IsAnyTaskRunning
    if ($running -eq $TRUE)
    {
    $message = "FlexRAID process(es) still running and preventing Server to shutdown…"
    $message
    Write-Eventlog -Logname ‘Application’ -source ‘FlexRAID’ -eventID 1 -EntryType Error -Category 0 -message $message
    cmd /c shutdown -a
    ExitWithCode -exitcode 2
    }
    else
    {
    "Wait on the Storage Pool to stop. This can take a few seconds."

    $state = ExecuteFRCmd("view class1_0 stop")

    $state
    $abort = "False"

    if ( $state -eq $null)
    {
    "Storage Pool failed to stop"
    $error[0] $message = "FlexRaid Storage Pool failed to stop and is preventing Server to shutdown: " + $error[0] $message
    Write-Eventlog -Logname ‘Application’ -source ‘FlexRAID’ -eventID 1 -EntryType Error -Category 0 -message $message
    cmd /c shutdown -a
    ExitWithCode -exitcode 2
    }
    else
    {
    $process = $state | ConvertFrom-Json

    $message = $process.commandMessages.messageCode
    if ($message -eq "successStoragePoolStopped")
    {
    "Storage Pool successfuly stopped"
    Write-Eventlog -Logname ‘Application’ -source ‘FlexRAID’ -eventID 1 -EntryType Warning -Category 0 -message "Storage Pool stopped before shutting down"
    }
    else
    {
    if ($message -eq "errorNoActiveStoratePool")
    {
    "Storage Pool actually not started"
    }
    else
    {
    $abort = "True"
    $event = "FlexRaid Storage Pool failed to stop, preventing Server to shutdown: " + $state
    $event
    Write-Eventlog -Logname ‘Application’ -source ‘FlexRAID’ -eventID 1 -EntryType Error -Category 0 -message $event
    cmd /c shutdown -a
    ExitWithCode -exitcode 3
    }
    }

    if ($abort -eq "False")
    {
    $error.clear()
    Stop-Service $srvName
    if ( $error.count -eq 0)
    {
    Write-Host -NoNewLine "Waiting on $srvName to stop "
    $timeout = new-timespan -Minutes 1
    $sw = [diagnostics.stopwatch]::StartNew()
    while (((Get-Service $srvName).status -ne "Stopped") -and ($sw.elapsed -lt $timeout))
    {
    Write-Host -NoNewLine "."
    sleep 1
    }
    "."
    }

    $serviceAfter = Get-Service $srvName
    if ($serviceAfter.status -eq "Stopped")
    {
    "$srvName is now " + $serviceAfter.status
    ExitWithCode -exitcode 0
    }
    else
    {
    "$srvName failed to stop. It is now " + $serviceAfter.status
    ExitWithCode -exitcode 1
    }
    }
    }
    }
    }[/ps]

    Here is the code to start FlexRaid, useful while testing.

    [ps]

    $srvName = "FlexRAID"
    $flexCmd = "C:\Program Files (x86)\FlexRAID 2.0 Client\FlexRAIDCMD.exe"
    $servicePrior = Get-Service $srvName
    #"$srvName is currently " + $servicePrior.status

    function ExitWithCode
    {
    param
    (
    $exitcode
    )
    "Exit with code $exitcode"
    #$host.SetShouldExit($exitcode)
    #exit
    }

    if ( ($servicePrior.status -ne "Stopped") -and ($servicePrior.status -ne "Running"))
    {
    "$srvName is not Stopped but " + $servicePrior.status
    }
    else
    {
    if ($servicePrior.status -eq "Running")
    {
    "$srvName is already " + $servicePrior.status
    }
    else
    {
    Start-Service $srvName

    Write-Host -NoNewLine "Waiting on $srvName to start "
    $timeout = new-timespan -Minutes 1
    $sw = [diagnostics.stopwatch]::StartNew()
    while (((Get-Service $srvName).status -ne "Running") -and ($sw.elapsed -lt $timeout))
    {
    Write-Host -NoNewLine "."
    sleep 1
    }
    "."
    }

    $serviceAfter = Get-Service $srvName
    if ($serviceAfter.status -eq "Running")
    {
    "$srvName is now " + $serviceAfter.status

    $error.clear()
    "Wait on the Storage Pool to start. This can take a while."
    $stopPool = Start-Process $flexCmd -ArgumentList "localhost – – view class1_0 start" -NoNewWindow -Wait -PassThru

    if ( $error.count -eq 0)
    {
    ExitWithCode -exitcode 0
    }
    else
    {
    "Storage Pool failed to start"
    $error[0] ExitWithCode -exitcode 2
    }
    }
    else
    {
    "$srvName failed to start. It is now " + $serviceAfter.status
    ExitWithCode -exitcode 1
    }
    }

    [/ps]

    Loading