public Settings CreateSettings(Device device, string settingsData)
        {
            Settings lastSettings = GetLastSettings(device);

            Settings newSettings = new Settings
            {
                DeviceId = device.Id,
                SerializedSettings = settingsData,
                VersionNumber = (lastSettings == null) ? 1 : lastSettings.VersionNumber + 1,
                Date = DateTime.Now
            };

            _context.Settings.Add(newSettings);
            _context.SaveChanges();
            return newSettings;
        }
 public Settings GetSettings(Device device, long version)
 {
     return GetSettings(device).FirstOrDefault(x => x.VersionNumber == version);
 }
 public Settings GetLastSettings(Device device)
 {
     return GetSettings(device).OrderByDescending(x => x.VersionNumber).FirstOrDefault();
 }
 public IEnumerable<Settings> GetSettings(Device device)
 {
     return _context.Settings.Where(x => x.DeviceId == device.Id).OrderByDescending(x => x.VersionNumber);
 }
 public List<IndiagramForDevice> GetIndiagrams(Device device, long version)
 {
     return GetIndiagramsUser(device.UserId).Select(x => ToIndiagramForDevice(device, x, version)).OrderBy(x => x.Position).ToList();
 }
 public IndiagramForDevice GetIndiagram(Device device, long id, long version)
 {
     Indiagram indiagram = GetIndiagramUser(device.UserId, id);
     return indiagram == null ? null : ToIndiagramForDevice(device, indiagram, version);
 }
        private IndiagramForDevice ToIndiagramForDevice(Device device, Indiagram indiagram, IndiagramInfo info)
        {
            IndiagramState state = info.States.FirstOrDefault(s => s.DeviceId == device.Id);

            return ToIndiagramForDevice(indiagram, info, state);
        }
        private IndiagramForDevice ToIndiagramForDevice(Device device, Indiagram indiagram, long version)
        {
            IndiagramInfo info = indiagram.Infos.OrderByDescending(item => item.Version).FirstOrDefault(item => item.Version <= version);
            if (info == null)
            {
                return null;
            }

            return ToIndiagramForDevice(device, indiagram, info);
        }
        private IndiagramForDevice ToIndiagramForDevice(Device device, Indiagram indiagram, bool allowOpenedVersion)
        {
            IndiagramInfo info = indiagram.LastIndiagramInfo;
            if (info == null)
            {
                return null;
            }

            if (!allowOpenedVersion && IsVersionOpen(device.UserId, info.Version))
            {
                info = indiagram.Infos.OrderByDescending(item => item.Version).FirstOrDefault(item => !IsVersionOpen(device.UserId, item.Version));

                if (info == null)
                {
                    return null;
                }
            }

            return ToIndiagramForDevice(device, indiagram, info);
        }