コード例 #1
0
        //[Test]
        //public void OutputForms_Get()
        //{
        //    var dbContext = TypiconDbContextFactory.Create();
        //    var outputForms = OutputFormsFactory.Create(dbContext);

        //    DeleteAllOutputDays(dbContext, TYPICON_ID);

        //    Result<LocalizedOutputDay> task = outputForms.GetDay(TYPICON_ID, new DateTime(2020, 1, 1), "cs-ru");

        //    Assert.IsTrue(task.Failure);
        //}

        private void DeleteAllOutputDays(TypiconDBContext dbContext, int typiconId)
        {
            var forms = dbContext.Set <OutputDay>().Where(c => c.TypiconId == typiconId);

            dbContext.Set <OutputDay>().RemoveRange(forms);

            dbContext.SaveChanges();
        }
コード例 #2
0
 public static MenologyRule GetMenologyRule(this TypiconDBContext dbContext, int typiconVersionId, DateTime date)
 {
     return((DateTime.IsLeapYear(date.Year))
         ? dbContext.Set <MenologyRule>().FirstOrDefault(c => c.TypiconVersionId == typiconVersionId &&
                                                         c.LeapDate.Day == date.Day &&
                                                         c.LeapDate.Month == date.Month)
         : dbContext.Set <MenologyRule>().FirstOrDefault(c => c.TypiconVersionId == typiconVersionId &&
                                                         c.Date.Day == date.Day &&
                                                         c.Date.Month == date.Month));
 }
コード例 #3
0
ファイル: UserStore.cs プロジェクト: AlexLunyov/TypiconOnline
 public async Task <User> FindByIdAsync(string userId, CancellationToken cancellationToken)
 {
     if (int.TryParse(userId, out int id))
     {
         return(await db.Set <User>().FindAsync(id));
     }
     else
     {
         return(await Task.FromResult((User)null));
     }
 }
コード例 #4
0
        public static async Task UpdateOutputFormAsync(this TypiconDBContext dbContext, OutputDay outputDay)
        {
            var outputDays = dbContext.Set <OutputDay>()
                             .Where(c => c.TypiconId == outputDay.TypiconId && c.Date.Date == outputDay.Date.Date);

            if (outputDays.Any())
            {
                dbContext.Set <OutputDay>().RemoveRange(outputDays);
            }

            dbContext.Set <OutputDay>().Add(outputDay);

            await dbContext.SaveChangesAsync();
        }
コード例 #5
0
        public static void UpdateOutputDay(this TypiconDBContext dbContext, OutputDay outputDay)
        {
            var outputDays = dbContext.Set <OutputDay>()
                             .Where(c => c.TypiconId == outputDay.TypiconId && c.Date.Date == outputDay.Date.Date);

            if (outputDays.Any())
            {
                dbContext.Set <OutputDay>().RemoveRange(outputDays);
            }

            dbContext.Set <OutputDay>().Add(outputDay);

            dbContext.SaveChanges();
        }
コード例 #6
0
        public Result <FileDownloadResponse> Export(int typiconVersionId)
        {
            var found = _dbContext.Set <TypiconVersion>().FirstOrDefault(c => c.Id == typiconVersionId);

            if (found != null)
            {
                var projection = _projector.Project(found);

                if (projection.Success)
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(TypiconVersionProjection));

                    using (MemoryStream stream = new MemoryStream())
                    {
                        serializer.Serialize(stream, projection.Value);

                        var response = new FileDownloadResponse(stream.ToArray()
                                                                , "application/xml"
                                                                , GetFileName(projection.Value.Name.ToString(), found.VersionNumber));

                        return(Result.Ok(response));
                    }
                }
            }

            return(Result.Fail <FileDownloadResponse>($"Устав с Id={typiconVersionId} не был найден."));
        }
コード例 #7
0
        public Result <RuleHandlerSettings> CreateRecursive(CreateRuleSettingsRequest request)
        {
            //обрабатываем только последовательности богослужений, не "переходящие" последовательности
            if (request.RuleMode == RuleMode.ModRule)
            {
                return(Decoratee(request));
            }

            var settings = _dbContext.Set <ScheduleSettings>()
                           .FirstOrDefault(c => c.TypiconVersionId == request.TypiconVersionId);

            if (settings != null)
            {
                bool success = FromDaysOfWeek(settings, request) ||
                               FromSigns(settings, request) ||
                               FromMenologies(settings, request) ||
                               FromTriodions(settings, request) ||
                               FromIncluded(settings, request);

                //exclude
                success = success && FromExcluded(settings, request);

                if (success)
                {
                    return(Decoratee(request));
                }
            }

            return(Result.Fail <RuleHandlerSettings>(""));
        }
コード例 #8
0
 public static bool IsModifiedYearExists(this TypiconDBContext dbContext, int typiconVersionId, int year)
 {
     lock (dbContext)
     {
         return(dbContext.Set <ModifiedYear>().Any(c => c.TypiconVersionId == typiconVersionId &&
                                                   c.Year == year));
     }
 }
コード例 #9
0
 /// <summary>
 /// Возвращает все непереходящие праздники
 /// </summary>
 /// <param name="dbContext"></param>
 /// <param name="typiconVersionId"></param>
 /// <returns></returns>
 public static IEnumerable <MenologyRule> GetAllModMenologyRules(this TypiconDBContext dbContext, int typiconVersionId)
 {
     return(dbContext.Set <MenologyRule>()
            .Where(c => c.TypiconVersionId == typiconVersionId &&
                   c.ModRuleDefinition != string.Empty)
            .ToList()
            .Where(c => !c.LeapDate.IsEmpty));
 }
コード例 #10
0
        /// <summary>
        /// Возвращает указанную версию Устава (опубликованную или черновик).
        /// </summary>
        /// <param name="typiconVersionId"></param>
        /// <returns></returns>
        public static Result <TypiconVersion> GetTypiconVersion(this TypiconDBContext dbContext, int typiconId)
        {
            var version = dbContext.Set <TypiconVersion>().FirstOrDefault(c => c.TypiconId == typiconId);

            return((version != null)
                ? Result.Ok(version)
                : Result.Fail <TypiconVersion>("Указанный Устав либо не существует, либо не существует его опубликованная версия."));
        }
コード例 #11
0
        public static TriodionRule GetTriodionRule(this TypiconDBContext dbContext, int typiconVersionId, DateTime date)
        {
            var currentEaster = dbContext.GetCurrentEaster(date.Year);

            int daysFromEaster = date.Date.Subtract(currentEaster.Date).Days;

            return(dbContext.Set <TriodionRule>()
                   .FirstOrDefault(c => c.TypiconVersionId == typiconVersionId && c.DaysFromEaster == daysFromEaster));
        }
コード例 #12
0
        public Repository(TypiconDBContext dbContext)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException("TypiconDBContext in Repository");
            }

            objectSet = dbContext.Set <DomainType>();
        }
コード例 #13
0
        /// <summary>
        /// Возвращает указанную версию Устава (опубликованную или черновик).
        /// </summary>
        /// <param name="typiconVersionId"></param>
        /// <returns></returns>
        public static Result <TypiconVersion> GetTypiconVersion(this TypiconDBContext dbContext, int typiconId, TypiconVersionStatus status)
        {
            var version = dbContext.Set <TypiconVersion>()
                          .FirstOrDefault(c => (status == TypiconVersionStatus.Draft)
                                        ? c.TypiconId == typiconId && c.BDate == null && c.EDate == null
                                        : c.TypiconId == typiconId && c.BDate != null && c.EDate == null);

            return((version != null)
                ? Result.Ok(version)
                : Result.Fail <TypiconVersion>("Указанный Устав либо не существует, либо не существует его версия."));
        }
コード例 #14
0
        public static DateTime GetCurrentEaster(this TypiconDBContext dbContext, int year)
        {
            EasterItem easter = dbContext.Set <EasterItem>().FirstOrDefault(c => c.Date.Year == year);

            if (easter == null)
            {
                throw new NullReferenceException($"День празднования Пасхи не определен для года {year}.");
            }

            return(easter.Date);
        }
コード例 #15
0
        public static Result <TypiconClaim> GetTypiconClaim(this TypiconDBContext dbContext, int id)
        {
            var found = dbContext.Set <TypiconClaim>().FirstOrDefault(c => c.Id == id);

            if (found != null)
            {
                return(Result.Ok(found));
            }

            return(Result.Fail <TypiconClaim>($"Заявка на создание Устава с заданным Id={id} не была найдена."));
        }
コード例 #16
0
 private List <TriodionWorshipProjection> GetTriodions()
 {
     return(_dbContext.Set <TriodionDay>()
            .SelectMany(c => c.DayWorships)
            .Select(d => new TriodionWorshipProjection()
     {
         Id = d.Id,
         DaysFromEaster = (d.Parent as TriodionDay).DaysFromEaster,
         IsCelebrating = d.IsCelebrating,
         UseFullName = d.UseFullName,
         WorshipName = (d.WorshipName != null) ? new ItemTextStyled(d.WorshipName) : default,
コード例 #17
0
        public void Delete_Test()
        {
            var optionsBuilder = new DbContextOptionsBuilder <TypiconDBContext>();

            //SQLite connection
            var connectionString = @"FileName=data\SQLiteDB.db";

            optionsBuilder.UseSqlite(connectionString);

            var context = new TypiconDBContext(optionsBuilder.Options);

            var years = context.Set <ModifiedYear>()
                        .Where(c => c.TypiconVersionId == 1)
                        .Include(c => c.ModifiedRules)
                        .AsNoTracking();

            if (years != null)
            {
                context.Set <ModifiedYear>().RemoveRange(years);
            }
        }
コード例 #18
0
        public static async Task ClearOutputFormsAsync(this TypiconDBContext dbContext, int typiconId, bool deleteModifiedOutputDays)
        {
            //var query = $"DELETE FROM OUTPUTDAY WHERE TypiconId={typiconId} ";
            //int numberOfRowDeleted = await dbContext.Database.ExecuteSqlRawAsync(query);

            var days = dbContext.Set <OutputDay>().Where(c => c.TypiconId == typiconId);

            //если оставляем измененные вручную выходные фомры
            if (!deleteModifiedOutputDays)
            {
                //выбираем только те, у которых ModifiedDate == null
                //и не существует изменных вручную дочерних служб
                days = days.Where(c => c.ModifiedDate == null)
                       .Where(c => !c.Worships.Any(e => e.ModifiedDate != null));
            }

            //var list = days.ToList();

            dbContext.Set <OutputDay>().RemoveRange(days.ToList());

            await dbContext.SaveChangesAsync();
        }
コード例 #19
0
        public static async Task AddTypiconVersionAsync(this TypiconDBContext dbContext, TypiconVersion version)
        {
            dbContext.Set <TypiconVersion>().Add(version);

            var iHasIds = dbContext.ChangeTracker.Entries()
                          .Where(c => c.State == EntityState.Added &&
                                 c.IsKeySet &&
                                 c.Entity is ITypiconVersionChild child &&
                                 child.TypiconVersionId == version.Id);

            //.Select(c => c.Entity as ITypiconVersionChild);

            foreach (var entry in iHasIds)
            {
                //entry.
                (entry.Entity as ITypiconVersionChild).Id = default(int);
                //entry.Id = default(int);
            }

            dbContext.Set <TypiconVersion>().Update(version);

            await dbContext.SaveChangesAsync();
        }
コード例 #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="typiconVersionId"></param>
        /// <param name="year"></param>
        /// <returns>0 = не существует,
        /// 1 = существутет, но еще не вычислен,
        /// 2 = существует и вычислен</returns>
        public static int IsCalcModifiedYearExists(this TypiconDBContext dbContext, int typiconVersionId, int year)
        {
            var found = dbContext.Set <ModifiedYear>()
                        .FirstOrDefault(c => c.TypiconVersionId == typiconVersionId && c.Year == year);

            int result = 0;

            if (found != null)
            {
                result = (found.IsCalculated) ? 2 : 1;
            }

            return(result);
        }
コード例 #21
0
        public Result Import(byte[] file)
        {
            try
            {
                var xml = Encoding.UTF8.GetString(file);

                var projection = _serializer.Deserialize <TypiconVersionProjection>(xml);

                var entity = _projector.Project(projection);

                _dbContext.Set <TypiconEntity>().Add(entity.Value);

                int i = _dbContext.SaveChanges();

                return(Result.Ok());
            }
            catch (Exception ex)
            {
                return(Result.Fail(ex.Message));
            }
        }
コード例 #22
0
        public static async Task RemoveTypiconClaimAsync(this TypiconDBContext dbContext, TypiconClaim claim)
        {
            dbContext.Set <TypiconClaim>().Remove(claim);

            await dbContext.SaveChangesAsync();
        }
コード例 #23
0
        public static async Task AddTypiconEntityAsync(this TypiconDBContext dbContext, TypiconEntity entity)
        {
            dbContext.Set <TypiconEntity>().Add(entity);

            await dbContext.SaveChangesAsync();
        }
コード例 #24
0
ファイル: Migration.cs プロジェクト: AlexLunyov/TypiconOnline
        private async Task Migrate()
        {
            var roleAdmin = new Role()
            {
                Name = "Администратор", SystemName = "admin"
            };

            _dbContext.Set <Role>().Add(roleAdmin);
            var roleEditor = new Role()
            {
                Name = "Уставщик", SystemName = "editor"
            };

            _dbContext.Set <Role>().Add(roleEditor);
            var roleTypesetter = new Role()
            {
                Name = "Редактор", SystemName = "typesetter"
            };

            _dbContext.Set <Role>().Add(roleTypesetter);

            Commit();

            var user = new User()
            {
                UserName = "******",
                Email    = "*****@*****.**",
            };

            user.UserRoles = new List <UserRole>()
            {
                new UserRole()
                {
                    Role = roleAdmin, User = user
                },
                new UserRole()
                {
                    Role = roleEditor, User = user
                },
                new UserRole()
                {
                    Role = roleTypesetter, User = user
                }
            };

            await _userCreationService.CreateUser(user, "eCa6?&OpM/");

            var typicon = new TypiconEntity()
            {
                Owner = user
            };

            _dbContext.Set <TypiconEntity>().Add(typicon);
            Commit();

            var typiconEntity = new TypiconVersion()
            {
                Name = new ItemText()
                {
                    Items = new List <ItemTextUnit>()
                    {
                        new ItemTextUnit("cs-ru", "Типикон")
                    }
                },
                DefaultLanguage = DEFAULT_LANGUAGE,
                TypiconId       = typicon.Id,

                //Делаем сразу опубликованную версию
                BDate = DateTime.Now
            };

            typicon.Versions.Add(typiconEntity);
            Commit();

            string folderPath = Path.Combine(FOLDER_PATH, TYPICON_NAME, "Sign");

            FileReader fileReader = new FileReader(folderPath);

            int i = 1;

            foreach (ScheduleDBDataSet.ServiceSignsRow row in _sh.DataSet.ServiceSigns.Rows)
            {
                SignMigrator signMigrator = new SignMigrator(row.Number);

                Sign sign = new Sign()
                {
                    //Id = signMigrator.NewId,
                    Priority         = signMigrator.Priority,
                    TypiconVersionId = typiconEntity.Id,
                    //Owner = typiconEntity,
                    IsTemplate        = row.IsTemplate,
                    RuleDefinition    = fileReader.Read(row.Name),
                    ModRuleDefinition = fileReader.Read(row.Name, "mod")
                };
                sign.SignName.AddOrUpdate(DEFAULT_LANGUAGE, row.Name);

                if (signMigrator.Number != null)
                {
                    sign.Number = (int)signMigrator.Number;
                }

                sign.SignName.AddOrUpdate(DEFAULT_LANGUAGE, row.Name);

                if (signMigrator.TemplateId != null)
                {
                    sign.Template   = typiconEntity.Signs.First(c => c.Number == signMigrator.TemplateId);
                    sign.IsAddition = true;
                }

                typiconEntity.Signs.Add(sign);

                i++;
            }

            Commit();

            MigrateMenologyDaysAndRules(typiconEntity);
            Commit();

            MigrateTriodionDaysAndRules(typiconEntity);
            Commit();

            MigrateCommonRules(typiconEntity);
            Commit();

            MigrateExplicitRules(typiconEntity);
            Commit();

            MigratePsalms();
            MigrateKathismas(typiconEntity);
        }
コード例 #25
0
 public Repository(TypiconDBContext typiconDBContext)
 {
     _typiconDBContext = typiconDBContext;
     _objectSet        = _typiconDBContext.Set <DomainType>();
 }
コード例 #26
0
        public static async Task UpdateTypiconEntityAsync(this TypiconDBContext dbContext, TypiconEntity typiconEntity)
        {
            dbContext.Set <TypiconEntity>().Update(typiconEntity);

            await dbContext.SaveChangesAsync();
        }
コード例 #27
0
        public static async Task UpdateTypiconVersionAsync(this TypiconDBContext dbContext, TypiconVersion version)
        {
            dbContext.Set <TypiconVersion>().Update(version);

            await dbContext.SaveChangesAsync();
        }
コード例 #28
0
        public static async Task UpdateModifiedYearAsync(this TypiconDBContext dbContext, ModifiedYear modifiedYear)
        {
            dbContext.Set <ModifiedYear>().Update(modifiedYear);

            await dbContext.SaveChangesAsync();
        }
コード例 #29
0
        public static void UpdateModifiedYear(this TypiconDBContext dbContext, ModifiedYear modifiedYear)
        {
            dbContext.Set <ModifiedYear>().Update(modifiedYear);

            dbContext.SaveChanges();
        }
コード例 #30
0
        public static bool IsOutputDayExists(this TypiconDBContext dbContext, int typiconId, DateTime date)
        {
            var found = dbContext.Set <OutputDay>().FirstOrDefault(c => c.TypiconId == typiconId && c.Date.Date == date.Date);

            return(found != null);
        }