public static SpecHomeVm GetCommunityUnit(CommunityUnitType communityUnitType)
        {
            SpecHomeVm obj = new SpecHomeVm
            {
                PriceRange     = new MeasureBoundaryVm <decimal, MoneyType>(),
                LivingSpace    = new MeasureBoundaryVm <int, LivingSpaceMeasure>(),
                Deposit        = new MeasureBoundaryVm <decimal, MoneyType>(),
                ApplicationFee = new MeasureBoundaryVm <decimal, MoneyType>(),
                PetDeposit     = new MeasureBoundaryVm <decimal, MoneyType>(),
                AvailableBedroomsFromQuantity = MSLivingChoices.Bcs.Components.ItemTypeBc.Instance.GetBedrooms().ToSelectListItemList()
            };

            obj.AvailableBedroomsToQuantity    = obj.AvailableBedroomsFromQuantity;
            obj.AvailableBathroomsFromQuantity = MSLivingChoices.Bcs.Components.ItemTypeBc.Instance.GetBathrooms().ToSelectListItemList();
            obj.AvailableBathroomsToQuantity   = obj.AvailableBathroomsFromQuantity;
            obj.CustomAmenities = new List <AmenityVm>
            {
                new AmenityVm()
            };
            obj.DefaultAmenities = AmenityBc.Instance.GetDefaultAmenities(communityUnitType).ConvertAll((Amenity m) => new CheckBoxVm
            {
                Value = m.ClassId.ToString(),
                Text  = m.Name
            });
            obj.Images = new ImageListVm(DisplayHelpers.GetDisplayNameForCommunityUnitImages(communityUnitType));
            return(obj);
        }
        public override void Display()
        {
            var topLevel = DataService.Get(CurrentParentID);

            if (string.IsNullOrEmpty(topLevel.Name))
            {
                var str = string.Format("Category name: {0}", topLevel.Name);
                Output.WriteLine(ConsoleColor.Green, str);
            }

            DisplayHelpers.WriteTable("Choose category to delete", topLevel.Childs);

            var itemToRemoveId = Input.ReadInt();

            var possibleIds = topLevel.Childs.Select(x => x.Id);

            if (possibleIds.Contains(itemToRemoveId))
            {
                DataService.Remove(itemToRemoveId);
                Output.WriteLine("Item deleted");
            }
            else
            {
                Output.DisplayPrompt("Item cannot be deleted");
            }

            Input.ReadString("Press [Enter] to navigate home");

            Program.NavigateBack();
        }
Example #3
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        label    = EditorGUI.BeginProperty(position, label, property);
        position = EditorGUI.PrefixLabel(position, label);

        EditorGUI.BeginChangeCheck();

        // Store old indent level and set it to 0, the PrefixLabel takes care of it
        int indent = EditorGUI.indentLevel;

        EditorGUI.indentLevel = 0;

        float prevHeight = position.y - EditorGUIUtility.standardVerticalSpacing;
        var   propnames  = PropNames();
        var   props      = DisplayHelpers.Properties(property, propnames).ToArray();

        for (int ii = 0; ii < props.Length; ++ii)
        {
            var sp = props[ii];
            prevHeight += EditorGUIUtility.standardVerticalSpacing;
            var  myHeight = EditorGUI.GetPropertyHeight(sp, true);
            Rect r        = new Rect(position.x, prevHeight, position.width, myHeight);
            EditorGUI.PropertyField(r, sp, new GUIContent(propnames[ii]));
            prevHeight += myHeight;
        }

        if (EditorGUI.EndChangeCheck())
        {
            property.serializedObject.ApplyModifiedProperties();
        }

        EditorGUI.indentLevel = indent;
        EditorGUI.EndProperty();
    }
        public override void Display()
        {
            var list = DataService.GetChilds(ParentId);

            var possibleIds = list.Select(x => x.Id);

            DisplayHelpers.WriteTable("display top level", list);

            if (list.Any())
            {
                var intValue = Input.ReadInt();

                this.ParentId = intValue;
            }
            else
            {
                this.ParentId = null;
            }

            Input.ReadString("Press [Enter] to navigate");

            var dlp = Program.SetPage <DisplayListPage>();

            Input.ReadString("Press [Enter] to navigate home");

            Program.NavigateBack();
        }
        public static HouseVm GetHouseUnit()
        {
            HouseVm houseVm = new HouseVm()
            {
                PriceRange     = new MeasureBoundaryVm <decimal, MoneyType>(),
                LivingSpace    = new MeasureBoundaryVm <int, LivingSpaceMeasure>(),
                Deposit        = new MeasureBoundaryVm <decimal, MoneyType>(),
                ApplicationFee = new MeasureBoundaryVm <decimal, MoneyType>(),
                PetDeposit     = new MeasureBoundaryVm <decimal, MoneyType>(),
                AvailableBedroomsFromQuantity  = MSLivingChoices.Bcs.Components.ItemTypeBc.Instance.GetBedrooms().ToSelectListItemList(),
                AvailableBedroomsToQuantity    = houseVm.AvailableBedroomsFromQuantity,
                AvailableBathroomsFromQuantity = MSLivingChoices.Bcs.Components.ItemTypeBc.Instance.GetBathrooms().ToSelectListItemList(),
                AvailableBathroomsToQuantity   = houseVm.AvailableBathroomsFromQuantity,
                CustomAmenities = new List <AmenityVm>()
                {
                    new AmenityVm()
                },
                DefaultAmenities = AmenityBc.Instance.GetDefaultAmenities(CommunityUnitType.House).ConvertAll <CheckBoxVm>((Amenity m) => new CheckBoxVm()
                {
                    Value = m.ClassId.ToString(),
                    Text  = m.Name
                }),
                Images  = new ImageListVm(DisplayHelpers.GetDisplayNameForCommunityUnitImages(CommunityUnitType.House)),
                Address = AdminViewModelsProvider.GetAddressVm()
            };

            return(houseVm);
        }
Example #6
0
        public override string ToString()
        {
            var pieceFile         = MovingPieceService.FileFromIdx(SquareIndex);
            var pawnDescription   = $"{Color.AsString()}";
            var pieceDescription  = $"Piece";
            var pawnPlacement     = $"on {DisplayHelpers.ToSquareString(SquareIndex)} ";
            var expectedIndexes   = MovingPieceService.GetSetBits(Expected);
            var playerOccupancy   = MovingPieceService.GetSetBits(PlayerObstructions);
            var opponentOccupancy = MovingPieceService.GetSetBits(OpponentObstructions);
            var strMoves          =
                expectedIndexes.Any()
                    ? $"move to {string.Join(", ", expectedIndexes.Select(DisplayHelpers.ToSquareString))}"
                    : "[no moves expected]";
            var strPlayerOccupancy =
                playerOccupancy.Any()
                    ? string.Join(", ", playerOccupancy.Select(DisplayHelpers.ToSquareString))
                    : "[no player pieces]";
            var strOpponentOccupancy =
                opponentOccupancy.Any()
                    ? string.Join(", ", opponentOccupancy.Select(DisplayHelpers.ToSquareString))
                    : "[no opponent pieces]";
            var attackedOpponentPieces = opponentOccupancy.Where(x => MovingPieceService.FileFromIdx(x) != pieceFile);
            var strAttack = attackedOpponentPieces.Any()
                ? $"- Attack pieces on {string.Join(", ", attackedOpponentPieces.Select(DisplayHelpers.ToSquareString))}"
                : "[no attacked pieces]";

            return($"{pawnDescription} {pieceDescription} on {pawnPlacement} should be able to:{Environment.NewLine}" +
                   $"{strMoves}{Environment.NewLine}" +
                   $"{strAttack}{Environment.NewLine}" +
                   $"when players pieces are at {strPlayerOccupancy} and opponent pieces are at {strOpponentOccupancy}.");
        }
Example #7
0
        public override void Display()
        {
            var topLevel = DataService.Get(CurrentParentID);

            DisplayHelpers.Display(topLevel);

            base.Display();
        }
Example #8
0
            private async void ServiceList_SelectionChanged()
            {
                var service = (GattDeviceService)((ComboBoxItem)ServiceList.SelectedItem)?.Tag;

                CharacteristicList.Items.Clear();
                RemoveValueChangedHandler();

                IReadOnlyList <GattCharacteristic> characteristics = null;

                try
                {
                    // Ensure we have access to the device.
                    var accessStatus = await service.RequestAccessAsync();

                    if (accessStatus == DeviceAccessStatus.Allowed)
                    {
                        // BT_Code: Get all the child characteristics of a service. Use the cache mode to specify uncached characterstics only
                        // and the new Async functions to get the characteristics of unpaired devices as well.
                        var result = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                        if (result.Status == GattCommunicationStatus.Success)
                        {
                            characteristics = result.Characteristics;
                        }
                        else
                        {
                            rootPage.NotifyUser("Error accessing service.", NotifyType.ErrorMessage);

                            // On error, act as if there are no characteristics.
                            characteristics = new List <GattCharacteristic>();
                        }
                    }
                    else
                    {
                        // Not granted access
                        rootPage.NotifyUser("Error accessing service.", NotifyType.ErrorMessage);

                        // On error, act as if there are no characteristics.
                        characteristics = new List <GattCharacteristic>();
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Restricted service. Can't read characteristics: " + ex.Message,
                                        NotifyType.ErrorMessage);
                    // On error, act as if there are no characteristics.
                    characteristics = new List <GattCharacteristic>();
                }

                foreach (GattCharacteristic c in characteristics)
                {
                    CharacteristicList.Items.Add(new ComboBoxItem {
                        Content = DisplayHelpers.GetCharacteristicName(c), Tag = c
                    });
                }
                CharacteristicList.Visibility = Visibility.Visible;
            }
        static void GetInputForSingleConvert()
        {
            string docExtention   = ".doc";
            string docxExtention  = ".docx";
            string filePath       = string.Empty;
            string targetLocation = string.Empty;

            do
            {
                DisplayHelpers.Print("Fully qualified path of the file(including the file name): ", Color.Gray, ConsoleWriteMethod.Write);
                filePath = System.Console.ReadLine();

                if (File.Exists($"{filePath}{docExtention}"))
                {
                    validFileInput = true;
                    filePath      += docExtention;
                }
                else if (File.Exists($"{filePath}{docxExtention}"))
                {
                    validFileInput = true;
                    filePath      += docxExtention;
                }
                else
                {
                    DisplayHelpers.Print("File doesnt exist.\n", Color.DarkRed, ConsoleWriteMethod.WriteLine);
                    validFileInput = false;
                }

                if (validFileInput)
                {
                    DisplayHelpers.Print("Target location for the converted file (leave blank if for the current directory): ", Color.Gray, ConsoleWriteMethod.Write);
                    targetLocation = System.Console.ReadLine();

                    if (string.IsNullOrWhiteSpace(targetLocation))
                    {
                        targetLocation = FileHelpers.GetDirectoryFromFilePath(filePath);
                    }

                    if (!Directory.Exists(targetLocation))
                    {
                        DisplayHelpers.Print("Path doesnt exist so will be created.", Color.Yellow, ConsoleWriteMethod.WriteLine);
                        try
                        {
                            Directory.CreateDirectory(targetLocation);
                        }
                        catch (Exception)
                        {
                            DisplayHelpers.Print("Something went wrong while creating the specified path.", Color.DarkRed, ConsoleWriteMethod.WriteLine);
                            Environment.Exit(0);
                        }
                    }
                }
            } while (!validFileInput);


            Directories.Add(filePath, string.IsNullOrWhiteSpace(targetLocation) ? filePath : targetLocation);
        }
Example #10
0
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        SerializedProperty enumVal = property.FindPropertyRelative(enumProperty);
        SerializedProperty duVal   = property.FindPropertyRelative(propName(enumVal.enumValueIndex));

        return(EditorGUI.GetPropertyHeight(enumVal) + EditorGUI.GetPropertyHeight(duVal, true) +
               DisplayHelpers.GetPropertyHeight(property, OtherPropNames(), label) +
               2 * EditorGUIUtility.standardVerticalSpacing);
    }
Example #11
0
        public override void Display()
        {
            var topLevel = DataService.GetTopLevel();

            DisplayHelpers.WriteTable("display top level", topLevel);

            Input.ReadString("Press [Enter] to navigate home");

            Program.NavigateBack();
        }
Example #12
0
            private async void ConnectButton_Click()
            {
                ConnectButton.IsEnabled = false;

                if (!await ClearBluetoothLEDeviceAsync())
                {
                    rootPage.NotifyUser("Error: Unable to reset state, try again.", NotifyType.ErrorMessage);
                    ConnectButton.IsEnabled = true;
                    return;
                }

                try
                {
                    // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
                    bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(rootPage.SelectedBleDeviceId);

                    if (bluetoothLeDevice == null)
                    {
                        rootPage.NotifyUser("Failed to connect to device.", NotifyType.ErrorMessage);
                    }
                }
                catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE)
                {
                    rootPage.NotifyUser("Bluetooth radio is not on.", NotifyType.ErrorMessage);
                }

                if (bluetoothLeDevice != null)
                {
                    // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method.
                    // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system).
                    // If the services supported by the device are expected to change during BT usage, subscribe to the GattServicesChanged event.
                    GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        var services = result.Services;
                        rootPage.NotifyUser(String.Format("Found {0} services", services.Count), NotifyType.StatusMessage);
                        foreach (var service in services)
                        {
                            ServiceList.Items.Add(new ComboBoxItem {
                                Content = DisplayHelpers.GetServiceName(service), Tag = service
                            });
                        }
                        ConnectButton.Visibility = Visibility.Collapsed;
                        ServiceList.Visibility   = Visibility.Visible;
                    }
                    else
                    {
                        rootPage.NotifyUser("Device unreachable", NotifyType.ErrorMessage);
                    }
                }
                ConnectButton.IsEnabled = true;
            }
        public async void Connect(string id)
        {
            try
            {
                // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
                bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(id);

                if (bluetoothLeDevice == null)
                {
                    Log.d("Failed to connect to device.", NotifyType.ErrorMessage);
                    return;
                }

                bluetoothLeDevice.ConnectionStatusChanged += ConnectionStatusChangedHandler;

                mBluetoothGatt = await GattSession.FromDeviceIdAsync(bluetoothLeDevice.BluetoothDeviceId);

                mBluetoothGatt.MaintainConnection = true;
            }
            catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE)
            {
                Log.d("Bluetooth radio is not on.", NotifyType.ErrorMessage);
                return;
            }

            if (bluetoothLeDevice != null)
            {
                // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method.
                // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system).
                // If the services supported by the device are expected to change during BT usage, subscribe to the GattServicesChanged event.
                GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesForUuidAsync(RX_SERVICE_UUID);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    _services.Clear();
                    _services.AddRange(result.Services);

                    Log.d(String.Format("Found {0} services", _services.Count), NotifyType.StatusMessage);
                    foreach (var service in _services)
                    {
                        Log.d("SERVICE: " + DisplayHelpers.GetServiceName(service));
                        GetCharachteristics(service);
                    }
                }
                else
                {
                    Log.d("Device unreachable", NotifyType.ErrorMessage);
                }
            }
        }
Example #14
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        label = EditorGUI.BeginProperty(position, label, property);
        var label_position = position;

        position = EditorGUI.PrefixLabel(position, label);

        EditorGUI.BeginChangeCheck();
        SerializedProperty enumVal = property.FindPropertyRelative(enumProperty);
        SerializedProperty duVal   = property.FindPropertyRelative(propName(enumVal.enumValueIndex));

        //int indent = EditorGUI.indentLevel;
        //EditorGUI.indentLevel = 0;

        float pw = position.width;
        float lw = label_position.width;

        float h1    = EditorGUI.GetPropertyHeight(enumVal);
        Rect  rect1 = new Rect(position.x, position.y, pw, h1);

        float prevHeight = position.y + h1; //Don't need to subtract vertical spacing since 1 is alreadyt required
        var   propnames  = OtherPropNames();
        var   props      = DisplayHelpers.Properties(property, propnames).ToArray();

        for (int ii = 0; ii < props.Length; ++ii)
        {
            var sp = props[ii];
            prevHeight += EditorGUIUtility.standardVerticalSpacing;
            var  myHeight = EditorGUI.GetPropertyHeight(sp, true);
            Rect r        = new Rect(label_position.x, prevHeight, lw, myHeight);
            EditorGUI.PropertyField(r, sp, new GUIContent(propnames[ii]));
            prevHeight += myHeight;
        }
        Rect rect2 = new Rect(label_position.x + lw * LabelOffset, prevHeight + EditorGUIUtility.standardVerticalSpacing,
                              lw * (1 - LabelOffset), EditorGUI.GetPropertyHeight(duVal, true));

        EditorGUI.PropertyField(rect1, enumVal, GUIContent.none);
        EditorGUI.PropertyField(rect2, duVal, GUIContent.none);

        if (EditorGUI.EndChangeCheck())
        {
            property.serializedObject.ApplyModifiedProperties();
        }

        //EditorGUI.indentLevel = indent;
        EditorGUI.EndProperty();
    }
        public override void Display()
        {
            var topLevel = DataService.Get(CurrentParentID);

            DisplayHelpers.Display(topLevel, "Choose category to open");

            var selectedId = Input.ReadInt();

            var possibleIds = topLevel.Childs.Select(x => x.Id);

            if (possibleIds.Contains(selectedId))
            {
                CurrentParentID = selectedId;
            }
            else
            {
                Output.DisplayPrompt("Item cannot be open");
            }

            Program.NavigateTo <DisplayCategory>();
        }
        static string GetOutputDirectory()
        {
            string path = string.Empty;

            do
            {
                DisplayHelpers.Print("Enter output path (leave blank if for the current directory): ", Color.Gray, ConsoleWriteMethod.Write);
                path = System.Console.ReadLine();

                if (Directory.Exists(path))
                {
                    validFileOutput = true;
                    return(path);
                }
                else
                {
                    try
                    {
                        if (string.IsNullOrWhiteSpace(path))
                        {
                            validFileOutput = true;
                        }
                        else
                        {
                            DisplayHelpers.Print("Directory doesnt exist so will be created.", Color.Yellow, ConsoleWriteMethod.WriteLine);
                            Directory.CreateDirectory(path);
                            validFileOutput = true;
                        }
                        return(path);
                    }
                    catch (Exception)
                    {
                        validFileOutput = false;
                        DisplayHelpers.Print("Invalid directory.\n", Color.DarkRed, ConsoleWriteMethod.WriteLine);
                    }
                }
            } while (!validFileOutput);
            return(path);
        }
        static string GetInputForDirectoryConvert()
        {
            string path = string.Empty;

            do
            {
                DisplayHelpers.Print("Enter directory path: ", Color.Gray, ConsoleWriteMethod.Write);
                path = System.Console.ReadLine();

                if (Directory.Exists(path))
                {
                    validDirectoryInput = true;
                    return(path);
                }
                else
                {
                    validDirectoryInput = false;
                    DisplayHelpers.Print("Invalid directory.\n", Color.DarkRed, ConsoleWriteMethod.WriteLine);
                }
            } while (!validDirectoryInput);
            return(path);
        }
        static void ConvertSingle(string source, string destination)
        {
            if (!string.IsNullOrWhiteSpace(source) && !string.IsNullOrWhiteSpace(destination))
            {
                string pdfExtension = ".pdf";
                var    extension    = Path.GetExtension(source);

                if (FileHelpers.IsValidWordFile(extension))
                {
                    var fileName = FileHelpers.GetFileName(source);

                    var converter = new Word2Pdf()
                    {
                        InputLocation  = source,
                        OutputLocation = Path.Combine(destination, $"{fileName}{pdfExtension}")
                    };

                    if (source == destination)
                    {
                        var sourceExtension = Path.GetExtension(source);
                        converter.OutputLocation = source.Replace(sourceExtension, pdfExtension);
                    }

                    DisplayHelpers.Print("\nConverting File: " + fileName, Color.Yellow, ConsoleWriteMethod.WriteLine);

                    try
                    {
                        var result = converter.Word2PdfCOnversion();
                        DisplayHelpers.Print("Done..", Color.DarkGreen, ConsoleWriteMethod.WriteLine);
                    }
                    catch (Exception ex)
                    {
                        DisplayHelpers.Print($"Something went wrong. Message: {ex.Message}.\n", Color.DarkRed, ConsoleWriteMethod.WriteLine);
                    }
                }
            }
        }
        static int SelectMenuOption()
        {
            var count          = (int)Enum.GetValues(typeof(MenuOption)).Cast <MenuOption>().Max();
            int selectedOption = 0;

            do
            {
                DisplayHelpers.Print("\nselect an option: ", Color.Gray, ConsoleWriteMethod.Write);
                int.TryParse(System.Console.ReadLine(), out int option);

                if (option < (count + 1) && option > 0)
                {
                    validMenuOptionSelected = true;
                    selectedOption          = option;
                }
                else
                {
                    DisplayHelpers.Print("Invalid option.", Color.DarkRed, ConsoleWriteMethod.WriteLine);
                    validMenuOptionSelected = false;
                }
            } while (!validMenuOptionSelected);

            return(selectedOption);
        }
Example #20
0
 public void Setup()
 {
     DisplayHelpers.Register();
 }
Example #21
0
 public override float GetPropertyHeight(SerializedProperty property, GUIContent label) =>
 DisplayHelpers.GetPropertyHeight(property, PropNames(), label);
Example #22
0
        /// <summary>
        /// The actual program, needs to be waited
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        static async Task Run(string[] args)
        {
            LogHelper.PrintHeader();

            LogHelper.PrintTitle("Configuration");
            bool configSucceed = await Configure(args);

            if (!configSucceed)
            {
                LogHelper.Error("Something went wrong during configuration");
            }
            else
            {
                #region connection

                LogHelper.PrintTitle("Connection");
                LogHelper.Pending("Looking for BLE device of id " + Configuration.device.deviceId);
                device = await BleUtility.Connect(Configuration.device.deviceId);

                if (device == null)
                {
                    LogHelper.Error("Failed to connect to device");
                }

                #endregion

                #region services

                GattDeviceService targettedService = null;
                if (device != null)
                {
                    LogHelper.PrintTitle("Services");
                    LogHelper.Pending("Looking for service " + Configuration.device.deviceServiceName + "...");

                    IReadOnlyList <GattDeviceService> services = await BleUtility.GetServices(device);

                    if (services != null)
                    {
                        LogHelper.Ok(String.Format("Found {0} service(s)", services.Count));
                        foreach (var service in services)
                        {
                            if (DisplayHelpers.GetServiceName(service) == Configuration.device.deviceServiceName)
                            {
                                LogHelper.Ok("Found service " + Configuration.device.deviceServiceName);
                                targettedService = service;
                                break;
                            }
                        }

                        if (targettedService == null)
                        {
                            LogHelper.Error("Couldn't find service " + Configuration.device.deviceServiceName);
                        }
                    }
                    else
                    {
                        LogHelper.Error("Device unreachable");
                    }
                }

                #endregion

                #region caracteristics

                GattCharacteristic characteristic = null;
                if (targettedService != null)
                {
                    LogHelper.PrintTitle("Caracteristics");
                    LogHelper.Pending("Looking for characteristic " + Configuration.device.deviceCharacteristicName + "...");
                    IReadOnlyList <GattCharacteristic> characteristics = await BleUtility.GetCharacteristics(targettedService);

                    if (characteristics == null)
                    {
                        LogHelper.Error("Could not find characteristics of " + Configuration.device.deviceName);
                    }
                    else
                    {
                        foreach (var charact in characteristics)
                        {
                            if (DisplayHelpers.GetCharacteristicName(charact) == Configuration.device.deviceCharacteristicName)
                            {
                                LogHelper.Ok("Found characteristic");
                                characteristic = charact;
                            }
                        }

                        if (characteristic == null)
                        {
                            LogHelper.Error("Could not find characteristic " + Configuration.device.deviceCharacteristicName);
                        }
                    }
                }

                #endregion

                #region show config

                LogHelper.PrintTitle("Save your config");
                LogHelper.Ok("Using configuration:");
                LogHelper.Log(Configuration.GetArgumentDetails());
                LogHelper.Log("\"" + Configuration.ToArgument() + "\"");
                LogHelper.Ok("Copy the line below, and run the program with this argument to [...]");
                LogHelper.Ok("[...] start the program automatically with the current configuration");

                #endregion

                #region communication

                if (characteristic != null)
                {
                    LogHelper.PrintTitle("Communication");

                    if (BleUtility.IsWriteableCharateristic(characteristic))
                    {
                        Loop(characteristic);
                    }
                    else
                    {
                        LogHelper.Error("This characteristic does not have either the 'Write' or 'WriteWithoutResponse' properties");
                    }
                }

                #endregion
            }

            #region cleanup

            LogHelper.PrintTitle("Cleanup");
            LogHelper.Pending("Exiting properly");
            device?.Dispose();
            LogHelper.Ok("Done. Type a key to exit");
            Console.ReadKey(true);

            #endregion
        }
        static void Main(string[] args)
        {
            DisplayHelpers.PrintIntro();
            DisplayHelpers.PrintMenu();

            while (true)
            {
                int selectedMenuOption = SelectMenuOption();

                switch (selectedMenuOption)
                {
                case (int)MenuOption.SingleConvert:
                {
                    //print single convert text
                    DisplayHelpers.PrintSingleConvert();

                    //get input for single convert
                    GetInputForSingleConvert();

                    //convert the input file
                    ConvertMany();

                    //clear the directories
                    ClearDirectories();
                    break;
                }

                case (int)MenuOption.DirectoryConvert:
                {
                    //print directory convert text
                    DisplayHelpers.PrintDirectoryConvert();

                    //get directory which needs to be converted
                    var directoryPath = GetInputForDirectoryConvert();

                    //get all the files from the directory
                    var fileNames = FileHelpers.GetFilesInDirectory(directoryPath);

                    //get valid word files from the files in the given directory
                    var validFileNames = FileHelpers.ExtractValidWordFiles(fileNames);

                    if (validFileNames?.Any() ?? false)
                    {
                        DisplayHelpers.Print($"\nFound {validFileNames.Length} files which can be convert to PDF.", Color.Yellow, ConsoleWriteMethod.WriteLine);

                        //display all the valid file names
                        DisplayHelpers.DisplayValidFileNames(validFileNames);

                        //get output path
                        var outputPath = GetOutputDirectory();

                        //set output path to be default source path if blank
                        if (string.IsNullOrWhiteSpace(outputPath))
                        {
                            outputPath = GetOutputDirectoryIfEmptyInput(validFileNames?.FirstOrDefault());
                        }

                        //prepare the directories dictionary with the valid filenames and their output path
                        foreach (var fileName in validFileNames)
                        {
                            Directories.Add(fileName, outputPath);
                        }

                        //convert the input files
                        ConvertMany();
                        DisplayHelpers.Print($"\nSuccessfully converted {validFileNames.Length} Files.", Color.DarkGreen, ConsoleWriteMethod.WriteLine);
                    }
                    else
                    {
                        DisplayHelpers.Print("No valid word files found in the provided directory.", Color.DarkRed, ConsoleWriteMethod.WriteLine);
                    }

                    //clear the directories
                    ClearDirectories();
                    break;
                }

                case (int)MenuOption.Quit:
                    DisplayHelpers.Print("Exiting...\n", Color.Gray, ConsoleWriteMethod.WriteLine);
                    Environment.Exit(0);
                    break;

                default:
                    DisplayHelpers.Print("Exiting...\n", Color.Gray, ConsoleWriteMethod.WriteLine);
                    Environment.Exit(0);
                    break;
                }
            }
        }
Example #24
0
        /// <summary>
        /// It looks for the compatible devices (discovery + analysis). Then, it asks
        /// for the user to choose the device. The selected device is returned
        /// through a CompatibleEndPoint object. It contains the id, service and
        /// characteristic name.
        /// </summary>
        /// <returns>The complete device id (or CompatibleEndPoint with all fields set as null if none were selected)</returns>
        static async Task <CompatibleEndPoint> AutomaticScan()
        {
            BleUtility.Discovery bleDiscovery = new BleUtility.Discovery();
            bleDiscovery.Start();

            LogHelper.Overwrite(true);
            LogHelper.NewLine(false);

            while (!bleDiscovery.HasEnded())
            {
                Thread.Sleep(50);
            }
            LogHelper.Overwrite(false);
            LogHelper.NewLine(true);
            LogHelper.Log("");

            LogHelper.Ok("Devices:");
            LogHelper.IncrementIndentLevel();
            List <DeviceInformation> devices = bleDiscovery.GetDevices();

            foreach (DeviceInformation device in devices)
            {
                LogHelper.Ok(device.Id + " " + device.Name);
            }
            LogHelper.DecrementIndentLevel();

            List <CompatibleEndPoint> compatibleEndPoints = new List <CompatibleEndPoint>();

            LogHelper.Pending("Checking compatibility of each device");
            LogHelper.IncrementIndentLevel();
            foreach (DeviceInformation device in devices)
            {
                LogHelper.Pending("Checking compatibility of device " + device.Id.Split("-").Last());
                LogHelper.IncrementIndentLevel();

                LogHelper.Pending("Connecting to device...");
                BluetoothLEDevice connection = await BleUtility.Connect(device.Id);

                if (connection == null)
                {
                    LogHelper.DecrementIndentLevel();
                    LogHelper.Warn("Failed to connect (doesn't mean that it's incompatible)");
                    continue;
                }
                LogHelper.Ok("Connected");

                LogHelper.Pending("Looking for services...");
                IReadOnlyList <GattDeviceService> services = await BleUtility.GetServices(connection);

                if (services == null)
                {
                    LogHelper.DecrementIndentLevel();
                    LogHelper.Warn("Gatt communication failed");
                    continue;
                }
                else if (services.Count == 0)
                {
                    LogHelper.DecrementIndentLevel();
                    LogHelper.Warn("No services found");
                    continue;
                }
                LogHelper.Ok(services.Count + " service(s) found");

                LogHelper.Pending("Looking for characteristics for each service...");
                LogHelper.IncrementIndentLevel();
                foreach (GattDeviceService service in services)
                {
                    LogHelper.Pending("Looking for characteristics of service " + DisplayHelpers.GetServiceName(service));
                    LogHelper.IncrementIndentLevel();

                    IReadOnlyList <GattCharacteristic> characteristics = await BleUtility.GetCharacteristics(service);

                    if (characteristics == null)
                    {
                        LogHelper.DecrementIndentLevel();
                        LogHelper.Warn("Failed to retrieve characteristics");
                        service.Dispose();
                        continue;
                    }
                    else if (characteristics.Count == 0)
                    {
                        LogHelper.DecrementIndentLevel();
                        LogHelper.Warn("No characteristics found");
                        service.Dispose();
                        continue;
                    }
                    LogHelper.Ok(characteristics.Count + " characteristic(s) found");

                    LogHelper.Pending("Checking compatibility of each characteristic...");
                    LogHelper.IncrementIndentLevel();
                    int compatibleCpt = 0;
                    foreach (GattCharacteristic characteristic in characteristics)
                    {
                        LogHelper.Pending("Checking characteristic " + DisplayHelpers.GetCharacteristicName(characteristic) + "...");

                        if (BleUtility.IsWriteableCharateristic(characteristic))
                        {
                            CompatibleEndPoint endPoint = new CompatibleEndPoint(
                                device.Id,
                                device.Name,
                                DisplayHelpers.GetServiceName(service),
                                DisplayHelpers.GetCharacteristicName(characteristic)
                                );

                            compatibleCpt++;
                            compatibleEndPoints.Add(endPoint);
                            LogHelper.Ok("Compatible!");
                        }
                        else
                        {
                            LogHelper.Warn("Not compatible");
                        }
                    }

                    service.Dispose();
                    LogHelper.DecrementIndentLevel();
                    LogHelper.Ok(compatibleCpt + " compatible endpoint(s) found");
                    LogHelper.DecrementIndentLevel();
                }
                LogHelper.Ok("Finished looking for characteristics");
                LogHelper.DecrementIndentLevel();

                LogHelper.Ok("Finished compatibility check of device " + device.Id.Split('-').Last());
                LogHelper.DecrementIndentLevel();
            }
            LogHelper.DecrementIndentLevel();
            LogHelper.Ok("Finished analyzing devices");

            if (compatibleEndPoints.Count == 0)
            {
                LogHelper.Error("No compatible device found");
                LogHelper.Error("Make sure that you're not already connected to it");
                return(new CompatibleEndPoint(null, null, null, null));
            }
            else
            {
                LogHelper.Ok("Compatible device(s):");
                LogHelper.IncrementIndentLevel();
                string[] ids = new string[compatibleEndPoints.Count];
                for (int i = 0; i < compatibleEndPoints.Count; i++)
                {
                    CompatibleEndPoint compatibleEndPoint = compatibleEndPoints.ElementAt(i);
                    LogHelper.Ok("name = '" + compatibleEndPoint.deviceName + "' id = '" + compatibleEndPoint.deviceId + "'");
                    ids[i] = compatibleEndPoint.deviceId + (compatibleEndPoint.deviceName != "" ? (" " + compatibleEndPoint.deviceName) : "");
                }
                LogHelper.DecrementIndentLevel();

                int choice = LogHelper.AskUserToChoose("Choose the device to use: ", ids);
                bleDiscovery.Dispose();
                return(compatibleEndPoints.ElementAt(choice));
            }
        }