Ejemplo n.º 1
0
        public async Task<bool> SignalExternalCommandLineArgs(IList<string> args)
        {
            if (args == null || args.Count == 0)
                return true;
            if ((args.Count <= 2)) return true;
            //the first index always contains the location of the exe so we need to check the second index
            if ((args[1].ToLowerInvariant() != "-startscene")) return true;
            var searchQuery = args[2].ToLower();

            using (var context = new ZvsContext(EntityContextConnection))
            {
                Scene scene;
                int sceneId;
                if (int.TryParse(searchQuery, out sceneId))
                    scene = await context.Scenes.FirstOrDefaultAsync(s => s.Id == sceneId);
                else scene = await context.Scenes.FirstOrDefaultAsync(s => s.Name.ToLower().Equals(searchQuery));

                if (scene != null)
                {
                    var cmd = await context.BuiltinCommands.FirstOrDefaultAsync(c => c.UniqueIdentifier == "RUN_SCENE");
                    if (cmd == null) return true;

                    await ZvsEngine.RunCommandAsync(cmd.Id, scene.Id.ToString(CultureInfo.InvariantCulture), string.Empty, Cts.Token);
                }
                else
                    await Log.ReportInfoFormatAsync(Cts.Token, "Cannot find scene '{0}'", searchQuery);
            }
            return true;
        }
        internal async Task<Result> ExecuteDeviceCommandAsync(DeviceCommand command, string argument, string argument2, CancellationToken cancellationToken)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                var deviceCommand = await context.DeviceCommands
                    .Include(o => o.Device)
                    .Include(o => o.Device.Type)
                    .Include(o => o.Device.Type.Adapter)
                    .FirstOrDefaultAsync(o => o.Id == command.Id, cancellationToken);

                if (deviceCommand == null)
                    return Result.ReportErrorFormat("Cannot locate device command with id of {0}", command.Id);

                var commandAction = string.Format("{0}{1} ({3}) on {2} ({4})",
                    deviceCommand.Name,
                    string.IsNullOrEmpty(argument) ? "" : " " + argument,
                    deviceCommand.Device.Name, deviceCommand.Id, deviceCommand.Device.Id);

                var aGuid = deviceCommand.Device.Type.Adapter.AdapterGuid;
                var adapter = AdapterManager.FindZvsAdapter(aGuid);
                if (adapter == null)
                {
                    return Result.ReportErrorFormat("{0} failed, device adapter is not loaded!",
                        commandAction);
                }

                if (!adapter.IsEnabled)
                    return Result.ReportErrorFormat("{0} failed because the '{1}' adapter is disabled",
                        commandAction,
                        deviceCommand.Device.Type.Adapter.Name);

                await adapter.ProcessDeviceCommandAsync(deviceCommand.Device, deviceCommand, argument, argument2);
                return Result.ReportSuccessFormat("{0} complete", commandAction);
            }
        }
Ejemplo n.º 3
0
        public static async Task <Result> TryAddOrEditAsync(ZvsContext context, ProgramOption programOption, CancellationToken cancellationToken)
        {
            if (programOption == null)
            {
                throw new ArgumentNullException(nameof(programOption));
            }

            var existingOption = await context.ProgramOptions.FirstOrDefaultAsync(o => o.UniqueIdentifier == programOption.UniqueIdentifier, cancellationToken);

            var changed = false;

            if (existingOption == null)
            {
                context.ProgramOptions.Add(programOption);
                changed = true;
            }
            else
            {
                if (existingOption.Value != programOption.Value)
                {
                    changed = true;
                    existingOption.Value = programOption.Value;
                }
            }

            if (changed)
            {
                return(await context.TrySaveChangesAsync(cancellationToken));
            }

            return(Result.ReportSuccess());
        }
Ejemplo n.º 4
0
        public static async Task<Result> TryAddOrEditAsync(ZvsContext context, ProgramOption programOption, CancellationToken cancellationToken)
        {
            if (programOption == null)
                throw new ArgumentNullException("programOption");

            var existingOption = await context.ProgramOptions.FirstOrDefaultAsync(o => o.UniqueIdentifier == programOption.UniqueIdentifier, cancellationToken);

            var changed = false;

            if (existingOption == null)
            {
                context.ProgramOptions.Add(programOption);
                changed = true;
            }
            else
            {
                if (existingOption.Value != programOption.Value)
                {
                    changed = true;
                    existingOption.Value = programOption.Value;
                }
            }

            if (changed)
                return await context.TrySaveChangesAsync(cancellationToken);

            return Result.ReportSuccess();
        }
        public async Task RegisterAsyncNewTest()
        {
            //arrange 
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "ssb-RegisterAsyncNewTest" };
            Database.SetInitializer(new CreateFreshDbInitializer());
            var ssb = new SceneSettingBuilder(dbConnection);

            var sceneSetting = new SceneSetting
            {
                Name = "Unit Test Scene Setting",
                UniqueIdentifier = "SCENE_SETTING1"
            };

            //act
            var result = await ssb.RegisterAsync(sceneSetting, CancellationToken.None);

            SceneSetting setting;
            using (var context = new ZvsContext(dbConnection))
            {
                setting =
                    await
                        context.SceneSettings.FirstOrDefaultAsync(
                            o => o.UniqueIdentifier == sceneSetting.UniqueIdentifier);

            }

            //assert 
            Console.WriteLine(result.Message);
            Assert.IsFalse(result.HasError, result.Message);
            Assert.IsNotNull(setting, "Expected new scene setting saved to DB");
        }
        internal async Task<Result> ExecuteDeviceTypeCommandAsync(DeviceTypeCommand command, string argument, string argument2, CancellationToken cancellationToken)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                int dId = int.TryParse(argument2, out dId) ? dId : 0;

                var device = await context.Devices
                    .Include(o => o.Type)
                    .Include(o => o.Type.Adapter)
                    .FirstOrDefaultAsync(o => o.Id == dId, cancellationToken);

                if (device == null)
                    return Result.ReportErrorFormat("Cannot find device with id of {0}", dId);

                var commandAction =
                    $"{command.Name}{(string.IsNullOrEmpty(argument) ? "" : " " + argument)} {device.Name}";

                var aGuid = device.Type.Adapter.AdapterGuid;
                var adapter = AdapterManager.FindZvsAdapter(aGuid);
                if (adapter == null)
                {
                    return Result.ReportErrorFormat("{0} failed, device adapter is not loaded!",
                        commandAction);
                }

                if (!adapter.IsEnabled)
                    return Result.ReportErrorFormat("{0} failed because the {1} adapter is {2}",
                        commandAction,
                        device.Type.Adapter.Name,
                        adapter.IsEnabled ? "not ready" : "disabled");

                await adapter.ProcessDeviceTypeCommandAsync(device.Type, device, command, argument);
                return Result.ReportSuccessFormat("{0} complete", commandAction);
            }
        }
        public async Task RegisterAsyncNewTest()
        {
            //arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());
            var bcb = new BuiltinCommandBuilder(dbConnection);

            var builtinCommand = new BuiltinCommand
            {
                Name = "Unit Test Builtin Command",
                UniqueIdentifier = "BUILTIN_COMMAND1"
            };

            //act
            var result = await bcb.RegisterAsync(builtinCommand, CancellationToken.None);

            BuiltinCommand setting;
            using (var context = new ZvsContext(dbConnection))
            {
                setting =
                    await
                        context.BuiltinCommands.FirstOrDefaultAsync(
                            o => o.UniqueIdentifier == builtinCommand.UniqueIdentifier);

            }

            //assert 
            Console.WriteLine(result.Message);
            Assert.IsFalse(result.HasError, result.Message);
            Assert.IsNotNull(setting, "Expected new builtin command setting saved to DB");
        }
        public async Task RegisterAsyncNewDeviceValueTest()
        {
            //arrange 
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "dvb-RegisterAsyncNewDeviceValueTest" };
            Database.SetInitializer(new CreateFreshDbInitializer());

            var dvb = new DeviceValueBuilder( dbConnection);

            var device = UnitTesting.CreateFakeDevice();
            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                await context.SaveChangesAsync();

                var deviceValue = new DeviceValue
                {
                    Description = "Testing Value Description Here",
                    Name = "Test Value",
                    ValueType = DataType.BOOL,
                    Value = true.ToString(),
                    DeviceId = device.Id
                };

                //act
                var result = await dvb.RegisterAsync(deviceValue, device, CancellationToken.None);
                var dv = await context.DeviceValues.FirstOrDefaultAsync(o => o.Name == deviceValue.Name);


                //assert 
                Assert.IsFalse(result.HasError, result.Message);
                Assert.IsNotNull(dv, "Registered device value count not be found in database.");
                Console.WriteLine(result.Message);
            }
        }
        public async Task<IHttpActionResult> Execute([FromODataUri] int key, ODataActionParameters parameters)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }

            var arg1 = (string)parameters["Argument"];
            var arg2 = (string)parameters["Argument2"];

            try
            {
                using (var context = new ZvsContext(WebApi2Plugin.EntityContextConnection))
                {
                    var command = await context.Commands.FirstOrDefaultAsync(o => o.Id == key);

                    if (command == null)
                        return NotFound();

                    var result = await WebApi2Plugin.RunCommandAsync(command.Id, arg1, arg2, CancellationToken.None);
                    if (result.HasError)
                        return BadRequest(result.Message); 

                    return Ok(result.Message);
                }

            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }
        }
 public TriggerEditorWindow(Int64 deviceValueTriggerId, ZvsContext context)
 {
      Log = new DatabaseFeedback(_app.EntityContextConnection) { Source = "Trigger Editor" };
     _context = context;
     _deviceValueTriggerId = deviceValueTriggerId;
     InitializeComponent();
 }
        public async Task RegisterAsyncNewTest()
        {
            //arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());
            var dsb = new DeviceSettingBuilder(dbConnection);

            var deviceSetting = new DeviceSetting
            {
                Name = "Unit Test Device Setting",
                UniqueIdentifier = "DEVICE_SETTING1"
            };

            //act
            var result = await dsb.RegisterAsync(deviceSetting, CancellationToken.None);

            DeviceSetting setting;
            using (var context = new ZvsContext(dbConnection))
            {
                setting =
                    await
                        context.DeviceSettings.FirstOrDefaultAsync(
                            o => o.UniqueIdentifier == deviceSetting.UniqueIdentifier);

            }

            //assert 
            Console.WriteLine(result.Message);
            Assert.IsFalse(result.HasError, result.Message);
            Assert.IsNotNull(setting, "Expected new device setting saved to DB");
        }
        public async Task RegisterAsyncNewDeviceTypeTest()
        {
            //arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var dtb = new DeviceTypeBuilder( dbConnection);
            var adapter = UnitTesting.CreateFakeAdapter();
            using (var context = new ZvsContext(dbConnection))
            {
                context.Adapters.Add(adapter);
                await context.SaveChangesAsync();
            }

            var dt = new DeviceType
            {
                AdapterId = adapter.Id,
                UniqueIdentifier = "UNIT_TEST_DEVICE_TYPE1",
                Name = "Unit Test Device Type"
            };

            //act
            var result = await dtb.RegisterAsync(adapter.AdapterGuid, dt, CancellationToken.None);

            //assert 
            Console.WriteLine(result.Message);
            Assert.IsFalse(result.HasError);
            Assert.IsTrue(dt.Id > 0, "Expected device type to have a database generated Id");
        }
        private async void LogUserControl_OnInitialized(object sender, EventArgs e)
        {
            // Do not load your data at design time.
            if (DesignerProperties.GetIsInDesignMode(this))
                return;

            await InitialLogEntryLoad();
            NotifyEntityChangeContext.ChangeNotifications<LogEntry>.OnEntityAdded += LogUserControl_OnEntityAdded;

            using (var context = new ZvsContext(App.EntityContextConnection))
            {
                //Load your data here and assign the result to the CollectionViewSource.
                var myCollectionViewSource = (CollectionViewSource)Resources["LogEntryViewSource"];
                myCollectionViewSource.Source = LogEntries;

                var dataView = CollectionViewSource.GetDefaultView(LogDataGrid.ItemsSource);
                //clear the existing sort order
                dataView.SortDescriptions.Clear();

                //create a new sort order for the sorting that is done lastly            
                var dir = ListSortDirection.Ascending;

                var option = await context.ProgramOptions.FirstOrDefaultAsync(o => o.UniqueIdentifier == "LOGDIRECTION");
                if (option != null && option.Value == "Descending")
                    dir = ListSortDirection.Descending;

                myCollectionViewSource.SortDescriptions.Clear();
                myCollectionViewSource.SortDescriptions.Add(new SortDescription("Datetime", dir));
            }
        }
        public async override Task<Result> ImportAsync(string fileName, CancellationToken cancellationToken)
        {
            var result = await ReadAsXmlFromDiskAsync<List<DeviceBackup>>(fileName);

            if (result.HasError)
                return Result.ReportError(result.Message);

            var backupDevices = result.Data;
            var importedCount = 0;

            using (var context = new ZvsContext(EntityContextConnection))
            {
                foreach (var d in await context.Devices.ToListAsync(cancellationToken))
                {
                    var dev = backupDevices.FirstOrDefault(o => o.NodeNumber == d.NodeNumber);
                    if (dev == null) continue;
                    
                    d.Name = dev.Name;
                    d.Location = dev.Location;
                    importedCount++;
                }

                var saveResult = await context.TrySaveChangesAsync(cancellationToken);

                if (saveResult.HasError)
                    return Result.ReportError(saveResult.Message);
            }

            return Result.ReportSuccess(string.Format("Restored {0} device names. File: '{1}'", importedCount, Path.GetFileName(fileName)));
        }
 public JavaScriptEditor()
 {
     Context = new ZvsContext(_app.EntityContextConnection);
     Log = new DatabaseFeedback(_app.EntityContextConnection) { Source = "Javascript Editor" };
     LogEntries = new ObservableCollection<LogEntry>();
     InitializeComponent();
 }
        public override async Task<Result> ExportAsync(string fileName, CancellationToken cancellationToken)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                var existingTriggers = await context.DeviceValueTriggers
                    .ToListAsync(cancellationToken);

                var backupTriggers = new List<TriggerBackup>();
                foreach (var o in existingTriggers)
                {
                    var trigger = new TriggerBackup
                    {
                        Name = o.Name,
                        isEnabled = o.IsEnabled,
                        DeviceValueName = o.DeviceValue.Name,
                        NodeNumber = o.DeviceValue.Device.NodeNumber,
                        StoredCommand = await StoredCmdBackup.ConvertToBackupCommand(o),
                        Operator = (int?) o.Operator,
                        Value = o.Value
                    };
                    backupTriggers.Add(trigger);
                }

                var saveResult = await SaveAsXmlToDiskAsync(backupTriggers, fileName);

                if (saveResult.HasError)
                    return Result.ReportError(saveResult.Message);

                return Result.ReportSuccessFormat("Exported {0} triggers to {1}", backupTriggers.Count,
                    Path.GetFileName(fileName));
            }
        }
        public async override Task<Result> ExportAsync(string fileName, CancellationToken cancellationToken)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                var backupJs = await context.JavaScriptCommands
                    .Select(o => new JavaScriptBackup
                    {
                        Script = o.Script,
                        Name = o.Name,
                        UniqueIdentifier = o.UniqueIdentifier,
                        ArgumentType = (int)o.ArgumentType,
                        Description = o.Description,
                        CustomData1 = o.CustomData1,
                        CustomData2 = o.CustomData2,
                        Help = o.Help,
                        SortOrder = o.SortOrder
                    })
                    .ToListAsync(cancellationToken);

                var saveResult = await SaveAsXmlToDiskAsync(backupJs, fileName);

                if (saveResult.HasError)
                    return Result.ReportError(saveResult.Message);

                return Result.ReportSuccessFormat("Exported {0} JavaScript commands to {1}", backupJs.Count,
                    Path.GetFileName(fileName));
            }
        }
Ejemplo n.º 18
0
        public async Task<Result> ExecuteScriptAsync(string script, CancellationToken cancellationToken)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                JintEngine.SetValue("zvsContext", context);

                JintEngine.SetValue("logInfo", new Action<object>(LogInfo));
                JintEngine.SetValue("logWarn", new Action<object>(LogWarn));
                JintEngine.SetValue("logError", new Action<object>(LogError));
                JintEngine.SetValue("setTimeout", new Action<string, double>(SetTimeout));
                JintEngine.SetValue("shell", new Func<string, string, System.Diagnostics.Process>(Shell));
                
                JintEngine.SetValue("runDeviceNameCommandName", new Func<string, string, string, Result>(RunDeviceNameCommandName));
                JintEngine.SetValue("runCommand", new Func<int, string, string, Result>(RunCommand));
                
                JintEngine.SetValue("require", new Action<string>(Require));

                JintEngine.SetValue("mappath", new Func<string, string>(MapPath));
                try
                {
                    //pull out import statements
                    //import them into the JintEngine by running each script
                    //then run the JintEngine as normal

                    var result = await Task.Run(() => JintEngine.Execute(script), cancellationToken);
                    return Result.ReportSuccessFormat("JavaScript execution complete. {0}", result);
                }
                catch (Exception ex)
                {
                    return Result.ReportErrorFormat("JavaScript execution error. {0}", ex.Message);
                }
            }
        }
        public async Task<Result> RegisterAsync(int deviceId, DeviceCommand deviceCommand, CancellationToken cancellationToken)
        {
            if (deviceCommand == null)
                return Result.ReportError("Device command is null");

            using (var context = new ZvsContext(EntityContextConnection))
            {
                var device = await context.Devices.FirstOrDefaultAsync(o => o.Id == deviceId, cancellationToken);

                if(device == null )
                    return Result.ReportError("Invalid device id");

                //Does device type exist? 
                var existingDc = await context.DeviceCommands
                    .Include(o => o.Options)
                    .FirstOrDefaultAsync(c => c.UniqueIdentifier == deviceCommand.UniqueIdentifier &&
                                              c.DeviceId == deviceId, cancellationToken);

                if (existingDc == null)
                {
                    device.Commands.Add(deviceCommand);
                    return await context.TrySaveChangesAsync(cancellationToken);
                }

                var changed = false;
                PropertyChangedEventHandler handler = (s, a) => changed = true;
                existingDc.PropertyChanged += handler;

                existingDc.ArgumentType = deviceCommand.ArgumentType;
                existingDc.CustomData1 = deviceCommand.CustomData1;
                existingDc.CustomData2 = deviceCommand.CustomData2;
                existingDc.Description = deviceCommand.Description;
                existingDc.Name = deviceCommand.Name;
                existingDc.Help = deviceCommand.Help;
                existingDc.SortOrder = deviceCommand.SortOrder;

                existingDc.PropertyChanged -= handler;

                var addedOptions = deviceCommand.Options.Where(option => existingDc.Options.All(o => o.Name != option.Name)).ToList();
                foreach (var option in addedOptions)
                {
                    existingDc.Options.Add(option);
                    changed = true;
                }

                var removedOptions = existingDc.Options.Where(option => deviceCommand.Options.All(o => o.Name != option.Name)).ToList();
                foreach (var option in removedOptions)
                {
                    context.CommandOptions.Local.Remove(option);
                    changed = true;
                }

                if (changed)
                    return await context.TrySaveChangesAsync(cancellationToken);

                return Result.ReportSuccess("Nothing to update");
            }
        }
Ejemplo n.º 20
0
 public void TestMethod1()
 {
     using (var context = new ZvsContext(new ZvsEntityContextConnection()))
     {
         var device = UnitTesting.CreateFakeDevice();
         context.Devices.Add(device);
         context.SaveChanges();
     }
 }
 public ScheduledTaskCreator()
 {
     _context = new ZvsContext(_app.EntityContextConnection);
     Log = new DatabaseFeedback(_app.EntityContextConnection) { Source = "Scheduled Task Editor" };
     InitializeComponent();
     NotifyEntityChangeContext.ChangeNotifications<ScheduledTask>.OnEntityAdded += ScheduledTaskCreator_onEntityAdded;
     NotifyEntityChangeContext.ChangeNotifications<ScheduledTask>.OnEntityDeleted += ScheduledTaskCreator_onEntityDeleted;
     NotifyEntityChangeContext.ChangeNotifications<ScheduledTask>.OnEntityUpdated += ScheduledTaskCreator_onEntityUpdated;
 }
        public SceneProperties()
        {
            SceneId = 0;
            Context = new ZvsContext(_app.EntityContextConnection);
            Log = new DatabaseFeedback(_app.EntityContextConnection) { Source = "Scene Properties" };

            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) return;
            InitializeComponent();
        }
        public TriggerGridUc()
        {
            _context = new ZvsContext(_app.EntityContextConnection);
            Log = new DatabaseFeedback(_app.EntityContextConnection) { Source = "Trigger Editor" };
            InitializeComponent();

            NotifyEntityChangeContext.ChangeNotifications<DeviceValueTrigger>.OnEntityAdded += TriggerGridUC_onEntityAdded;
            NotifyEntityChangeContext.ChangeNotifications<DeviceValueTrigger>.OnEntityDeleted += TriggerGridUC_onEntityDeleted;
            NotifyEntityChangeContext.ChangeNotifications<DeviceValueTrigger>.OnEntityUpdated += TriggerGridUC_onEntityUpdated;
        }
        public DeviceValues(int deviceId)
        {
            DeviceId = deviceId;
            _context = new ZvsContext(_app.EntityContextConnection);
            Log = new DatabaseFeedback(_app.EntityContextConnection) { Source = "Device Values Viewer" };
            InitializeComponent();

            NotifyEntityChangeContext.ChangeNotifications<DeviceValue>.OnEntityAdded += DeviceValues_onEntityAdded;
            NotifyEntityChangeContext.ChangeNotifications<DeviceValue>.OnEntityUpdated += DeviceValues_onEntityUpdated;
            NotifyEntityChangeContext.ChangeNotifications<DeviceValue>.OnEntityDeleted += DeviceValues_onEntityDeleted;
        }
        private async void DeviceMultiselectWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            using (var context = new ZvsContext(ZvsEntityContextConnection))
            {
                var deviceViewSource = ((CollectionViewSource)(FindResource("DeviceViewSource")));

                //Fill the device combo box from db
                await context.Devices.Where(o => !DeviceIdsToExclude.Contains(o.Id)).ToListAsync();
                deviceViewSource.Source = context.Devices.Local.OrderBy(o => o.Name);
            }
        }
        public AdapterManagerWindow()
        {
            App = (App)Application.Current;
            Log = new DatabaseFeedback(App.EntityContextConnection) { Source = "Adapter Manager Window" };
            Context = new ZvsContext(App.EntityContextConnection);
            InitializeComponent();

            NotifyEntityChangeContext.ChangeNotifications<Adapter>.OnEntityAdded += AdapterManagerWindow_onEntityAdded;
            NotifyEntityChangeContext.ChangeNotifications<Adapter>.OnEntityDeleted += AdapterManagerWindow_onEntityDeleted;
            NotifyEntityChangeContext.ChangeNotifications<Adapter>.OnEntityUpdated += AdapterManagerWindow_onEntityUpdated;
        }
Ejemplo n.º 27
0
 private async void SettingWindow_Loaded_1(object sender, RoutedEventArgs e)
 {
     using (var context = new ZvsContext(_app.EntityContextConnection))
     {
         var option = await context.ProgramOptions.FirstOrDefaultAsync(o => o.UniqueIdentifier == "LOGDIRECTION");
         if (option != null && option.Value == "Descending")
             DecenLogOrderRadioBtn.IsChecked = true;
         else
             AcenLogOrderRadioBtn.IsChecked = true;
     }
     _isLoading = false;
 }
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List<ValidationResult>();

            using (var context = new ZvsContext())
                if (context.DeviceSettingValues.Any(o => o.DeviceId == DeviceId && 
                    o.DeviceSettingId == DeviceSettingId && 
                    o.Id != Id))  //Check o.Id != this.Id so updates do not fail
                    results.Add(new ValidationResult("Device Setting Value name already exists", new[] { "Name" }));

            return results;
        }
        public async Task<Result> RegisterAsync(BuiltinCommand builtinCommand, CancellationToken cancellationToken)
        {
            if (builtinCommand == null)
                return Result.ReportError("builtinCommand is null");

            using (var context = new ZvsContext(EntityContextConnection))
            {
                var existingC = await context.BuiltinCommands.FirstOrDefaultAsync(o => o.UniqueIdentifier == builtinCommand.UniqueIdentifier, cancellationToken);
                var wasModified = false;
                if (existingC == null)
                {
                    context.BuiltinCommands.Add(builtinCommand);
                    wasModified = true;
                }
                else
                {
                    PropertyChangedEventHandler handler = (s, a) => wasModified = true;
                    existingC.PropertyChanged += handler;

                    existingC.Name = builtinCommand.Name;
                    existingC.CustomData1 = builtinCommand.CustomData1;
                    existingC.CustomData2 = builtinCommand.CustomData2;
                    existingC.ArgumentType = builtinCommand.ArgumentType;
                    existingC.Description = builtinCommand.Description;
                    existingC.Help = builtinCommand.Help;

                    existingC.PropertyChanged -= handler;

                    var addded =
                        builtinCommand.Options.Where(option => existingC.Options.All(o => o.Name != option.Name))
                            .ToList();
                    foreach (var option in addded)
                    {
                        existingC.Options.Add(option);
                        wasModified = true;
                    }

                    var removed =
                        existingC.Options.Where(option => builtinCommand.Options.All(o => o.Name != option.Name)).ToList();
                    foreach (var option in removed)
                    {
                        context.CommandOptions.Local.Remove(option);
                        wasModified = true;
                    }
                }

                if (wasModified)
                    return await context.TrySaveChangesAsync(cancellationToken);

                return Result.ReportSuccess("Nothing to update");
            }
        }
Ejemplo n.º 30
0
 private async void DecenLogOrderRadioBtn_Checked(object sender, RoutedEventArgs e)
 {
     AcenLogOrderRadioBtn.IsChecked = false;
     if (_isLoading) return;
     using (var context = new ZvsContext(_app.EntityContextConnection))
     {
         await ProgramOption.TryAddOrEditAsync(context, new ProgramOption()
         {
             UniqueIdentifier = "LOGDIRECTION",
             Value = "Descending"
         }, _app.Cts.Token);
     }
 }
        public async Task<Result> RegisterAsync(SceneSetting sceneSetting, CancellationToken cancellationToken)
        {
            if (sceneSetting == null)
                return Result.ReportError("sceneSetting is null");

            using (var context = new ZvsContext(EntityContextConnection))
            {
                var existingSetting = await context.SceneSettings
                    .Include(o => o.Options)
                    .FirstOrDefaultAsync(s => s.UniqueIdentifier == sceneSetting.UniqueIdentifier, cancellationToken);

                var changed = false;
                if (existingSetting == null)
                {
                    context.SceneSettings.Add(sceneSetting);
                    changed = true;
                }
                else
                {
                    //Update
                    PropertyChangedEventHandler handler = (s, a) => changed = true;
                    existingSetting.PropertyChanged += handler;

                    existingSetting.Name = sceneSetting.Name;
                    existingSetting.Description = sceneSetting.Description;
                    existingSetting.ValueType = sceneSetting.ValueType;
                    existingSetting.Value = sceneSetting.Value;

                    existingSetting.PropertyChanged -= handler;

                    var added = sceneSetting.Options.Where(option => existingSetting.Options.All(o => o.Name != option.Name)).ToList();
                    foreach (var option in added)
                    {
                        existingSetting.Options.Add(option);
                        changed = true;
                    }

                    var removed = existingSetting.Options.Where(option => sceneSetting.Options.All(o => o.Name != option.Name)).ToList();
                    foreach (var option in removed)
                    {
                        context.SceneSettingOptions.Local.Remove(option);
                        changed = true;
                    }
                }

                if (changed)
                    return await context.TrySaveChangesAsync(cancellationToken);

                return Result.ReportSuccess("Nothing to update");
            }
        }
Ejemplo n.º 32
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            using (var context = new ZvsContext())
                if (context.DeviceSettingValues.Any(o => o.DeviceId == DeviceId &&
                                                    o.DeviceSettingId == DeviceSettingId &&
                                                    o.Id != Id)) //Check o.Id != this.Id so updates do not fail
                {
                    results.Add(new ValidationResult("Device Setting Value name already exists", new[] { "Name" }));
                }

            return(results);
        }
Ejemplo n.º 33
0
        public async Task ReportAsync(LogEntry value, CancellationToken ct)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                context.LogEntries.Add(value);

                try
                {
                    await context.SaveChangesAsync(ct);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }
Ejemplo n.º 34
0
        //TODO: MOve to extension method...
        public async static Task<string> GetPropertyValueAsync(ZvsContext Context, Scene scene, string scenePropertyUniqueIdentifier)
        {
            //Find the property
            SceneSetting property = await Context.SceneSettings.FirstOrDefaultAsync(p => p.UniqueIdentifier == scenePropertyUniqueIdentifier);
            
            if (property == null)
                return string.Empty;

            Scene s2 = await Context.Scenes.Include(o=> o.SettingValues).FirstOrDefaultAsync(o => o.Id == scene.Id);

            if (s2 == null)
                return string.Empty;

            SceneSettingValue spv = s2.SettingValues.FirstOrDefault(o => o.SceneSetting == property);
                
            //Check to see if the property has been set yet, otherwise return the default value for this property.
            if (spv != null)
                return spv.Value;

            return property.Value; //default value
        }
Ejemplo n.º 35
0
        public static async Task <string> GetDevicePropertyValueAsync(ZvsContext context, Device device, string settingName)
        {
            var d2 = await context.Devices
                     .Include(o => o.DeviceSettingValues)
                     .FirstOrDefaultAsync(o => o.Id == device.Id);

            if (d2 == null)
            {
                return(string.Empty);
            }

            //See if the custom value is set.
            var dpv = d2.DeviceSettingValues.FirstOrDefault(o => o.DeviceSetting.UniqueIdentifier == settingName);

            if (dpv != null)
            {
                return(dpv.Value);
            }

            //default value from property
            var dp = await context.DeviceSettings.FirstOrDefaultAsync(o => o.UniqueIdentifier == settingName);

            return(dp != null ? dp.Value : string.Empty);
        }
Ejemplo n.º 36
0
        public static async Task SetTargetObjectNameAsync(this IStoredCommand storedCommand, ZvsContext context)
        {
            var sw = new Stopwatch();

            sw.Start();

            if (storedCommand.Command is BuiltinCommand)
            {
                #region Built-in Command
                var bc = storedCommand.Command as BuiltinCommand;

                switch (bc.UniqueIdentifier)
                {
                case "REPOLL_ME":
                {
                    var dId = 0;
                    int.TryParse(storedCommand.Argument, out dId);

                    var deviceToRepoll = await context.Devices.FirstOrDefaultAsync(d => d.Id == dId);

                    if (deviceToRepoll != null)
                    {
                        storedCommand.TargetObjectName = $"{deviceToRepoll.Location} {deviceToRepoll.Name}";
                    }

                    break;
                }

                case "GROUP_ON":
                case "GROUP_OFF":
                {
                    int gId;
                    int.TryParse(storedCommand.Argument, out gId);
                    var g = await context.Groups.FirstOrDefaultAsync(gr => gr.Id == gId);

                    if (g != null)
                    {
                        storedCommand.TargetObjectName = g.Name;
                    }

                    break;
                }

                case "RUN_SCENE":
                {
                    int sceneId;
                    int.TryParse(storedCommand.Argument, out sceneId);

                    var scene = await context.Scenes.FirstOrDefaultAsync(d => d.Id == sceneId);

                    if (scene != null)
                    {
                        storedCommand.TargetObjectName = scene.Name;
                    }
                    break;
                }

                default:
                    storedCommand.TargetObjectName = storedCommand.Argument;
                    break;
                }
                #endregion
            }
            else if (storedCommand.Command is DeviceCommand)
            {
                var device = await context.Devices.FirstOrDefaultAsync(o => o.Commands.Any(p => p.Id == storedCommand.Command.Id));

                storedCommand.TargetObjectName = $"{device.Location} {device.Name}";
            }
            else if (storedCommand.Command is DeviceTypeCommand)
            {
                int dId = int.TryParse(storedCommand.Argument2, out dId) ? dId : 0;
                var d   = await context.Devices.FirstOrDefaultAsync(o => o.Id == dId);

                storedCommand.TargetObjectName = d != null ? $"{d.Location} {d.Name}" : "Unknown Device";
            }
            else if (storedCommand.Command is JavaScriptCommand)
            {
                var jsCmd = storedCommand.Command as JavaScriptCommand;
                storedCommand.TargetObjectName = jsCmd.Name;
            }

            sw.Stop();
            Debug.WriteLine("SetTargetObjectNameAsync took " + sw.Elapsed.ToString());
        }
Ejemplo n.º 37
0
        public async Task <string> GetDeviceSettingAsync(string deviceSettingUniqueIdentifier, ZvsContext context)
        {
            //check if the value has been defined by the user for this device
            var definedSetting = await context.DeviceSettingValues.FirstOrDefaultAsync(o =>
                                                                                       o.DeviceSetting.UniqueIdentifier == deviceSettingUniqueIdentifier &&
                                                                                       o.Device.Id == Id);

            if (definedSetting != null)
            {
                return(definedSetting.Value);
            }

            //otherwise get default for the command
            var defaultSetting = await context.DeviceTypeSettings.FirstOrDefaultAsync(o =>
                                                                                      o.UniqueIdentifier == deviceSettingUniqueIdentifier);

            return(defaultSetting != null ? defaultSetting.Value : null);
        }