Exemplo n.º 1
0
        public List<Station> getStations(Inputs input)
        {
            List<Station> ret = new List<Station>();

            RegistryManager registry = new RegistryManager();
            byte[] value = registry.getStations(input);

            int segmentLength = 40;
            int stationEndpoint = segmentLength * registry.getStationCount(input);
            for (int i = 8; i < stationEndpoint; i += segmentLength)
            {
                ArraySegment<byte> segment = new ArraySegment<byte>(value, i, segmentLength);

                Station s = new Station();
                s.Input = input;
                s.PhysicalChannel = BitConverter.ToInt16(segment.Array, segment.Offset + (int)StationBytePositions.PhysicalChannel);
                s.VirtualChannel = BitConverter.ToInt16(segment.Array, segment.Offset + (int)StationBytePositions.VirtualChannel);
                s.SubChannel = segment.Array[segment.Offset + (int)StationBytePositions.SubChannel];

                // TODO: (KJM 02/21/06) Figure out how to treat 0xFF as -1 rather than 255.
                int minorChannel = segment.Array[segment.Offset + (int)StationBytePositions.MinorChannel];
                if (255 == minorChannel)
                {
                    minorChannel = -1;
                }
                s.MinorChannel = minorChannel;

                // TODO: (KJM 02/21/06) Figure out a way of actually reading in the name without dying on channels without names.
                //s.Name = System.Text.Encoding.ASCII.GetString(segment.Array, segment.Offset + 16, 5);

                ret.Add(s);
            }

            return ret;
        }
        public IotHubRepository(IConfigurationProvider configProvider)
        {
            // Temporary code to bypass https cert validation till DNS on IotHub is configured
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

            _iotHubConnectionString = configProvider.GetConfigurationSettingValue("iotHub.ConnectionString");
            _deviceManager = RegistryManager.CreateFromConnectionString(_iotHubConnectionString);
        }
        public static void Main()
        {
            BTV btv = new BTV();
            List<Recording> recordings = btv.getRecordings();

            // First clear out all the previous recordings, then schedule all the current recordings.
            RegistryManager registry = new RegistryManager();
            registry.clearRecordings();

            foreach (Recording r in recordings)
            {
                registry.scheduleRecording(r);
            }
        }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            try
            {
                if ((args.Length == 0) || string.IsNullOrEmpty(args[0]) || args[0].Equals("localhost", StringComparison.OrdinalIgnoreCase))
                {
                    m_applicationName = Utils.GetHostName();
                }
                else
                {
                    m_applicationName = args[0];
                }

                Trace("Publisher is starting up...");
                ModuleConfiguration moduleConfiguration = new ModuleConfiguration(m_applicationName);
                m_configuration = moduleConfiguration.Configuration;
                m_configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);

                // start our server interface
                try
                {
                    Trace("Starting server on endpoint " + m_configuration.ServerConfiguration.BaseAddresses[0].ToString() + "...");
                    m_server.Start(m_configuration);
                    Trace("Server started.");
                }
                catch (Exception ex)
                {
                    Trace("Starting server failed with: " + ex.Message);
                }

                // check if we also received an owner connection string
                string ownerConnectionString = string.Empty;
                if ((args.Length > 1) && !string.IsNullOrEmpty(args[1]))
                {
                    ownerConnectionString = args[1];
                }
                else
                {
                    Trace("IoT Hub owner connection string not passed as argument.");

                    // check if we have an environment variable to register ourselves with IoT Hub
                    if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("_HUB_CS")))
                    {
                        ownerConnectionString = Environment.GetEnvironmentVariable("_HUB_CS");
                    }
                }

                // register ourselves with IoT Hub
                if (ownerConnectionString != string.Empty)
                {
                    Trace("Attemping to register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    RegistryManager manager = RegistryManager.CreateFromConnectionString(ownerConnectionString);

                    // remove any existing device
                    Device existingDevice = manager.GetDeviceAsync(m_applicationName).Result;
                    if (existingDevice != null)
                    {
                        manager.RemoveDeviceAsync(m_applicationName).Wait();
                    }

                    Device newDevice = manager.AddDeviceAsync(new Device(m_applicationName)).Result;
                    if (newDevice != null)
                    {
                        string hostname = ownerConnectionString.Substring(0, ownerConnectionString.IndexOf(";"));
                        string deviceConnectionString = hostname + ";DeviceId=" + m_applicationName + ";SharedAccessKey=" + newDevice.Authentication.SymmetricKey.PrimaryKey;
                        SecureIoTHubToken.Write(m_applicationName, deviceConnectionString);
                    }
                    else
                    {
                        Trace("Could not register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    }
                }
                else
                {
                    Trace("IoT Hub owner connection string not found, registration with IoT Hub abandoned.");
                }

                // try to read connection string from secure store and open IoTHub client
                Trace("Attemping to read connection string from secure store with certificate name: " + m_applicationName);
                string connectionString = SecureIoTHubToken.Read(m_applicationName);
                if (!string.IsNullOrEmpty(connectionString))
                {
                    Trace("Attemping to configure publisher with connection string: " + connectionString);
                    m_deviceClient             = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
                    m_deviceClient.RetryPolicy = RetryPolicyType.Exponential_Backoff_With_Jitter;
                    m_deviceClient.OpenAsync().Wait();
                }
                else
                {
                    Trace("Device connection string not found in secure store.");
                }

                // get a list of persisted endpoint URLs and create a session for each.
                try
                {
                    // check if we have an env variable specifying the published nodes path, otherwise use current directory
                    string publishedNodesFilePath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "publishednodes.json";
                    if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("_GW_PNFP")))
                    {
                        publishedNodesFilePath = Environment.GetEnvironmentVariable("_GW_PNFP");
                    }

                    Trace("Attemping to load nodes file from: " + publishedNodesFilePath);
                    m_nodesLookups = JsonConvert.DeserializeObject <PublishedNodesCollection>(File.ReadAllText(publishedNodesFilePath));
                    Trace("Loaded " + m_nodesLookups.Count.ToString() + " nodes.");
                }
                catch (Exception ex)
                {
                    Trace("Nodes file loading failed with: " + ex.Message);
                }

                foreach (NodeLookup nodeLookup in m_nodesLookups)
                {
                    if (!m_endpointUrls.Contains(nodeLookup.EndPointURL))
                    {
                        m_endpointUrls.Add(nodeLookup.EndPointURL);
                    }
                }

                // connect to the other servers
                Trace("Attemping to connect to servers...");
                try
                {
                    List <Task> connectionAttempts = new List <Task>();
                    foreach (Uri endpointUrl in m_endpointUrls)
                    {
                        Trace("Connecting to server: " + endpointUrl);
                        connectionAttempts.Add(EndpointConnect(endpointUrl));
                    }

                    // Wait for all sessions to be connected
                    Task.WaitAll(connectionAttempts.ToArray());
                }
                catch (Exception ex)
                {
                    Trace("Exception: " + ex.ToString() + "\r\n" + ex.InnerException != null ? ex.InnerException.ToString() : null);
                }

                // subscribe to preconfigured nodes
                Trace("Attemping to subscribe to published nodes...");
                if (m_nodesLookups != null)
                {
                    foreach (NodeLookup nodeLookup in m_nodesLookups)
                    {
                        try
                        {
                            CreateMonitoredItem(nodeLookup);
                        }
                        catch (Exception ex)
                        {
                            Trace("Unexpected error publishing node: " + ex.Message + "\r\nIgnoring node: " + nodeLookup.EndPointURL.AbsoluteUri + ", " + nodeLookup.NodeID.ToString());
                        }
                    }
                }


                Task dequeueAndSendTask = null;
                var  tokenSource        = new CancellationTokenSource();
                var  token = tokenSource.Token;

                Trace("Creating task to send OPC UA messages in batches to IoT Hub...");
                try
                {
                    dequeueAndSendTask = Task.Run(() => DeQueueMessagesAsync(token), token);
                }
                catch (Exception ex)
                {
                    Trace("Exception: " + ex.ToString());
                }

                Trace("Publisher is running. Press enter to quit.");
                Console.ReadLine();

                foreach (Session session in m_sessions)
                {
                    session.Close();
                }

                //Send cancellation token and wait for last IoT Hub message to be sent.
                try
                {
                    tokenSource.Cancel();
                    dequeueAndSendTask.Wait();
                }
                catch (Exception ex)
                {
                    Trace("Exception: " + ex.ToString());
                }

                if (m_deviceClient != null)
                {
                    m_deviceClient.CloseAsync().Wait();
                }
            }
            catch (Exception e)
            {
                Trace(e, "Unhandled exception in Publisher, exiting!");
            }
        }
Exemplo n.º 5
0
        public void Init()
        {
            string hubConnString = "HostName=lefitche-hub-3.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=wyT/feMmLKDj8wnWxLCHkQERmOUBWaeuLMDLDjAILug=";

            registryManager = RegistryManager.CreateFromConnectionString(hubConnString);
        }
Exemplo n.º 6
0
        public int RunCommand(CKAN.KSP ksp, object raw_options)
        {
            ShowOptions options = (ShowOptions)raw_options;

            if (options.Modname == null)
            {
                // empty argument
                user.RaiseMessage("show <module> - module name argument missing, perhaps you forgot it?");
                return(Exit.BADOPT);
            }

            // Check installed modules for an exact match.
            var registry = RegistryManager.Instance(ksp).registry;
            var installedModuleToShow = registry.InstalledModule(options.Modname);

            if (installedModuleToShow != null)
            {
                // Show the installed module.
                return(ShowMod(installedModuleToShow));
            }

            // Module was not installed, look for an exact match in the available modules,
            // either by "name" (the user-friendly display name) or by identifier
            CkanModule moduleToShow = registry
                                      .Available(ksp.Version())
                                      .SingleOrDefault(
                mod => mod.name == options.Modname ||
                mod.identifier == options.Modname
                );

            if (moduleToShow == null)
            {
                // No exact match found. Try to look for a close match for this KSP version.
                user.RaiseMessage("{0} not found or installed.", options.Modname);
                user.RaiseMessage("Looking for close matches in available mods for KSP {0}.", ksp.Version());

                Search search  = new Search(user);
                var    matches = search.PerformSearch(ksp, options.Modname);

                // Display the results of the search.
                if (!matches.Any())
                {
                    // No matches found.
                    user.RaiseMessage("No close matches found.");
                    return(Exit.BADOPT);
                }
                else if (matches.Count() == 1)
                {
                    // If there is only 1 match, display it.
                    user.RaiseMessage("Found 1 close match: {0}", matches[0].name);
                    user.RaiseMessage("");

                    moduleToShow = matches[0];
                }
                else
                {
                    // Display the found close matches.
                    string[] strings_matches = new string[matches.Count];

                    for (int i = 0; i < matches.Count; i++)
                    {
                        strings_matches[i] = matches[i].name;
                    }

                    int selection = user.RaiseSelectionDialog("Close matches", strings_matches);

                    if (selection < 0)
                    {
                        return(Exit.BADOPT);
                    }

                    // Mark the selection as the one to show.
                    moduleToShow = matches[selection];
                }
            }

            return(ShowMod(moduleToShow));
        }
Exemplo n.º 7
0
 public EncryptedFilesList()
 {
     InitializeComponent();
     rm = new RegistryManager();
 }
Exemplo n.º 8
0
        private async Task DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base(
            Client.TransportType protocol, Func <RegistryManager, string, Task> registryManagerOperation)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix + $"_{Guid.NewGuid()}").ConfigureAwait(false);

            string deviceConnectionString = testDevice.ConnectionString;

            var    config   = new Configuration.IoTHub.DeviceConnectionStringParser(deviceConnectionString);
            string deviceId = config.DeviceID;

            ConnectionStatus?            status             = null;
            ConnectionStatusChangeReason?statusChangeReason = null;
            int deviceDisabledReceivedCount = 0;

            using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, protocol))
            {
                ConnectionStatusChangesHandler statusChangeHandler = (s, r) =>
                {
                    if (r == ConnectionStatusChangeReason.Device_Disabled)
                    {
                        status             = s;
                        statusChangeReason = r;
                        deviceDisabledReceivedCount++;
                    }
                };

                deviceClient.SetConnectionStatusChangesHandler(statusChangeHandler);
                _log.WriteLine($"Created {nameof(DeviceClient)} ID={TestLogging.IdOf(deviceClient)}");

                Console.WriteLine("DeviceClient OpenAsync.");
                await deviceClient.OpenAsync().ConfigureAwait(false);

                // Receiving the module twin should succeed right now.
                Console.WriteLine("ModuleClient GetTwinAsync.");
                var twin = await deviceClient.GetTwinAsync().ConfigureAwait(false);

                Assert.IsNotNull(twin);

                // Delete/disable the device in IoT Hub. This should trigger the ConnectionStatusChangesHandler.
                using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
                {
                    await registryManagerOperation(registryManager, deviceId).ConfigureAwait(false);
                }

                // Artificial sleep waiting for the connection status change handler to get triggered.
                int sleepCount = 50;
                for (int i = 0; i < sleepCount; i++)
                {
                    await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);

                    if (deviceDisabledReceivedCount == 1)
                    {
                        break;
                    }
                }

                Assert.AreEqual(1, deviceDisabledReceivedCount);
                Assert.AreEqual(ConnectionStatus.Disconnected, status);
                Assert.AreEqual(ConnectionStatusChangeReason.Device_Disabled, statusChangeReason);
            }
        }
Exemplo n.º 9
0
 public DesiredPropertyUpdater(RegistryManager registryManager, ITwinTestResultHandler resultHandler, TwinState twinState)
 {
     this.registryManager = registryManager;
     this.resultHandler   = resultHandler;
     this.twinState       = twinState;
 }
Exemplo n.º 10
0
        public int RunCommand(CKAN.KSP ksp, object raw_options)
        {
            ReplaceOptions options = (ReplaceOptions)raw_options;

            if (options.ckan_file != null)
            {
                options.modules.Add(MainClass.LoadCkanFromFile(ksp, options.ckan_file).identifier);
            }

            if (options.modules.Count == 0 && !options.replace_all)
            {
                // What? No mods specified?
                User.RaiseMessage("Usage: ckan replace Mod [Mod2, ...]");
                User.RaiseMessage("  or   ckan replace --all");
                return(Exit.BADOPT);
            }

            // Prepare options. Can these all be done in the new() somehow?
            var replace_ops = new RelationshipResolverOptions
            {
                with_all_suggests  = options.with_all_suggests,
                with_suggests      = options.with_suggests,
                with_recommends    = !options.no_recommends,
                allow_incompatible = options.allow_incompatible
            };

            var registry   = RegistryManager.Instance(ksp).registry;
            var to_replace = new List <ModuleReplacement>();

            if (options.replace_all)
            {
                log.Debug("Running Replace all");
                var installed = new Dictionary <string, ModuleVersion>(registry.Installed());

                foreach (KeyValuePair <string, ModuleVersion> mod in installed)
                {
                    ModuleVersion current_version = mod.Value;

                    if ((current_version is ProvidesModuleVersion) || (current_version is UnmanagedModuleVersion))
                    {
                        continue;
                    }
                    else
                    {
                        try
                        {
                            log.DebugFormat("Testing {0} {1} for possible replacement", mod.Key, mod.Value);
                            // Check if replacement is available

                            ModuleReplacement replacement = registry.GetReplacement(mod.Key, ksp.VersionCriteria());
                            if (replacement != null)
                            {
                                // Replaceable
                                log.InfoFormat("Replacement {0} {1} found for {2} {3}",
                                               replacement.ReplaceWith.identifier, replacement.ReplaceWith.version,
                                               replacement.ToReplace.identifier, replacement.ToReplace.version);
                                to_replace.Add(replacement);
                            }
                        }
                        catch (ModuleNotFoundKraken)
                        {
                            log.InfoFormat("{0} is installed, but it or its replacement is not in the registry",
                                           mod.Key);
                        }
                    }
                }
            }
            else
            {
                foreach (string mod in options.modules)
                {
                    try
                    {
                        log.DebugFormat("Checking that {0} is installed", mod);
                        CkanModule modToReplace = registry.GetInstalledVersion(mod);
                        if (modToReplace != null)
                        {
                            log.DebugFormat("Testing {0} {1} for possible replacement", modToReplace.identifier, modToReplace.version);
                            try
                            {
                                // Check if replacement is available
                                ModuleReplacement replacement = registry.GetReplacement(modToReplace.identifier, ksp.VersionCriteria());
                                if (replacement != null)
                                {
                                    // Replaceable
                                    log.InfoFormat("Replacement {0} {1} found for {2} {3}",
                                                   replacement.ReplaceWith.identifier, replacement.ReplaceWith.version,
                                                   replacement.ToReplace.identifier, replacement.ToReplace.version);
                                    to_replace.Add(replacement);
                                }
                                if (modToReplace.replaced_by != null)
                                {
                                    log.InfoFormat("Attempt to replace {0} failed, replacement {1} is not compatible",
                                                   mod, modToReplace.replaced_by.name);
                                }
                                else
                                {
                                    log.InfoFormat("Mod {0} has no replacement defined for the current version {1}",
                                                   modToReplace.identifier, modToReplace.version);
                                }
                            }
                            catch (ModuleNotFoundKraken)
                            {
                                log.InfoFormat("{0} is installed, but its replacement {1} is not in the registry",
                                               mod, modToReplace.replaced_by.name);
                            }
                        }
                    }
                    catch (ModuleNotFoundKraken kraken)
                    {
                        User.RaiseMessage("Module {0} not found", kraken.module);
                    }
                }
            }
            if (to_replace.Count() != 0)
            {
                User.RaiseMessage("\r\nReplacing modules...\r\n");
                foreach (ModuleReplacement r in to_replace)
                {
                    User.RaiseMessage("Replacement {0} {1} found for {2} {3}",
                                      r.ReplaceWith.identifier, r.ReplaceWith.version,
                                      r.ToReplace.identifier, r.ToReplace.version);
                }

                bool ok = User.RaiseYesNoDialog("\r\nContinue?");

                if (!ok)
                {
                    User.RaiseMessage("Replacements canceled at user request.");
                    return(Exit.ERROR);
                }

                // TODO: These instances all need to go.
                try
                {
                    ModuleInstaller.GetInstance(ksp, manager.Cache, User).Replace(to_replace, replace_ops, new NetAsyncModulesDownloader(User));
                    User.RaiseMessage("\r\nDone!\r\n");
                }
                catch (DependencyNotSatisfiedKraken ex)
                {
                    User.RaiseMessage("Dependencies not satisfied for replacement, {0} requires {1} {2} but it is not listed in the index, or not available for your version of KSP.", ex.parent, ex.module, ex.version);
                }
            }
            else
            {
                User.RaiseMessage("No replacements found.");
                return(Exit.OK);
            }

            return(Exit.OK);
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter IoT Hub connection string: ");
            _iotHubConnectionString = Console.ReadLine();

            _registryManager = RegistryManager.CreateFromConnectionString(_iotHubConnectionString);

            Task.Run(
                async() =>
            {
                while (true)
                {
                    try
                    {
                        Console.WriteLine();
                        Console.WriteLine("Commands:");
                        Console.WriteLine("1: Register random devices");
                        Console.WriteLine("2: Send data from all devices");
                        Console.WriteLine("3: Remove all devices");
                        Console.WriteLine("4: Exit");

                        string command = Console.ReadLine();

                        switch (command)
                        {
                        case "1":
                            Console.WriteLine("Number of devices?");
                            int num = Int32.Parse(Console.ReadLine());
                            await AddRandomDevicesAsync(num);
                            break;

                        case "2":
                            Console.WriteLine("Number of messages?");
                            int nbMessages = Int32.Parse(Console.ReadLine());
                            await SendFromAllDevicesAsync(nbMessages);
                            break;

                        case "3":
                            Console.WriteLine("Do you confirm? (y/n)");
                            var confirm = Console.ReadLine();
                            if (confirm != null && confirm.ToLower().Equals("y"))
                            {
                                var devices = await _registryManager.GetDevicesAsync(Int32.MaxValue);
                                //var query = registryManager.CreateQuery("select * from devices");
                                //while (query.HasMoreResults)
                                //{
                                //    var page = await query.GetNextAsTwinAsync();
                                //    foreach (var twin in page)
                                //    {
                                //        // do work on twin object
                                //        devices.Append(twin.)
                                //    }
                                //}
                                foreach (var device in devices)
                                {
                                    await _registryManager.RemoveDeviceAsync(device.Id);
                                }
                            }
                            break;

                        case "4":
                            return;

                        default:
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("An error occured: {0}", ex.Message);
                    }
                }
            }
                ).GetAwaiter().GetResult();
        }
Exemplo n.º 12
0
 static DevicesController()
 {
     _registryManager = RegistryManager.CreateFromConnectionString(Settings.Instance.IotHubConnectionString);
 }
Exemplo n.º 13
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public MainWindow()
        {
            // Initialize the UI
            InitializeComponent();

            // Initialize timer for handling the state of the save button
            timer          = new Timer();
            timer.Tick    += new EventHandler(resetSaveButtonText);
            timer.Interval = 500;

            // Make window unresizable
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MaximizeBox     = false;

            // Get the application settings from the settings file.
            this.m_Settings = SettingsManager.read();
            if (this.m_Settings.IsValid)
            {
                // Check that the Imaris version stored in the file exists in
                // the registry. Otherwise inform the admin.
                RegistryManager manager = new RegistryManager(this.m_Settings.ImarisVersion);
                if (!manager.ImarisKeyExists())
                {
                    // Inform the user
                    MessageBox.Show(
                        "The Imaris version stored in the settings file does not have " +
                        "the corresponding registry entries. This probably means that " +
                        "the settings file is obsolete.\n\n" +
                        "It is highly recommended to choose current Imaris executable " +
                        "to manage and, if needed, reconfigure it.",
                        "Warning",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }


                // Display the Imaris path on the button
                buttonImarisPath.Text = this.m_Settings.ImarisPath;

                // Fill in the list of products
                checkedListBoxProducts.Items.Clear();
                foreach (String productName in this.m_Settings.ProductsWithEnabledState.Keys)
                {
                    bool state;
                    if (this.m_Settings.ProductsWithEnabledState.ContainsKey(productName))
                    {
                        if (!this.m_Settings.ProductsWithEnabledState.TryGetValue(productName, out state))
                        {
                            state = true;
                        }
                    }
                    else
                    {
                        state = true;
                    }

                    // Add the product with the state read from the application settings
                    checkedListBoxProducts.Items.Add(productName, state);
                }

                // Now set all other settings
                // TODO: Add all necessary checks

                // Texture cache
                if (this.m_Settings.TextureCache == -1)
                {
                    numericTextureCache.Text = "";
                }
                else
                {
                    numericTextureCache.Value = this.m_Settings.TextureCache;
                }

                // Data cache
                if (this.m_Settings.DataCache == -1)
                {
                    numericDataCache.Text = "";
                }
                else
                {
                    numericDataCache.Value = this.m_Settings.DataCache;
                }

                // Data cache file paths
                if (!this.m_Settings.DataBlockCachingFilePath.Equals(""))
                {
                    String[] dataBlockCachingFilePathArray = this.m_Settings.DataBlockCachingFilePath.Split(';');
                    listCLFileCachePaths.Items.Clear();
                    foreach (String d in dataBlockCachingFilePathArray)
                    {
                        if (!d.Equals(""))
                        {
                            listCLFileCachePaths.Items.Add(d);
                        }
                    }
                }

                // XT folder paths
                if (!this.m_Settings.XTFolderPath.Equals(""))
                {
                    String[] xtFolderPathArray = this.m_Settings.XTFolderPath.Split(';');
                    listCTXTPaths.Items.Clear();
                    foreach (String x in xtFolderPathArray)
                    {
                        if (!x.Equals(""))
                        {
                            listCTXTPaths.Items.Add(x);
                        }
                    }
                }

                // Python path
                if (!this.m_Settings.PythonPath.Equals(""))
                {
                    buttonCTAddPythonPath.Text = this.m_Settings.PythonPath;
                }

                // Fiji path
                if (!this.m_Settings.FijiPath.Equals(""))
                {
                    buttonCTAddFijiPath.Text = this.m_Settings.FijiPath;
                }

                // Enable save button
                this.buttonSave.Enabled = true;
            }
        }
Exemplo n.º 14
0
        public void InstallAndSortByCompat_WithAnyCompat_NoCrash()
        {
            /*
             * // An exception would be thrown at the bottom of this.
             * var main = new Main(null, new GUIUser(), false);
             * main.Manager = _manager;
             * // First sort by name
             * main.configuration.SortByColumnIndex = 2;
             * // Now sort by version
             * main.configuration.SortByColumnIndex = 6;
             * main.MarkModForInstall("kOS");
             *
             * // Make sure we have one requested change
             * var changeList = main.mainModList.ComputeUserChangeSet()
             *  .Select((change) => change.Mod.ToCkanModule()).ToList();
             *
             * // Do the install
             * new ModuleInstaller(_instance.KSP, main.currentUser).InstallList(
             *  changeList,
             *  new RelationshipResolverOptions(),
             *  new NetAsyncModulesDownloader(main.currentUser)
             * );
             */

            // Arrange

            DisposableKSP       instance        = new DisposableKSP();
            RegistryManager     registryManager = RegistryManager.Instance(instance.KSP);
            Registry            registry        = Registry.Empty();
            FakeConfiguration   config          = new FakeConfiguration(instance.KSP, instance.KSP.Name);
            GameInstanceManager manager         = new GameInstanceManager(new NullUser(), config);
            // A module with a ksp_version of "any" to repro our issue
            CkanModule   anyVersionModule = TestData.DogeCoinFlag_101_module();
            ModList      modList          = new ModList(null);
            DataGridView listGui          = new DataGridView();

            CKAN.ModuleInstaller      installer  = new CKAN.ModuleInstaller(instance.KSP, manager.Cache, manager.User);
            NetAsyncModulesDownloader downloader = new NetAsyncModulesDownloader(manager.User, manager.Cache);

            // Act

            // Install module and set it as pre-installed
            manager.Cache.Store(TestData.DogeCoinFlag_101_module(), TestData.DogeCoinFlagZip());
            registry.RegisterModule(anyVersionModule, new string[] { }, instance.KSP, false);
            registry.AddAvailable(anyVersionModule);

            HashSet <string> possibleConfigOnlyDirs = null;

            installer.InstallList(
                new List <CkanModule> {
                anyVersionModule
            },
                new RelationshipResolverOptions(),
                registryManager,
                ref possibleConfigOnlyDirs,
                downloader
                );

            // This module is not for "any" version,
            // to provide another to sort against
            registry.AddAvailable(TestData.kOS_014_module());

            // TODO: Refactor the column header code to allow mocking of the GUI without creating columns
            const int numCheckboxCols = 4;
            const int numTextCols     = 10;

            listGui.Columns.AddRange(
                Enumerable.Range(1, numCheckboxCols)
                .Select(i => (DataGridViewColumn) new DataGridViewCheckBoxColumn())
                .Concat(Enumerable.Range(1, numTextCols)
                        .Select(i => new DataGridViewTextBoxColumn()))
                .ToArray());

            // Assert (and Act a bit more)

            Assert.IsNotNull(instance.KSP);
            Assert.IsNotNull(manager);
            Assert.IsNotNull(modList);

            var modules = registry.available_modules
                          .Select(mod => new GUIMod(mod.Value.Latest(), registry, instance.KSP.VersionCriteria()))
                          .ToList();

            listGui.Rows.AddRange(modList.ConstructModList(modules, null).ToArray());
            // The header row adds one to the count
            Assert.AreEqual(modules.Count + 1, listGui.Rows.Count);

            // Sort by game compatibility, this is the fuse-lighting
            listGui.Sort(listGui.Columns[8], ListSortDirection.Descending);

            // Mark the mod for install, after completion we will get an exception
            var otherModule = modules.First(mod => mod.Identifier.Contains("kOS"));

            otherModule.IsInstallChecked = true;

            Assert.IsTrue(otherModule.IsInstallChecked);
            Assert.IsFalse(otherModule.IsInstalled);

            Assert.DoesNotThrow(() =>
            {
                // Install the "other" module
                installer.InstallList(
                    modList.ComputeUserChangeSet(null).Select(change => change.Mod).ToList(),
                    new RelationshipResolverOptions(),
                    registryManager,
                    ref possibleConfigOnlyDirs,
                    downloader
                    );

                // Now we need to sort
                // Make sure refreshing the GUI state does not throw a NullReferenceException
                listGui.Refresh();
            });

            instance.Dispose();
            manager.Dispose();
            config.Dispose();
        }
 public void setUp()
 {
     registry = new RegistryManager();
 }
Exemplo n.º 16
0
 public DeviceTwinRepository(string iotHubConnectionString)
 {
     _iotHubConnectionString = iotHubConnectionString;
     _registryManager        = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
     _jobClient = JobClient.CreateFromConnectionString(iotHubConnectionString);
 }
Exemplo n.º 17
0
 public IoTSetDeviceTwinAsyncCollector(RegistryManager registryManager, IoTSetDeviceTwinAttribute attribute)
 {
     // create client;
     this.registryManager = registryManager;
 }
Exemplo n.º 18
0
        /// <summary>
        /// Upgrade an installed module
        /// </summary>
        /// <param name="ksp">Game instance from which to remove</param>
        /// <param name="raw_options">Command line options object</param>
        /// <returns>
        /// Exit code for shell environment
        /// </returns>
        public int RunCommand(CKAN.KSP ksp, object raw_options)
        {
            UpgradeOptions options = (UpgradeOptions)raw_options;

            if (options.ckan_file != null)
            {
                options.modules.Add(MainClass.LoadCkanFromFile(ksp, options.ckan_file).identifier);
            }

            if (options.modules.Count == 0 && !options.upgrade_all)
            {
                // What? No files specified?
                User.RaiseMessage("Usage: ckan upgrade Mod [Mod2, ...]");
                User.RaiseMessage("  or   ckan upgrade --all");
                if (AutoUpdate.CanUpdate)
                {
                    User.RaiseMessage("  or   ckan upgrade ckan");
                }
                return(Exit.BADOPT);
            }

            if (!options.upgrade_all && options.modules[0] == "ckan" && AutoUpdate.CanUpdate)
            {
                User.RaiseMessage("Querying the latest CKAN version");
                AutoUpdate.Instance.FetchLatestReleaseInfo();
                var latestVersion  = AutoUpdate.Instance.latestUpdate.Version;
                var currentVersion = new ModuleVersion(Meta.GetVersion(VersionFormat.Short));

                if (latestVersion.IsGreaterThan(currentVersion))
                {
                    User.RaiseMessage("New CKAN version available - " + latestVersion);
                    var releaseNotes = AutoUpdate.Instance.latestUpdate.ReleaseNotes;
                    User.RaiseMessage(releaseNotes);
                    User.RaiseMessage("\r\n");

                    if (User.RaiseYesNoDialog("Proceed with install?"))
                    {
                        User.RaiseMessage("Upgrading CKAN, please wait..");
                        AutoUpdate.Instance.StartUpdateProcess(false);
                    }
                }
                else
                {
                    User.RaiseMessage("You already have the latest version.");
                }

                return(Exit.OK);
            }

            User.RaiseMessage("\r\nUpgrading modules...\r\n");

            try
            {
                HashSet <string> possibleConfigOnlyDirs = null;
                var regMgr   = RegistryManager.Instance(ksp);
                var registry = regMgr.registry;
                if (options.upgrade_all)
                {
                    var installed  = new Dictionary <string, ModuleVersion>(registry.Installed());
                    var to_upgrade = new List <CkanModule>();

                    foreach (KeyValuePair <string, ModuleVersion> mod in installed)
                    {
                        ModuleVersion current_version = mod.Value;

                        if ((current_version is ProvidesModuleVersion) || (current_version is UnmanagedModuleVersion))
                        {
                            continue;
                        }
                        else
                        {
                            try
                            {
                                // Check if upgrades are available
                                var latest = registry.LatestAvailable(mod.Key, ksp.VersionCriteria());

                                // This may be an unindexed mod. If so,
                                // skip rather than crash. See KSP-CKAN/CKAN#841.
                                if (latest == null || latest.IsDLC)
                                {
                                    continue;
                                }

                                if (latest.version.IsGreaterThan(mod.Value))
                                {
                                    // Upgradable
                                    log.InfoFormat("New version {0} found for {1}",
                                                   latest.version, latest.identifier);
                                    to_upgrade.Add(latest);
                                }
                            }
                            catch (ModuleNotFoundKraken)
                            {
                                log.InfoFormat("{0} is installed, but no longer in the registry",
                                               mod.Key);
                            }
                        }
                    }

                    ModuleInstaller.GetInstance(ksp, manager.Cache, User).Upgrade(to_upgrade, new NetAsyncModulesDownloader(User, manager.Cache), ref possibleConfigOnlyDirs, regMgr);
                }
                else
                {
                    // TODO: These instances all need to go.
                    Search.AdjustModulesCase(ksp, options.modules);
                    ModuleInstaller.GetInstance(ksp, manager.Cache, User).Upgrade(options.modules, new NetAsyncModulesDownloader(User, manager.Cache), ref possibleConfigOnlyDirs, regMgr);
                }
            }
            catch (ModuleNotFoundKraken kraken)
            {
                User.RaiseMessage("Module {0} not found", kraken.module);
                return(Exit.ERROR);
            }
            catch (InconsistentKraken kraken)
            {
                User.RaiseMessage(kraken.ToString());
                return(Exit.ERROR);
            }
            catch (ModuleIsDLCKraken kraken)
            {
                User.RaiseMessage($"CKAN can't upgrade expansion '{kraken.module.name}' for you.");
                var res           = kraken?.module?.resources;
                var storePagesMsg = new Uri[] { res?.store, res?.steamstore }
                .Where(u => u != null)
                .Aggregate("", (a, b) => $"{a}\r\n- {b}");
                if (!string.IsNullOrEmpty(storePagesMsg))
                {
                    User.RaiseMessage($"To upgrade this expansion, download any updates from the store page from which you purchased it:\r\n{storePagesMsg}");
                }
                return(Exit.ERROR);
            }
            User.RaiseMessage("\r\nDone!\r\n");

            return(Exit.OK);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initialize the Screen
        /// </summary>
        /// <param name="mgr">Game instance manager containing the instances</param>
        /// <param name="k">Instance to edit</param>
        public GameInstanceEditScreen(GameInstanceManager mgr, GameInstance k)
            : base(mgr, k.Name, k.GameDir())
        {
            ksp = k;
            try {
                // If we can't parse the registry, just leave the repo list blank
                registry = RegistryManager.Instance(ksp).registry;
            } catch { }

            // Show the repositories if we can
            if (registry != null)
            {
                // Need to edit a copy of the list so it doesn't save on cancel
                repoEditList = new SortedDictionary <string, Repository>();
                foreach (var kvp in registry.Repositories)
                {
                    repoEditList.Add(kvp.Key, new Repository(
                                         kvp.Value.name,
                                         kvp.Value.uri.ToString(),
                                         kvp.Value.priority
                                         ));
                }

                // Also edit copy of the compatible versions
                compatEditList = new List <GameVersion>(ksp.GetCompatibleVersions());

                // I'm not a huge fan of this layout, but I think it's better than just a label
                AddObject(new ConsoleDoubleFrame(
                              1, repoFrameTop, -1, compatFrameBottom, compatFrameTop,
                              () => $"Mod List Sources",
                              () => $"Additional Compatible Versions",
                              th => th.LabelFg
                              ));

                repoList = new ConsoleListBox <Repository>(
                    3, repoListTop, -3, repoListBottom,
                    new List <Repository>(repoEditList.Values),
                    new List <ConsoleListBoxColumn <Repository> >()
                {
                    new ConsoleListBoxColumn <Repository>()
                    {
                        Header   = "Index",
                        Renderer = r => r.priority.ToString(),
                        Width    = 7
                    }, new ConsoleListBoxColumn <Repository>()
                    {
                        Header   = "Name",
                        Renderer = r => r.name,
                        Width    = 16
                    }, new ConsoleListBoxColumn <Repository>()
                    {
                        Header   = "URL",
                        Renderer = r => r.uri.ToString(),
                        Width    = 50
                    }
                },
                    1, 0, ListSortDirection.Ascending
                    );
                AddObject(repoList);
                repoList.AddTip("A", "Add");
                repoList.AddBinding(Keys.A, (object sender, ConsoleTheme theme) => {
                    LaunchSubScreen(theme, new RepoAddScreen(ksp.game, repoEditList));
                    repoList.SetData(new List <Repository>(repoEditList.Values));
                    return(true);
                });
                repoList.AddTip("R", "Remove");
                repoList.AddBinding(Keys.R, (object sender, ConsoleTheme theme) => {
                    int oldPrio = repoList.Selection.priority;
                    repoEditList.Remove(repoList.Selection.name);
                    // Reshuffle the priorities to fill
                    foreach (Repository r in repoEditList.Values)
                    {
                        if (r.priority > oldPrio)
                        {
                            --r.priority;
                        }
                    }
                    repoList.SetData(new List <Repository>(repoEditList.Values));
                    return(true);
                });
                repoList.AddTip("E", "Edit");
                repoList.AddBinding(Keys.E, (object sender, ConsoleTheme theme) => {
                    LaunchSubScreen(theme, new RepoEditScreen(ksp.game, repoEditList, repoList.Selection));
                    repoList.SetData(new List <Repository>(repoEditList.Values));
                    return(true);
                });
                repoList.AddTip("-", "Up");
                repoList.AddBinding(Keys.Minus, (object sender, ConsoleTheme theme) => {
                    if (repoList.Selection.priority > 0)
                    {
                        Repository prev = SortedDictFind(repoEditList,
                                                         r => r.priority == repoList.Selection.priority - 1);
                        if (prev != null)
                        {
                            ++prev.priority;
                        }
                        --repoList.Selection.priority;
                        repoList.SetData(new List <Repository>(repoEditList.Values));
                    }
                    return(true);
                });
                repoList.AddTip("+", "Down");
                repoList.AddBinding(Keys.Plus, (object sender, ConsoleTheme theme) => {
                    Repository next = SortedDictFind(repoEditList,
                                                     r => r.priority == repoList.Selection.priority + 1);
                    if (next != null)
                    {
                        --next.priority;
                    }
                    ++repoList.Selection.priority;
                    repoList.SetData(new List <Repository>(repoEditList.Values));
                    return(true);
                });

                compatList = new ConsoleListBox <GameVersion>(
                    3, compatListTop, -3, compatListBottom,
                    compatEditList,
                    new List <ConsoleListBoxColumn <GameVersion> >()
                {
                    new ConsoleListBoxColumn <GameVersion>()
                    {
                        Header   = "Version",
                        Width    = 10,
                        Renderer = v => v.ToString(),
                        Comparer = (a, b) => a.CompareTo(b)
                    }
                },
                    0, 0, ListSortDirection.Descending
                    );
                AddObject(compatList);

                compatList.AddTip("A", "Add");
                compatList.AddBinding(Keys.A, (object sender, ConsoleTheme theme) => {
                    CompatibleVersionDialog vd = new CompatibleVersionDialog(ksp.game);
                    GameVersion newVersion     = vd.Run(theme);
                    DrawBackground(theme);
                    if (newVersion != null && !compatEditList.Contains(newVersion))
                    {
                        compatEditList.Add(newVersion);
                        compatList.SetData(compatEditList);
                    }
                    return(true);
                });
                compatList.AddTip("R", "Remove", () => compatList.Selection != null);
                compatList.AddBinding(Keys.R, (object sender, ConsoleTheme theme) => {
                    compatEditList.Remove(compatList.Selection);
                    compatList.SetData(compatEditList);
                    return(true);
                });
            }
            else
            {
                // Notify the user that the registry doesn't parse
                AddObject(new ConsoleLabel(
                              1, repoFrameTop, -1,
                              () => $"Failed to extract mod list sources from {ksp.Name}."
                              ));
            }
        }
Exemplo n.º 20
0
        static async Task <int> Main(string[] args)
        {
            var connectionString = Environment.GetEnvironmentVariable(IotHubConnectionStringEnvVar);

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                Console.Error.WriteLine($"Environment variable for '{IotHubConnectionStringEnvVar}' is not defined");
                return(-1);
            }

            var devicePrefix = Environment.GetEnvironmentVariable(DevicePrefixEnvVar);

            if (string.IsNullOrWhiteSpace(devicePrefix))
            {
                devicePrefix = "sim";
            }

            if (!int.TryParse(Environment.GetEnvironmentVariable(DeviceCountEnvVar), out var deviceCount) || deviceCount < 1)
            {
                deviceCount = 1;
            }

            if (!int.TryParse(Environment.GetEnvironmentVariable(DeviceIndexEnvVar), out var deviceIndex) || deviceIndex < 0)
            {
                deviceIndex = 1;
            }

            bool isCreateOperation = true;

            if (string.Equals(Environment.GetEnvironmentVariable(OperationNameEnvVar), DeleteOperationNameEnvVar, StringComparison.OrdinalIgnoreCase))
            {
                var isDeleteConfirmed = string.Equals(Environment.GetEnvironmentVariable(DeleteConfirmationEnvVar), DeleteConfirmationResponseEnvVar, StringComparison.OrdinalIgnoreCase);
                if (!isDeleteConfirmed)
                {
                    Console.WriteLine($"Delete operations must be confirmed with an additional environment variable {DeleteConfirmationEnvVar}={DeleteConfirmationResponseEnvVar}");
                    return(-1);
                }

                isCreateOperation = false;
            }

            RegistryManager registryManager = null;

            try
            {
                registryManager = RegistryManager.CreateFromConnectionString(connectionString);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Failed connecting to IoT Hub registry, check the connection string value\n" + ex.ToString());
                return(1);
            }

            try
            {
                await registryManager.OpenAsync();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Failed connecting to IoT Hub registry.\n" + ex.ToString());
                return(1);
            }

            var deviceIdCollection = Enumerable.Range(deviceIndex, deviceCount)
                                     .Select(n => $"{devicePrefix}{n.ToString("000000")}");

            var registryManagerTasks = new List <Task>();

            var stats = new DeviceProvisionStats();

            if (isCreateOperation)
            {
                Console.WriteLine($"Starting device provisioning");
            }
            else
            {
                Console.WriteLine($"Starting device deletion");
            }

            var timer = Stopwatch.StartNew();

            foreach (var partition in Partitioner.Create(deviceIdCollection).GetPartitions(ParallelizationLevel))
            {
                if (isCreateOperation)
                {
                    registryManagerTasks.Add(Task.Run(() => CreateDevicesAsync(partition, registryManager, stats)));
                }
                else
                {
                    registryManagerTasks.Add(Task.Run(() => DeleteDevicesAsync(partition, registryManager, stats)));
                }
            }

            try
            {
                await Task.WhenAll(registryManagerTasks);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }

            timer.Stop();
            Console.WriteLine($"Finished device provisioning");
            Console.WriteLine($"Device count = {deviceCount}");
            Console.WriteLine($"Total devices created = {stats.TotalCreated}");
            Console.WriteLine($"Total devices deleted = {stats.TotalDeleted}");
            Console.WriteLine($"Total errors = {stats.TotalErrors}");
            Console.WriteLine($"Time = {timer.ElapsedMilliseconds}ms");

            return(0);
        }
Exemplo n.º 21
0
 public DeviceManager(IConfiguration config)
 {
     _serviceClient   = ServiceClient.CreateFromConnectionString(config["Server:ServiceConnectionString"]);
     _registryManager = RegistryManager.CreateFromConnectionString(config["Server:RegistryConnectionString"]);
 }
Exemplo n.º 22
0
        public static async Task <TestModule> CreateAndConnect(RegistryManager rm, string hostName, string deviceId, string moduleId, ITransportSettings[] transportSettings)
        {
            string connStr = await RegistryManagerHelper.GetOrCreateModule(rm, hostName, deviceId, moduleId);

            return(await CreateAndConnect(connStr, transportSettings));
        }
Exemplo n.º 23
0
 public AzureIoTHub(string connectionString)
 {
     registryManager = RegistryManager.CreateFromConnectionString(connectionString);
     Name            = connectionString.Substring(connectionString.IndexOf('=') + 1);
     Name            = Name.Substring(0, Name.IndexOf("."));
 }
        public static async System.Threading.Tasks.Task <HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext context)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();
            string          connectionString       = config.GetConnectionString("IoTHubConnectionString");
            string          deviceConfigurationUrl = Environment.GetEnvironmentVariable("DEVICE_CONFIG_LOCATION");
            RegistryManager manager = RegistryManager.CreateFromConnectionString(connectionString);
            // parse query parameter
            var    queryStrings       = req.GetQueryParameterDictionary();
            string deviceName         = "";
            string publishingUserName = "";
            string publishingPassword = "";
            string region             = "";
            string resetPin           = "";

            queryStrings.TryGetValue("deviceName", out deviceName);
            queryStrings.TryGetValue("publishingUserName", out publishingUserName);
            queryStrings.TryGetValue("publishingPassword", out publishingPassword);
            queryStrings.TryGetValue("region", out region);
            queryStrings.TryGetValue("resetPin", out resetPin);


            //Get function facade key
            var    base64Auth = Convert.ToBase64String(Encoding.Default.GetBytes($"{publishingUserName}:{publishingPassword}"));
            var    apiUrl     = new Uri($"https://{Environment.GetEnvironmentVariable("WEBSITE_CONTENTSHARE")}.scm.azurewebsites.net/api");
            var    siteUrl    = new Uri($"https://{Environment.GetEnvironmentVariable("WEBSITE_CONTENTSHARE")}.azurewebsites.net");
            string JWT;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Basic {base64Auth}");
                var result = client.GetAsync($"{apiUrl}/functions/admin/token").Result;
                JWT = result.Content.ReadAsStringAsync().Result.Trim('"'); //get  JWT for call funtion key
            }
            string facadeKey = "";

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + JWT);

                string  jsonResult = client.GetAsync($"{siteUrl}/admin/host/keys").Result.Content.ReadAsStringAsync().Result;
                dynamic resObject  = JsonConvert.DeserializeObject(jsonResult);
                facadeKey = resObject.keys[0].value;
            }


            Device edgeGatewayDevice = new Device(deviceName);

            edgeGatewayDevice.Capabilities = new DeviceCapabilities()
            {
                IotEdge = true
            };

            await manager.AddDeviceAsync(edgeGatewayDevice);

            string json = "";

            //todo correct
            using (WebClient wc = new WebClient())
            {
                json = wc.DownloadString(deviceConfigurationUrl);
            }

            json = json.Replace("[$region]", region);
            json = json.Replace("[$reset_pin]", resetPin);
            ConfigurationContent spec = JsonConvert.DeserializeObject <ConfigurationContent>(json);
            await manager.AddModuleAsync(new Module(deviceName, "LoRaWanNetworkSrvModule"));

            await manager.ApplyConfigurationContentOnDeviceAsync(deviceName, spec);

            Twin twin = new Twin();

            twin.Properties.Desired = new TwinCollection(@"{FacadeServerUrl:'" + String.Format("https://{0}.azurewebsites.net/api/", GetEnvironmentVariable("FACADE_HOST_NAME")) + "',FacadeAuthCode: " +
                                                         "'" + facadeKey + "'}");
            var remoteTwin = await manager.GetTwinAsync(deviceName);

            await manager.UpdateTwinAsync(deviceName, "LoRaWanNetworkSrvModule", twin, remoteTwin.ETag);

            bool deployEndDevice = false;

            Boolean.TryParse(Environment.GetEnvironmentVariable("DEPLOY_DEVICE"), out deployEndDevice);

            //This section will get deployed ONLY if the user selected the "deploy end device" options.
            //Information in this if clause, is for demo purpose only and should not be used for productive workloads.
            if (deployEndDevice)
            {
                string OTAAdeviceId = "47AAC86800430028";
                Device OTAADevice   = new Device(OTAAdeviceId);
                await manager.AddDeviceAsync(OTAADevice);

                Twin OTAAendTwin = new Twin();
                OTAAendTwin.Properties.Desired = new TwinCollection(@"{AppEUI:'BE7A0000000014E2',AppKey:'8AFE71A145B253E49C3031AD068277A1',GatewayID:''," +
                                                                    "SensorDecoder:'DecoderValueSensor'}");
                var OTAARemoteTwin = await manager.GetTwinAsync(OTAAdeviceId);

                await manager.UpdateTwinAsync(OTAAdeviceId, OTAAendTwin, OTAARemoteTwin.ETag);

                string ABPdeviceId = "46AAC86800430028";
                Device ABPDevice   = new Device(ABPdeviceId);
                await manager.AddDeviceAsync(ABPDevice);

                Twin ABPTwin = new Twin();
                ABPTwin.Properties.Desired = new TwinCollection(@"{AppSKey:'2B7E151628AED2A6ABF7158809CF4F3C',NwkSKey:'3B7E151628AED2A6ABF7158809CF4F3C',GatewayID:''," +
                                                                "DevAddr:'0028B1B1',SensorDecoder:'DecoderValueSensor'}");
                var ABPRemoteTwin = await manager.GetTwinAsync(ABPdeviceId);

                await manager.UpdateTwinAsync(ABPdeviceId, ABPTwin, ABPRemoteTwin.ETag);
            }

            var template = @"{'$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#', 'contentVersion': '1.0.0.0', 'parameters': {}, 'variables': {}, 'resources': []}";
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);


            response.Content = new StringContent(template, System.Text.Encoding.UTF8, "application/json");

            return(response);
        }
Exemplo n.º 25
0
 static void Main(string[] args)
 {
     registryManager = RegistryManager.CreateFromConnectionString(Constants.connectionString);
     AddDeviceAsync().Wait();
     Console.ReadLine();
 }
Exemplo n.º 26
0
 public DeviceGetter(RegistryManager registryManager, ILoRaDeviceCacheStore cacheStore)
 {
     this.registryManager = registryManager;
     this.cacheStore      = cacheStore;
 }
Exemplo n.º 27
0
 public FileManager()
 {
     fe = new FileEncrypter();
     rm = new RegistryManager();
 }
Exemplo n.º 28
0
 public DeviceIdentity()
 {
     // initialize to default values
     _connectionString = AzureIoTHub.GetConnectionString();
     _registryManager  = RegistryManager.CreateFromConnectionString(_connectionString);
 }
 RegistryManager GetRegistryManager()
 {
     return(this.registryManager ?? (this.registryManager = RegistryManager.CreateFromConnectionString(this.Configuration.IoTHubConnectionString)));
 }
 public CleanUpDevicesSample(RegistryManager rm)
 {
     _rm = rm ?? throw new ArgumentNullException(nameof(rm));
 }
Exemplo n.º 31
0
        private void AddToStartup()
        {
            RegistryManager rm = new RegistryManager();

            rm.AddItemToStartup(REGISTRY_STARTUP_VALUE_NAME, this.new_path, NO_MELT_ARG);
        }
Exemplo n.º 32
0
        public async Task TestEdgeHubConnection()
        {
            var twinMessageConverter           = new TwinMessageConverter();
            var twinCollectionMessageConverter = new TwinCollectionMessageConverter();
            var messageConverterProvider       = new MessageConverterProvider(
                new Dictionary <Type, IMessageConverter>()
            {
                { typeof(Client.Message), new DeviceClientMessageConverter() },
                { typeof(Twin), twinMessageConverter },
                { typeof(TwinCollection), twinCollectionMessageConverter }
            });
            var cloudConnectionProvider = new CloudConnectionProvider(messageConverterProvider, 1, new ClientProvider(), Option.None <UpstreamProtocol>());
            var connectionManager       = new ConnectionManager(cloudConnectionProvider);

            string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey");

            Devices.IotHubConnectionStringBuilder iotHubConnectionStringBuilder = Devices.IotHubConnectionStringBuilder.Create(iotHubConnectionString);
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
            await registryManager.OpenAsync();

            (string edgeDeviceId, string deviceConnStr) = await RegistryManagerHelper.CreateDevice("testHubEdgeDevice1", iotHubConnectionString, registryManager, true, false);

            try
            {
                string             iothubHostName          = iotHubConnectionStringBuilder.HostName;
                var                identityFactory         = new ClientCredentialsFactory(iothubHostName);
                string             edgeHubConnectionString = $"{deviceConnStr};ModuleId={EdgeHubModuleId}";
                IClientCredentials edgeHubCredentials      = identityFactory.GetWithConnectionString(edgeHubConnectionString);
                Assert.NotNull(edgeHubCredentials);
                Assert.NotNull(edgeHubCredentials.Identity);

                // Set Edge hub desired properties
                await this.SetDesiredProperties(registryManager, edgeDeviceId);

                var endpointFactory = new EndpointFactory(connectionManager, new RoutingMessageConverter(), edgeDeviceId);
                var routeFactory    = new EdgeRouteFactory(endpointFactory);

                var            dbStoreProvider            = new InMemoryDbStoreProvider();
                IStoreProvider storeProvider              = new StoreProvider(dbStoreProvider);
                IEntityStore <string, TwinInfo> twinStore = storeProvider.GetEntityStore <string, TwinInfo>("twins");
                var      twinManager             = new TwinManager(connectionManager, twinCollectionMessageConverter, twinMessageConverter, Option.Some(twinStore));
                var      routerConfig            = new RouterConfig(Enumerable.Empty <Route>());
                TimeSpan defaultTimeout          = TimeSpan.FromSeconds(60);
                var      endpointExecutorFactory = new SyncEndpointExecutorFactory(new EndpointExecutorConfig(defaultTimeout, new FixedInterval(0, TimeSpan.FromSeconds(1)), defaultTimeout, true));
                Router   router = await Router.CreateAsync(Guid.NewGuid().ToString(), iothubHostName, routerConfig, endpointExecutorFactory);

                IInvokeMethodHandler invokeMethodHandler = new InvokeMethodHandler(connectionManager);
                IEdgeHub             edgeHub             = new RoutingEdgeHub(router, new RoutingMessageConverter(), connectionManager, twinManager, edgeDeviceId, invokeMethodHandler);

                var versionInfo = new VersionInfo("v1", "b1", "c1");

                // Create Edge Hub connection
                Try <ICloudProxy> edgeHubCloudProxy = await connectionManager.CreateCloudConnectionAsync(edgeHubCredentials);

                Assert.True(edgeHubCloudProxy.Success);
                EdgeHubConnection edgeHubConnection = await EdgeHubConnection.Create(
                    edgeHubCredentials.Identity as IModuleIdentity,
                    edgeHub,
                    twinManager,
                    connectionManager,
                    edgeHubCloudProxy.Value,
                    routeFactory,
                    twinCollectionMessageConverter,
                    twinMessageConverter,
                    versionInfo
                    );

                await Task.Delay(TimeSpan.FromMinutes(1));

                // Get and Validate EdgeHubConfig
                Option <EdgeHubConfig> edgeHubConfigOption = await edgeHubConnection.GetConfig();

                Assert.True(edgeHubConfigOption.HasValue);
                EdgeHubConfig edgeHubConfig = edgeHubConfigOption.OrDefault();
                Assert.Equal("1.0", edgeHubConfig.SchemaVersion);
                Assert.NotNull(edgeHubConfig.Routes);
                Assert.NotNull(edgeHubConfig.StoreAndForwardConfiguration);
                Assert.Equal(20, edgeHubConfig.StoreAndForwardConfiguration.TimeToLiveSecs);

                List <(string Name, string Value, Route Route)> routes = edgeHubConfig.Routes.ToList();
                Assert.Equal(4, routes.Count);

                (string Name, string Value, Route Route)route1 = routes[0];
                Assert.NotNull(route1);
                Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint));
                Assert.Equal("route1", route1.Name);
                Assert.Equal("from /* INTO $upstream", route1.Value);

                (string Name, string Value, Route Route)route2 = routes[1];
                Assert.NotNull(route2);
                Endpoint endpoint = route2.Route.Endpoints.First();
                Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id);
                Assert.Equal("route2", route2.Name);
                Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value);

                (string Name, string Value, Route Route)route3 = routes[2];
                Assert.NotNull(route3);
                endpoint = route3.Route.Endpoints.First();
                Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                Assert.Equal($"{edgeDeviceId}/module3/input1", endpoint.Id);
                Assert.Equal("route3", route3.Name);
                Assert.Equal("from /modules/module2 INTO BrokeredEndpoint(\"/modules/module3/inputs/input1\")", route3.Value);

                (string Name, string Value, Route Route)route4 = routes[3];
                Assert.NotNull(route4);
                endpoint = route4.Route.Endpoints.First();
                Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                Assert.Equal($"{edgeDeviceId}/module4/input1", endpoint.Id);
                Assert.Equal("route4", route4.Name);
                Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module4/inputs/input1\")", route4.Value);

                // Make sure reported properties were updated appropriately
                EdgeHubConnection.ReportedProperties reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.NotNull(reportedProperties.Clients);
                Assert.Equal(0, reportedProperties.Clients.Count);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // Simulate a module and a downstream device that connects to Edge Hub.

                string             moduleId = "module1";
                string             sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{edgeDeviceId}/modules/{moduleId}");
                string             moduleConnectionstring  = $"HostName={iothubHostName};DeviceId={edgeDeviceId};ModuleId={moduleId};SharedAccessSignature={sasToken}";
                IClientCredentials moduleClientCredentials = identityFactory.GetWithConnectionString(moduleConnectionstring);
                var moduleProxy = Mock.Of <IDeviceProxy>(d => d.IsActive);

                string downstreamDeviceId = "device1";
                sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{downstreamDeviceId}");
                string             downstreamDeviceConnectionstring = $"HostName={iothubHostName};DeviceId={downstreamDeviceId};SharedAccessSignature={sasToken}";
                IClientCredentials downstreamDeviceCredentials      = identityFactory.GetWithConnectionString(downstreamDeviceConnectionstring);
                var downstreamDeviceProxy = Mock.Of <IDeviceProxy>(d => d.IsActive);

                // Connect the module and downstream device and make sure the reported properties are updated as expected.
                await connectionManager.AddDeviceConnection(moduleClientCredentials.Identity, moduleProxy);

                await connectionManager.AddDeviceConnection(downstreamDeviceCredentials.Identity, downstreamDeviceProxy);

                string moduleIdKey = $"{edgeDeviceId}/{moduleId}";
                await Task.Delay(TimeSpan.FromSeconds(10));

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(2, reportedProperties.Clients.Count);
                Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[moduleIdKey].Status);
                Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc);
                Assert.Null(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc);
                Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[downstreamDeviceId].Status);
                Assert.NotNull(reportedProperties.Clients[downstreamDeviceId].LastConnectedTimeUtc);
                Assert.Null(reportedProperties.Clients[downstreamDeviceId].LastDisconnectTimeUtc);
                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // Update desired propertied and make sure callback is called with valid values
                bool callbackCalled = false;

                Task ConfigUpdatedCallback(EdgeHubConfig updatedConfig)
                {
                    Assert.NotNull(updatedConfig);
                    Assert.NotNull(updatedConfig.StoreAndForwardConfiguration);
                    Assert.NotNull(updatedConfig.Routes);

                    routes = updatedConfig.Routes.ToList();
                    Assert.Equal(4, routes.Count);

                    route1 = routes[0];
                    Assert.NotNull(route1);
                    Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint));
                    Assert.Equal("route1", route1.Name);
                    Assert.Equal("from /* INTO $upstream", route1.Value);

                    route2 = routes[1];
                    Assert.NotNull(route2);
                    endpoint = route2.Route.Endpoints.First();
                    Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                    Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id);
                    Assert.Equal("route2", route2.Name);
                    Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value);

                    route3 = routes[2];
                    Assert.NotNull(route3);
                    endpoint = route3.Route.Endpoints.First();
                    Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                    Assert.Equal($"{edgeDeviceId}/module5/input1", endpoint.Id);
                    Assert.Equal("route4", route3.Name);
                    Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module5/inputs/input1\")", route3.Value);

                    route4 = routes[3];
                    Assert.NotNull(route4);
                    endpoint = route4.Route.Endpoints.First();
                    Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                    Assert.Equal($"{edgeDeviceId}/module6/input1", endpoint.Id);
                    Assert.Equal("route5", route4.Name);
                    Assert.Equal("from /modules/module5 INTO BrokeredEndpoint(\"/modules/module6/inputs/input1\")", route4.Value);

                    callbackCalled = true;
                    return(Task.CompletedTask);
                }

                edgeHubConnection.SetConfigUpdatedCallback(ConfigUpdatedCallback);
                await this.UpdateDesiredProperties(registryManager, edgeDeviceId);

                await Task.Delay(TimeSpan.FromSeconds(5));

                Assert.True(callbackCalled);

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.NotNull(reportedProperties.Clients);
                Assert.Equal(2, reportedProperties.Clients.Count);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // Disconnect the downstream device and make sure the reported properties are updated as expected.
                await connectionManager.RemoveDeviceConnection(moduleIdKey);

                await connectionManager.RemoveDeviceConnection(downstreamDeviceId);

                await Task.Delay(TimeSpan.FromSeconds(10));

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(1, reportedProperties.Clients.Count);
                Assert.True(reportedProperties.Clients.ContainsKey(moduleIdKey));
                Assert.False(reportedProperties.Clients.ContainsKey(downstreamDeviceId));
                Assert.Equal(ConnectionStatus.Disconnected, reportedProperties.Clients[moduleIdKey].Status);
                Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc);
                Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc);
                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // If the edge hub restarts, clear out the connected devices in the reported properties.
                await EdgeHubConnection.Create(edgeHubCredentials.Identity as IModuleIdentity, edgeHub, twinManager, connectionManager, edgeHubCloudProxy.Value, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo);

                await Task.Delay(TimeSpan.FromMinutes(1));

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Null(reportedProperties.Clients);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);
            }
            finally
            {
                try
                {
                    await RegistryManagerHelper.RemoveDevice(edgeDeviceId, registryManager);
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
Exemplo n.º 33
0
        public async Task RegistryManager_ConfigurationOperations_Work()
        {
            // arrange

            bool   configCreated   = false;
            string configurationId = (_idPrefix + Guid.NewGuid()).ToLower(); // Configuration Id characters must be all lower-case.

            using var client = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString);

            try
            {
                var expected = new Configuration(configurationId)
                {
                    Priority        = 2,
                    Labels          = { { "labelName", "labelValue" } },
                    TargetCondition = "*",
                    Content         =
                    {
                        DeviceContent = { { "properties.desired.x", 4L } },
                    },
                    Metrics =
                    {
                        Queries = { { "successfullyConfigured", "select deviceId from devices where properties.reported.x = 4" } }
                    },
                };

                // act and assert

                Configuration addResult = await client.AddConfigurationAsync(expected).ConfigureAwait(false);

                configCreated = true;
                addResult.Id.Should().Be(configurationId);
                addResult.Priority.Should().Be(expected.Priority);
                addResult.TargetCondition.Should().Be(expected.TargetCondition);
                addResult.Content.DeviceContent.First().Should().Be(expected.Content.DeviceContent.First());
                addResult.Metrics.Queries.First().Should().Be(expected.Metrics.Queries.First());
                addResult.ETag.Should().NotBeNullOrEmpty();

                Configuration getResult = await client.GetConfigurationAsync(configurationId).ConfigureAwait(false);

                getResult.Id.Should().Be(configurationId);
                getResult.Priority.Should().Be(expected.Priority);
                getResult.TargetCondition.Should().Be(expected.TargetCondition);
                getResult.Content.DeviceContent.First().Should().Be(expected.Content.DeviceContent.First());
                getResult.Metrics.Queries.First().Should().Be(expected.Metrics.Queries.First());
                getResult.ETag.Should().Be(addResult.ETag);

                IEnumerable <Configuration> listResult = await client.GetConfigurationsAsync(100).ConfigureAwait(false);

                listResult.Should().Contain(x => x.Id == configurationId);

                expected.Priority++;
                expected.ETag = getResult.ETag;
                Configuration updateResult = await client.UpdateConfigurationAsync(expected).ConfigureAwait(false);

                updateResult.Id.Should().Be(configurationId);
                updateResult.Priority.Should().Be(expected.Priority);
                updateResult.TargetCondition.Should().Be(expected.TargetCondition);
                updateResult.Content.DeviceContent.First().Should().Be(expected.Content.DeviceContent.First());
                updateResult.Metrics.Queries.First().Should().Be(expected.Metrics.Queries.First());
                updateResult.ETag.Should().NotBeNullOrEmpty().And.Should().NotBe(getResult.ETag, "The ETag should have changed after update");
            }
            finally
            {
                if (configCreated)
                {
                    // If this fails, we shall let it throw an exception and fail the test
                    await client.RemoveConfigurationAsync(configurationId).ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 34
0
        static async Task <IEnumerable <Device> > GetDevices(string iothubConString, int maxdevices = 500)
        {
            var registryManager = RegistryManager.CreateFromConnectionString(iothubConString);

            return(await registryManager.GetDevicesAsync(maxdevices)); // Time 1 sek
        }