public async Task <dynamic> ListMoviesUpcomingWithGenres(string page)
        {
            var genres = await _genreRepository.ListMovieGenres();

            var upcomingMovies = await _movieRepository.ListUpcomingMovies(page);

            var resultList = new List <ResultCommand>();

            foreach (var movie in upcomingMovies.results)
            {
                var result = new ResultCommand();

                result.Filme          = movie.title;
                result.DataLancamento = movie.release_date;

                var movieGenres = genres.genres.Where(genre => movie.genre_ids.Any(item => item.Equals(genre.id)));

                foreach (var item in movieGenres)
                {
                    result.Generos.Add(item.name);
                }

                resultList.Add(result);
            }

            return(resultList);
        }
        public async Task <ResultCommand> SetDeviceSecretKeys(RequestCommandSetDeviceSecretKeys requestSetDeviceKeys)
        {
            try
            {
                //Set new Portal password
                if (!await PortalApiHelper.SetDevicePassword(SecretManager.PortalPassword, requestSetDeviceKeys.PortalPassword))
                {
                    return(ResultCommand.CreateFailedCommand($"Error SetDevicePassword: Error while setting new device password."));
                }
                //Update Portal Password
                SecretManager.PortalPassword = requestSetDeviceKeys.PortalPassword;
                PortalApiHelper.Init("Administrator", SecretManager.PortalPassword);

                //Change Encryption Key
                SecretManager.EncryptionKey = requestSetDeviceKeys.EncryptionKey;

                //Set new Access Point - Will change the AP after reboot of the app
                //SecretManager.AccessPointSsid = SecretManager.AccessPointSsid;
                SecretManager.AccessPointPassword = requestSetDeviceKeys.AccessPointPassword;

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error SetDevicePassword: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error SetDevicePassword: {e.Message}."));
            }
        }
        protected override IScriptCommand executeInner(ParameterDic pm, ItemsControl ic, RoutedEventArgs evnt, IUIInput input, IList <IUIInputProcessor> inpProcs)
        {
            var        scp    = ControlUtils.GetScrollContentPresenter(ic);
            IChildInfo icInfo = UITools.FindVisualChild <Panel>(scp) as IChildInfo;

            if (icInfo == null)
            {
                return(ResultCommand.Error(new NotSupportedException()));
            }

            Rect          selectionBound = pm.GetValue <Rect>(SelectionBoundAdjustedKey);
            List <object> selectedList   = new List <object>();
            List <int>    selectedIdList = new List <int>();

            for (int i = 0; i < ic.Items.Count; i++)
            {
                if (icInfo.GetChildRect(i).IntersectsWith(selectionBound))
                {
                    selectedList.Add(ic.Items[i]);
                    selectedIdList.Add(i);
                }
            }

            pm.SetValue(SelectedListKey, selectedList);
            pm.SetValue(SelectedIdListKey, selectedIdList);
            logger.Debug(String.Format("Selected = {0}", selectedIdList.Count()));

            return(NextCommand);
        }
Beispiel #4
0
        public ResultCommandGenerateCSR GenerateCSR()
        {
            try
            {
                //Generate Certificate with RSA Private key
                byte[] csr = null;
                using (RSA key = SimulatedDevice.GetPrivateKey(true))
                {
                    CertificateRequest certRequest = new CertificateRequest($"CN={SimulatedDevice.DeviceId}",
                                                                            key,
                                                                            HashAlgorithmName.SHA256,
                                                                            RSASignaturePadding.Pkcs1);
                    csr = certRequest.CreateSigningRequest();
                }

                return(new ResultCommandGenerateCSR()
                {
                    Csr = csr != null?Convert.ToBase64String(csr) : null,
                              IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GenerateCSR: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandGenerateCSR>($"Error GenerateCSR: {e.Message}."));
            }
        }
Beispiel #5
0
        public async Task <ResultCommandAvailableNetworks> GetAvailableNetworkListHandler()
        {
            try
            {
                var wifiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();

                List <AvailableNetwork> networks = new List <AvailableNetwork>();

                foreach (var adapter in wifiAdapterList)
                {
                    try
                    {
                        var availableNetworks = await PortalApiHelper.GetAvailableNetworks(adapter.NetworkAdapter.NetworkAdapterId);

                        if (availableNetworks != null && availableNetworks.AvailableNetworks != null)
                        {
                            networks.AddRange(availableNetworks.AvailableNetworks);
                        }
                    }
                    catch (Exception) { }
                }

                var sortedNetworks = networks.OrderBy(x => x.SSID).Distinct().ToList();

                return(new ResultCommandAvailableNetworks()
                {
                    Networks = sortedNetworks, IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GetAvailableNetworkListHandler: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandAvailableNetworks>($"Error GetAvailableNetworkListHandler: {e.Message}."));
            }
        }
Beispiel #6
0
        public async Task <ResultCommand> ProvisionDevice(RequestCommandProvisionDevice requestProvisionDevice, string password)
        {
            try
            {
                DeviceCertificateModel certificateInfo = requestProvisionDevice.DeviceCertificateInformation;

                //Load certificate chain
                var(deviceCertificate, collectionCertificates) =
                    LoadCertificateFromPfx(Convert.FromBase64String(certificateInfo.Certificate), password);

                //Save certificate in store
                if (!await SaveCertificateInStore(deviceCertificate))
                {
                    return(ResultCommand.CreateFailedCommand($"Error while saving User Certificate in Store."));
                }

                using (var securityProvider = new SecurityProviderX509Certificate(deviceCertificate, collectionCertificates))
                {
                    using (var transport = new ProvisioningTransportHandlerHttp())
                    {
                        ProvisioningDeviceClient provClient =
                            ProvisioningDeviceClient.Create(certificateInfo.DpsInstance, certificateInfo.DpsIdScope, securityProvider, transport);
                        DeviceRegistrationResult result = await provClient.RegisterAsync();

                        if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                        {
                            DebugHelper.LogError($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
                            return(ResultCommand.CreateFailedCommand($"Error during registration: {result.Status}, {result.ErrorMessage}"));
                        }

                        //Test the connection
                        if (!await TestDeviceConnection(result.DeviceId, result.AssignedHub, deviceCertificate))
                        {
                            return(ResultCommand.CreateFailedCommand($"Error while testing the device connection."));
                        }

                        //Persist provision in TPM/HSM
                        SimulatedDevice.ProvisionDevice(result.AssignedHub, result.DeviceId);

                        //Provisioned!
                        SimulatedDevice.IsProvisioned = true;
                    }
                }
                if (deviceCertificate != null)
                {
                    deviceCertificate.Dispose();
                }

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error ProvisionDevice: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error ProvisionDevice: {e.Message}."));
            }
        }
        public override IScriptCommand Execute(ParameterDic pm)
        {
            try
            {
                _command.Execute(pm.GetValue("{Parameter}"));
            }
            catch (Exception ex) { return(ResultCommand.Error(ex)); }

            return(ResultCommand.NoError);
        }
Beispiel #8
0
        private void ProcessCommand(CommandEventArgs commandArgs, Func <ResultCommand> commandProcess)
        {
            ResultCommand resultCommand = commandProcess();

            commandArgs.OutputCommand = new Command()
            {
                BaseCommand = commandArgs.InputCommand.BaseCommand + 100,
                Data        = resultCommand != null ? resultCommand : null
            };
        }
Beispiel #9
0
        private async Task ProcessCommand(CommandEventArgs commandArgs, Func <Task <ResultCommand> > commandProcess)
        {
            ResultCommand resultCommand = await commandProcess();

            commandArgs.OutputCommand = new Command()
            {
                BaseCommand = commandArgs.InputCommand.BaseCommand + 100,
                Data        = resultCommand != null ? resultCommand : null
            };
        }
Beispiel #10
0
        private static Task <TResponse> Errors(IEnumerable <ValidationFailure> failures)
        {
            var response = new ResultCommand();

            foreach (var failure in failures)
            {
                response.ValidationResult.Errors.Add(failure);
            }
            return(Task.FromResult(response as TResponse));
        }
        public override IScriptCommand Execute(FileExplorer.ParameterDic pm)
        {
            IWindowManager wm = pm.GetValue <IWindowManager>(WindowManagerKey) ?? new WindowManager();

            WPF.MDI.MdiContainer container = pm.GetValue <WPF.MDI.MdiContainer>(MdiContainerKey);

            if (container == null)
            {
                return(ResultCommand.Error(new KeyNotFoundException("MdiContainerKey")));
            }

            IExplorerViewModel explorer = pm.GetValue <IExplorerViewModel>(ExplorerKey);

            if (explorer == null)
            {
                return(ResultCommand.Error(new KeyNotFoundException("ExplorerKey")));
            }

            var view = new ExplorerView();

            Caliburn.Micro.Bind.SetModel(view, explorer); //Set the ViewModel using this command.
            var mdiChild = new WPF.MDI.MdiChild
            {
                DataContext = explorer,
                ShowIcon    = true,
                Content     = view
            };

            mdiChild.SetBinding(WPF.MDI.MdiChild.TitleProperty, new Binding("DisplayName")
            {
                Mode = BindingMode.OneWay
            });
            mdiChild.SetBinding(WPF.MDI.MdiChild.IconProperty, new Binding("CurrentDirectory.Icon")
            {
                Mode = BindingMode.OneWay
            });
            mdiChild.SetBinding(WPF.MDI.MdiChild.WidthProperty, new Binding("Parameters.Width")
            {
                Mode = BindingMode.TwoWay
            });
            mdiChild.SetBinding(WPF.MDI.MdiChild.HeightProperty, new Binding("Parameters.Height")
            {
                Mode = BindingMode.TwoWay
            });
            mdiChild.SetBinding(WPF.MDI.MdiChild.PositionProperty, new Binding("Parameters.Position")
            {
                Mode = BindingMode.TwoWay
            });
            container.Children.Add(mdiChild);

            return(NextCommand);
        }
        public async Task <ResultCommand> SetDeviceType(RequestCommandSetDeviceType requestDeviceType)
        {
            try
            {
                var apps = await LoadFirmwares();

                //Find the app
                var app = apps.FirstOrDefault(p => p.PackageFullName.ToLower().StartsWith(requestDeviceType.DeviceType.ToLower()));
                if (app == null)
                {
                    DebugHelper.LogError($"Package starting with {requestDeviceType.DeviceType} not found.");
                    return(ResultCommand.CreateFailedCommand($"Error SetDeviceType: Package starting with {requestDeviceType.DeviceType} not found."));
                }

                //Deactivate all other firmwares at startup
                foreach (var appToStop in apps)
                {
                    if (appToStop.IsStartup)
                    {
                        if (!await PortalApiHelper.SetStartupForHeadlessApp(false, appToStop.PackageFullName))
                        {
                            DebugHelper.LogError($"Error while turning off run at startup for App {appToStop.PackageFullName}");
                        }
                    }
                    if (!await PortalApiHelper.StopHeadlessApp(appToStop.PackageFullName))
                    {
                        DebugHelper.LogError($"Error while stopping App {appToStop.PackageFullName}");
                    }
                }

                //Start our firmware and set to run
                if (!await PortalApiHelper.StartHeadlessApp(app.PackageFullName))
                {
                    DebugHelper.LogError($"Error while starting App {app.PackageFullName}");
                    return(ResultCommand.CreateFailedCommand($"Error SetDeviceType: Error while starting App {app.PackageFullName}"));
                }

                if (!await PortalApiHelper.SetStartupForHeadlessApp(true, app.PackageFullName))
                {
                    DebugHelper.LogError($"Error while turning on run at startup for App {app.PackageFullName}");
                    return(ResultCommand.CreateFailedCommand($"Error SetDeviceType: Error while turning on run at startup for App {app.PackageFullName}"));
                }

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error SetDeviceType: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error SetDeviceType: {e.Message}."));
            }
        }
Beispiel #13
0
        public async Task <ResultCommandGetDeviceId> GetDeviceId()
        {
            RestRequest request = await PrepareQuery("GetDeviceId", Method.GET);

            var queryResult = await _client.ExecuteTaskAsync <Command>(request);

            if (queryResult.IsSuccessful)
            {
                return(GetResultCommand <ResultCommandGetDeviceId>(queryResult.Data));
            }
            else
            {
                Debug.WriteLine($"GetDeviceId: {queryResult.StatusCode}");
            }
            return(ResultCommand.CreateFailedCommand <ResultCommandGetDeviceId>($"GetDeviceId: {queryResult.StatusCode}"));
        }
Beispiel #14
0
 public ResultCommandGetDeviceId GetDeviceId()
 {
     try
     {
         return(new ResultCommandGetDeviceId()
         {
             DeviceId = SimulatedDevice.DeviceId,
             IsSuccess = true
         });
     }
     catch (Exception e)
     {
         DebugHelper.LogError($"Error GetDeviceId: {e.Message}.");
         return(ResultCommand.CreateFailedCommand <ResultCommandGetDeviceId>($"Error GetDeviceId: {e.Message}."));
     }
 }
        public async Task <ResultCommand> StopApp(string appName)
        {
            var apps = await PortalApiHelper.ListFirmwares();

            foreach (var app in apps.AppPackages)
            {
                if (app.PackageFullName.ToLower().StartsWith(appName.ToLower()))
                {
                    if (!await PortalApiHelper.StopHeadlessApp(app.PackageFullName))
                    {
                        return(ResultCommand.CreateFailedCommand($"Error StopApp: Error while stopping App {app.PackageFullName}"));
                    }
                    break;
                }
            }
            return(ResultCommand.CreateSuccessCommand());
        }
Beispiel #16
0
        public async Task <ResultCommandNetworkStatus> DisconnectFromClientNetwork(RequestCommandDisconnectFromNetwork requestDisconnectFromNetwork)
        {
            RestRequest request = await PrepareQuery("DisconnectFromNetwork", Method.POST);

            request.AddParameter("application/json", JsonConvert.SerializeObject(requestDisconnectFromNetwork), ParameterType.RequestBody);
            var queryResult = await _client.ExecuteTaskAsync <Command>(request);

            if (queryResult.IsSuccessful)
            {
                return(GetResultCommand <ResultCommandNetworkStatus>(queryResult.Data));
            }
            else
            {
                Debug.WriteLine($"DisconnectFromNetwork: {queryResult.StatusCode}");
            }
            return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"DisconnectFromNetwork: {queryResult.StatusCode}"));
        }
Beispiel #17
0
        public async Task <ResultCommand> SetDeviceType(RequestCommandSetDeviceType requestSetDeviceType)
        {
            RestRequest request = await PrepareQuery("SetDeviceType", Method.POST);

            request.AddParameter("application/json", JsonConvert.SerializeObject(requestSetDeviceType), ParameterType.RequestBody);
            var queryResult = await _client.ExecuteTaskAsync <Command>(request);

            if (queryResult.IsSuccessful)
            {
                return(GetResultCommand <ResultCommand>(queryResult.Data));
            }
            else
            {
                Debug.WriteLine($"SetDeviceType: {queryResult.StatusCode}");
            }
            return(ResultCommand.CreateFailedCommand <ResultCommand>($"SetDeviceType: {queryResult.StatusCode}"));
        }
Beispiel #18
0
        public override IScriptCommand Execute(ParameterDic pm)
        {
            AdornerLayer     value  = null;
            FrameworkElement sender = pm.GetValue <FrameworkElement>(SenderKey);

            if (sender == null)
            {
                return(ResultCommand.Error(new KeyNotFoundException(SenderKey)));
            }
            switch (AssignAdornerType)
            {
            case AdornerType.Named:
                Window           parentWindow = Window.GetWindow(sender);
                AdornerDecorator decorator    = UITools.FindVisualChildByName <AdornerDecorator>(parentWindow, "PART_DragDropAdorner");
                value = AdornerLayer.GetAdornerLayer(sender);
                break;

            case AdornerType.ItemsControl:
                value = AdornerLayer.GetAdornerLayer(sender);
                break;

            case AdornerType.SelectedItem:
                if (!(sender is ItemsControl))
                {
                    return(ResultCommand.Error(new ArgumentException(SenderKey)));
                }
                ItemsControl ic = sender as ItemsControl;
                foreach (var item in ic.ItemsSource)
                {
                    if (item is ISelectable && (item as ISelectable).IsSelected)
                    {
                        UIElement selectedItem = ic.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
                        value = UITools.FindVisualChild <AdornerLayer>(selectedItem);
                    }
                }
                break;
            }

            if (value != null)
            {
                return(ScriptCommands.Assign(DestinationKey,
                                             value, SkipIfExists, NextCommand));
            }
            return(FailCommand);
        }
        public async Task <ResultCommandListFirmwares> GetFirmwares()
        {
            try
            {
                var allFirmwares = await LoadFirmwares();

                return(new ResultCommandListFirmwares()
                {
                    Firmwares = allFirmwares.Select(p => p.PackageFullName),
                    IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error ListFirmwares: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandListFirmwares>($"Error ListFirmwares: {e.Message}."));
            }
        }
        public async Task <ResultCommand> SetDeviceName(RequestCommandSetDeviceName requestDeviceName)
        {
            try
            {
                if (!await PortalApiHelper.SetDeviceName(requestDeviceName.Name))
                {
                    DebugHelper.LogError($"Error while setting device name: {requestDeviceName.Name}");
                    return(ResultCommand.CreateFailedCommand($"Error SetDeviceName: Error while setting device name: {requestDeviceName.Name}"));
                }

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error SetDeviceName: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error SetDeviceName: {e.Message}."));
            }
        }
        public async Task <ResultCommandIPAdapters> GetNetworkProfiles()
        {
            try
            {
                var profiles = await PortalApiHelper.GetNetworkProfiles();

                return(new ResultCommandIPAdapters()
                {
                    IPAdapters = profiles,
                    IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GetAccessPointSettings: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandIPAdapters>($"Error GetAccessPointSettings: {e.Message}."));
            }
        }
Beispiel #22
0
        public void Execute_ArbitraryCommand_Always_Executes()
        {
            // arrange
            CommandsLibrary.Setup();

            var command = new ResultCommand {
                Number = 1
            };


            // act
            var result = CommandsLibrary.CommandsProcessor.Execute((ICommand)command);


            // assert
            result.Should().Be(2);
            command.Number.Should().Be(2);
        }
        public async Task <ResultCommandSoftAPSettings> GetAccessPointSettings()
        {
            try
            {
                var apSettings = await PortalApiHelper.GetSoftAPSettings();

                return(new ResultCommandSoftAPSettings()
                {
                    SoftAPSettings = apSettings,
                    IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GetAccessPointSettings: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandSoftAPSettings>($"Error GetAccessPointSettings: {e.Message}."));
            }
        }
        public static async Task Test_CopyFile()
        {
            string tempDirectory = "C:\\Temp";
            string srcFile       = System.IO.Path.Combine(tempDirectory, "File1.txt");
            string destFile      = System.IO.Path.Combine(tempDirectory, "File2.txt");
            string signature     = "Created by testCopyFile at " + DateTime.Now.ToString();

            Directory.CreateDirectory(tempDirectory);
            using (var sw = File.CreateText(srcFile))
                sw.WriteLine(signature);
            //File.Delete(destFile);

            IProfile fsiProfile = new FileSystemInfoExProfile(null, null);


            IScriptCommand copyCommand =
                CoreScriptCommands.ParsePath("{Profile}", "{SourceFile}", "{Source}",
                                             CoreScriptCommands.DiskParseOrCreateFile("{Profile}", "{DestinationFile}", "{Destination}",
                                                                                      CoreScriptCommands.DiskOpenStream("{Source}", "{SourceStream}", FileExplorer.Defines.FileAccess.Read,
                                                                                                                        CoreScriptCommands.DiskOpenStream("{Destination}", "{DestinationStream}", FileExplorer.Defines.FileAccess.Write,
                                                                                                                                                          CoreScriptCommands.CopyStream("{SourceStream}", "{DestinationStream}"))))
                                             , ResultCommand.Error(new FileNotFoundException(srcFile))
                                             );

            //copyCommand = ScriptCommands.CopyFile("SourceFile", "DestinationFile");
            copyCommand = serializeAndDeserializeCommand(copyCommand);
            await ScriptRunner.RunScriptAsync(new ParameterDic()
            {
                { "Profile", fsiProfile },
                { "SourceFile", srcFile },
                { "DestinationFile", destFile }
            }, copyCommand);


            string actual = null;

            using (var sr = File.OpenText(destFile))
            {
                actual = sr.ReadLine();
            }

            Assert.AreEqual(signature, actual);
        }
Beispiel #25
0
        public async Task <ResultCommandNetworkStatus> ConnectToNetworkHandler(RequestCommandConnectToNetwork requestConnectToNetwork)
        {
            try
            {
                NetworkInformation networkInfo = requestConnectToNetwork.NetworkInformation;

                var wifiSet = await FindWifi(networkInfo.Ssid);

                if (wifiSet != null)
                {
                    if (!await PortalApiHelper.DisconnectFromNetwork(wifiSet.Adapter.NetworkAdapter.NetworkAdapterId))
                    {
                        DebugHelper.LogWarning($"Error while trying to disconnect from network: {wifiSet.Adapter.NetworkAdapter.NetworkAdapterId}");
                    }

                    var availableNetworks = await PortalApiHelper.GetAvailableNetworks(wifiSet.Adapter.NetworkAdapter.NetworkAdapterId);

                    foreach (var network in availableNetworks.AvailableNetworks)
                    {
                        if (network.ProfileAvailable && !await PortalApiHelper.DeleteNetworkProfile(wifiSet.Adapter.NetworkAdapter.NetworkAdapterId, network.ProfileName))
                        {
                            DebugHelper.LogWarning($"Error while trying to disconnect from network: {wifiSet.Adapter.NetworkAdapter.NetworkAdapterId}");
                        }
                    }
                    if (!await PortalApiHelper.ConnectToNetwork(wifiSet.Adapter.NetworkAdapter.NetworkAdapterId, networkInfo.Ssid, networkInfo.Password))
                    {
                        return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"Error ConnectToNetworkHandler: Could not connect to network '{networkInfo.Ssid}'."));
                    }

                    return(new ResultCommandNetworkStatus()
                    {
                        IsSuccess = true, Status = "Connected"
                    });
                }
                return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"Error ConnectToNetworkHandler: UnspecifiedFailure."));
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error ConnectToNetworkHandler: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"Error ConnectToNetworkHandler: {e.Message}."));
            }
        }
Beispiel #26
0
        private async Task ProcessCommand <T>(CommandEventArgs commandArgs, Func <T, Task <ResultCommand> > commandProcess) where T : RequestCommand
        {
            T             requestCommand = null;
            ResultCommand resultCommand  = null;
            string        data           = commandArgs.InputCommand.Data.ToString();

            if (!string.IsNullOrEmpty(data))
            {
                requestCommand = JsonConvert.DeserializeObject <T>(data);
            }
            if (requestCommand != null)
            {
                resultCommand = await commandProcess(requestCommand);
            }
            commandArgs.OutputCommand = new Command()
            {
                BaseCommand = commandArgs.InputCommand.BaseCommand + 100,
                Data        = resultCommand != null ? resultCommand : null
            };
        }
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            string fileName = _fileNameGenerator.Generate();

            while (fileName != null &&
                   await _profile.ParseAsync(_profile.Path.Combine(_parentPath, fileName)) != null)
            {
                fileName = _fileNameGenerator.Generate();
            }
            if (fileName == null)
            {
                return(ResultCommand.Error(new ArgumentException("Already exists.")));
            }

            string newEntryPath  = _profile.Path.Combine(_parentPath, fileName);
            var    createddModel = await _profile.DiskIO.CreateAsync(newEntryPath, _isFolder, pm.CancellationToken);

            return(new NotifyChangedCommand(_profile, newEntryPath, FileExplorer.Defines.ChangeType.Created,
                                            _thenFunc(createddModel)));
        }
Beispiel #28
0
        public override IScriptCommand Execute(ParameterDic pm)
        {
            FrameworkElement origSource = pm.GetValue <FrameworkElement>(SourceElementKey);

            Value = null;
            FrameworkElement ele = null;

            if (origSource != null)
            {
                switch (DataContextType)
                {
                case UIEventHub.DataContextType.Any:
                    Value = origSource.DataContext;
                    ele   = origSource;
                    break;

                case UIEventHub.DataContextType.SupportDrag:
                    Value = DataContextFinder.GetDataContext(origSource, out ele, DataContextFinder.SupportDrag);
                    break;

                case UIEventHub.DataContextType.SupportShellDrag:
                    Value = DataContextFinder.GetDataContext(origSource, out ele, DataContextFinder.SupportShellDrag);
                    break;

                case UIEventHub.DataContextType.SupportShellDrop:
                    Value = DataContextFinder.GetDataContext(origSource, out ele, DataContextFinder.SupportShellDrop);
                    break;

                case UIEventHub.DataContextType.SupportDrop:
                    Value = DataContextFinder.GetDataContext(origSource, out ele, DataContextFinder.SupportDrop);
                    break;

                default:
                    return(ResultCommand.Error(new NotSupportedException("DataContextType")));
                }
            }

            pm.SetValue(VariableKey, Value, SkipIfExists);
            pm.SetValue(DataContextElementKey, ele, SkipIfExists);
            return(NextCommand);
        }
        public override IScriptCommand Execute(ParameterDic pm)
        {
            FrameworkElement   ele      = pm.GetValue <FrameworkElement>(ElementKey);
            DependencyProperty property = pm.GetValue <DependencyProperty>(PropertyKey);

            if (ele == null)
            {
                return(ResultCommand.Error(new ArgumentException(ElementKey)));
            }
            if (property == null)
            {
                return(ResultCommand.Error(new ArgumentException(PropertyKey)));
            }

            object value = ele.GetValue(property);

            logger.Debug(String.Format("{0}'s {1} is equal to {2}", ele, property, value));
            pm.SetValue(DestinationKey, value);

            return(NextCommand);
        }
        public async Task <ResultCommandAvailableNetworks> GetAvailableNetworkListHandler()
        {
            try
            {
                var wifiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();

                var wifiList = from adapter in wifiAdapterList
                               from network in adapter.NetworkReport.AvailableNetworks
                               select network.Ssid;
                var networks = wifiList.OrderBy(x => x).Distinct();

                return(new ResultCommandAvailableNetworks()
                {
                    Networks = networks, IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GetAvailableNetworkListHandler: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandAvailableNetworks>($"Error GetAvailableNetworkListHandler: {e.Message}."));
            }
        }