本文整理汇总了C#中zvs.DataModel.ZvsContext.TrySaveChangesAsync方法的典型用法代码示例。如果您正苦于以下问题:C# ZvsContext.TrySaveChangesAsync方法的具体用法?C# ZvsContext.TrySaveChangesAsync怎么用?C# ZvsContext.TrySaveChangesAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zvs.DataModel.ZvsContext
的用法示例。
在下文中一共展示了ZvsContext.TrySaveChangesAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RegisterAsync
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");
}
}
示例2: RegisterAsync
public async Task<Result> RegisterAsync(DeviceValue deviceValue, Device device, CancellationToken cancellationToken)
{
if (deviceValue == null)
return Result.ReportError("You must send a device value when registering a device value!");
if (device == null)
return Result.ReportError("You must send a device when registering a device value!");
using (var context = new ZvsContext(EntityContextConnection))
{
var existingDv =
await
context.DeviceValues.FirstOrDefaultAsync(o => o.UniqueIdentifier == deviceValue.UniqueIdentifier
&& o.DeviceId == device.Id, cancellationToken);
if (existingDv == null)
{
//NEW VALUE
context.DeviceValues.Add(deviceValue);
return await context.TrySaveChangesAsync(cancellationToken);
}
var hasChanged = false;
PropertyChangedEventHandler action = (s, a) => hasChanged = true;
existingDv.PropertyChanged += action;
existingDv.CommandClass = deviceValue.CommandClass;
existingDv.CustomData1 = deviceValue.CustomData1;
existingDv.CustomData2 = deviceValue.CustomData2;
existingDv.Genre = deviceValue.Genre;
existingDv.Index = deviceValue.Index;
existingDv.IsReadOnly = deviceValue.IsReadOnly;
existingDv.Description = deviceValue.Description;
existingDv.Name = deviceValue.Name;
existingDv.ValueType = deviceValue.ValueType;
existingDv.Value = deviceValue.Value;
existingDv.IsReadOnly = deviceValue.IsReadOnly;
existingDv.PropertyChanged -= action;
if (hasChanged)
{
return await context.TrySaveChangesAsync(cancellationToken);
}
return Result.ReportSuccess("Nothing to update");
}
}
示例3: TryAddOrEditAsync
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();
}
示例4: ImportAsync
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)));
}
示例5: RegisterAsync
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");
}
}
示例6: RegisterAsync
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");
}
}
示例7: ResetBtn_Click_1
private async void ResetBtn_Click_1(object sender, RoutedEventArgs e)
{
using (var context = new ZvsContext(_app.EntityContextConnection))
{
var scene = await context.Scenes.FirstOrDefaultAsync(sc => sc.Id == SceneId);
if (scene == null) return;
scene.IsRunning = false;
var result = await context.TrySaveChangesAsync(_app.Cts.Token);
if (result.HasError)
await Log.ReportErrorFormatAsync(_app.Cts.Token, "Error resetting scene. {0}", result.Message);
}
}
示例8: AddSensor
private async Task AddSensor(MqttMsgPublishEventArgs e)
{
var name = e.Topic;
var value = System.Text.UTF8Encoding.UTF8.GetString(e.Message);
using (ZvsContext context = new ZvsContext())
{
context.Devices
.FirstOrDefaultAsync(
d => d.Type.Adapter.AdapterGuid == this.AdapterGuid &&
d.Name == name).ContinueWith(t =>
{
Device dev = t.Result;
if (dev == null)
{
log.Info("New MQTT device found, registering:" + name);
dev = new Device
{
////NodeNumber =
//// rnd.Next((int) byte.MinValue + 100, (int) byte.MaxValue),
DeviceTypeId = SensorTypeId,
Name = name,
CurrentLevelInt = 0,
CurrentLevelText = value
};
//dev.Commands.Add(motionCommand);
context.Devices.Add(dev);
context.TrySaveChangesAsync().ContinueWith(tt =>
{
if (tt.Result.HasError)
ZvsEngine.log.Error(tt.Result.Message);
}).Wait();
}
AddOrUpdateValue(name, System.DateTime.Now.ToString(), dev.Id, DataType.STRING,
"Date", "Audit", context);
AddOrUpdateValue(name, value, dev.Id, DataType.STRING, "Value", "MQTT", context);
AddOrUpdateValue(name, e.QosLevel.ToString(), dev.Id, DataType.BYTE, "QosLevel",
"MQTT", context);
AddOrUpdateValue(name, e.Topic, dev.Id, DataType.STRING, "Topic", "MQTT",
context);
AddOrUpdateValue(name, e.Retain.ToString(), dev.Id, DataType.BOOL, "Retain",
"MQTT",
context);
}).Wait();
}
}
示例9: AddMQTTAdDevice
private async Task AddMQTTAdDevice()
{
using(ZvsContext context = new ZvsContext())
{
context.Devices.FirstOrDefaultAsync(
d => d.Type.Adapter.AdapterGuid == this.AdapterGuid && d.Name == SystemTopic).ContinueWith(t =>
{
if (t.Result == null)
{
log.Info("MQTT broker not found, registering.");
Device dev = new Device
{
//NodeNumber = rnd.Next((int) byte.MinValue + 100, (int) byte.MaxValue),
DeviceTypeId = SensorTypeId,
Name = SystemTopic,
};
//dev.Commands.Add(motionCommand);
context.Devices.Add(dev);
context.TrySaveChangesAsync().ContinueWith(tt =>
{
if (tt.Result.HasError)
ZvsEngine.log.Error(tt.Result.Message);
AddCommand(dev.Id, "Publish to Broker", context);
}).Wait();
}
}).Wait();
}
}
示例10: RefreshTriggerDescripitions
//TODO: MOVE TO SAVE CHANGES
public async Task RefreshTriggerDescripitions()
{
using (var context = new ZvsContext(EntityContextConnection))
{
var triggers = await context.DeviceValueTriggers
.Include(o => o.DeviceValue)
.Include(o => o.DeviceValue.Device)
.ToListAsync();
foreach (var trigger in triggers)
trigger.SetDescription();
var result = await context.TrySaveChangesAsync(Cts.Token);
if (result.HasError)
await Log.ReportErrorAsync(result.Message, Cts.Token);
}
}
示例11: ImportAsync
public async override Task<Result> ImportAsync(string fileName, CancellationToken cancellationToken)
{
var result = await ReadAsXmlFromDiskAsync<List<ScheduledTaskBackup>>(fileName);
if (result.HasError)
return Result.ReportError(result.Message);
var skippedCount = 0;
var newSTs = new List<DataModel.ScheduledTask>();
using (var context = new ZvsContext(EntityContextConnection))
{
var existingScheduledTasks = await context.ScheduledTasks
.ToListAsync(cancellationToken);
foreach (var scheduledTaskBackup in result.Data)
{
if (existingScheduledTasks.Any(o => o.Name == scheduledTaskBackup.Name))
{
skippedCount++;
continue;
}
var cmd =
await
StoredCmdBackup.RestoreStoredCommandAsync(context, scheduledTaskBackup.StoredCommand,
cancellationToken);
if (cmd == null) continue;
var task = new DataModel.ScheduledTask
{
Argument = cmd.Argument,
Argument2 = cmd.Argument2,
CommandId = cmd.CommandId,
Name = scheduledTaskBackup.Name,
IsEnabled = scheduledTaskBackup.isEnabled,
RepeatIntervalInDays = scheduledTaskBackup.RecurDays ?? 0,
RepeatIntervalInMonths = scheduledTaskBackup.RecurMonth ?? 0,
RepeatIntervalInSeconds = scheduledTaskBackup.RecurSeconds ?? 0,
RepeatIntervalInWeeks = scheduledTaskBackup.RecurWeeks ?? 0,
SortOrder = scheduledTaskBackup.sortOrder,
StartTime = scheduledTaskBackup.startTime ?? DateTime.Now
};
if (scheduledTaskBackup.Frequency != null)
task.TaskType = (ScheduledTaskType)scheduledTaskBackup.Frequency;
if (scheduledTaskBackup.DaysOfMonthToActivate != null)
task.DaysOfMonthToActivate = (DaysOfMonth)scheduledTaskBackup.DaysOfMonthToActivate;
if (scheduledTaskBackup.DaysOfWeekToActivate != null)
task.DaysOfWeekToActivate = (DaysOfWeek)scheduledTaskBackup.DaysOfWeekToActivate;
newSTs.Add(task);
}
context.ScheduledTasks.AddRange(newSTs);
if (newSTs.Count > 0)
{
var saveResult = await context.TrySaveChangesAsync(cancellationToken);
if (saveResult.HasError)
return Result.ReportError(saveResult.Message);
foreach (var task in newSTs)
{
task.SetDescription();
await task.SetTargetObjectNameAsync(context);
}
var r = await context.TrySaveChangesAsync(cancellationToken);
if (r.HasError)
return Result.ReportError(r.Message);
}
}
return Result.ReportSuccess(string.Format("Imported {0} scheduled tasks, skipped {1} from {2}", newSTs.Count, skippedCount, Path.GetFileName(fileName)));
}
示例12: DisablePluginAsync
public async Task<Result> DisablePluginAsync(Guid pluginGuid, CancellationToken cancellationToken)
{
var plugin = FindZvsPlugin(pluginGuid);
if (plugin == null)
return Result.ReportErrorFormat("Unable to disable plugin with Guid of {0}", pluginGuid);
plugin.IsEnabled = false;
await plugin.StopAsync();
using (var context = new ZvsContext(EntityContextConnection))
{
//Save Database Value
var a = await context.Plugins.FirstOrDefaultAsync(o => o.PluginGuid == pluginGuid, cancellationToken);
if (a != null)
a.IsEnabled = false;
await context.TrySaveChangesAsync(cancellationToken);
}
return Result.ReportSuccess();
}
示例13: ImportAsync
public async override Task<Result> ImportAsync(string fileName, CancellationToken cancellationToken)
{
var result = await ReadAsXmlFromDiskAsync<List<GroupBackup>>(fileName);
if (result.HasError)
return Result.ReportError(result.Message);
var skippedCount = 0;
var newGroups = new List<Group>();
using (var context = new ZvsContext(EntityContextConnection))
{
var existingGroups = await context.Groups.ToListAsync(cancellationToken);
var existingDevice = await context.Devices.ToListAsync(cancellationToken);
foreach (var backupGroup in result.Data)
{
if (existingGroups.Any(o => o.Name == backupGroup.Name))
{
skippedCount++;
continue;
}
var group = new Group();
group.Name = backupGroup.Name;
var devices = existingDevice.Where(o => backupGroup.NodeNumbers.Contains(o.NodeNumber));
foreach (var device in devices)
group.Devices.Add(device);
newGroups.Add(group);
}
context.Groups.AddRange(newGroups);
if (newGroups.Count > 0)
{
var saveResult = await context.TrySaveChangesAsync(cancellationToken);
if (saveResult.HasError)
return Result.ReportError(saveResult.Message);
}
}
return Result.ReportSuccess(
$"Imported {newGroups.Count} groups, skipped {skippedCount} from {Path.GetFileName(fileName)}");
}
示例14: ImportAsync
public override async Task<Result> ImportAsync(string fileName, CancellationToken cancellationToken)
{
var result = await ReadAsXmlFromDiskAsync<List<TriggerBackup>>(fileName);
if (result.HasError)
return Result.ReportError(result.Message);
var skippedCount = 0;
var newTriggers = new List<DeviceValueTrigger>();
using (var context = new ZvsContext(EntityContextConnection))
{
var existingTriggers = await context.DeviceValueTriggers.ToListAsync(cancellationToken);
var existingDeviceValues = await context.DeviceValues
.Include(o => o.Device)
.ToListAsync(cancellationToken);
foreach (var backupTrigger in result.Data)
{
if (existingTriggers.Any(o => o.Name == backupTrigger.Name))
{
skippedCount++;
continue;
}
var dv = existingDeviceValues.FirstOrDefault(o => o.Device.NodeNumber == backupTrigger.NodeNumber
&& o.Name == backupTrigger.DeviceValueName);
var cmd =
await
StoredCmdBackup.RestoreStoredCommandAsync(context, backupTrigger.StoredCommand,
cancellationToken);
if (dv == null || cmd == null) continue;
var dvTrigger = new DeviceValueTrigger
{
Name = backupTrigger.Name,
DeviceValue = dv,
IsEnabled = backupTrigger.isEnabled
};
dvTrigger.Name = backupTrigger.Name;
dvTrigger.Argument = cmd.Argument;
dvTrigger.Argument2 = cmd.Argument2;
dvTrigger.CommandId = cmd.CommandId;
if (backupTrigger.Operator != null)
dvTrigger.Operator = (TriggerOperator) backupTrigger.Operator;
dvTrigger.Value = backupTrigger.Value;
newTriggers.Add(dvTrigger);
}
context.DeviceValueTriggers.AddRange(newTriggers);
if (newTriggers.Count > 0)
{
var saveResult = await context.TrySaveChangesAsync(cancellationToken);
if (saveResult.HasError)
return Result.ReportError(saveResult.Message);
foreach (var cmd in newTriggers)
{
cmd.SetDescription();
await cmd.SetTargetObjectNameAsync(context);
cmd.SetTriggerDescription();
}
var r = await context.TrySaveChangesAsync(cancellationToken);
if (r.HasError)
return Result.ReportError(r.Message);
}
}
return
Result.ReportSuccess(
$"Imported {newTriggers.Count} triggers, skipped {skippedCount} from {Path.GetFileName(fileName)}");
}
示例15: AddNewDeviceToDatabase
private async Task AddNewDeviceToDatabase(byte nodeId)
{
#region Add device to database
using (var context = new ZvsContext(EntityContextConnection))
{
var ozwDevice = await context.Devices
.FirstOrDefaultAsync(d => d.Type.Adapter.AdapterGuid == AdapterGuid &&
d.NodeNumber == nodeId);
//If already have the device, don't install a duplicate
if (ozwDevice != null)
return;
ozwDevice = new Device
{
NodeNumber = nodeId,
DeviceTypeId = UnknownTypeId,
Name = "Unknown OpenZwave Device",
CurrentLevelInt = 0,
CurrentLevelText = ""
};
context.Devices.Add(ozwDevice);
var result = await context.TrySaveChangesAsync(CancellationToken);
if (result.HasError)
await Log.ReportErrorFormatAsync(CancellationToken, "Failed to save new device. {0}", result.Message);
}
#endregion
}