Пример #1
0
        public static Dictionary <string, IEnumerable> SampleTestData(int maxRows,
                                                                      int minValue       = 1,
                                                                      int maxValue       = 100,
                                                                      int denominator    = 100,
                                                                      string dataSetName = "Data")
        {
            List <ExcelTestData>             values  = new List <ExcelTestData>();
            Dictionary <string, IEnumerable> results = new Dictionary <string, IEnumerable>();

            Random         random   = new Random();
            RandomDateTime randomdt = new RandomDateTime(1990, 1, 1);

            for (int i = 0; i < maxRows; i++)
            {
                int     r      = random.Next(minValue, maxValue);
                decimal result = Convert.ToDecimal((double)r / denominator);
                values.Add(new ExcelTestData()
                {
                    decimalvalue  = result,
                    datetimevalue = randomdt.Next()
                });
            }

            results.Add(dataSetName, values);
            return(results);
        }
Пример #2
0
 public static BlobInfoV1 Blob()
 {
     return(new BlobInfoV1
     {
         Id = IdGenerator.NextLong(),
         Group = RandomText.Name(),
         Name = RandomText.Name(),
         Size = RandomLong.NextLong(100, 100000),
         ContentType = RandomArray.Pick(new string[] { "text/plain", "application/binary", "application/json" }),
         CreateTime = DateTime.UtcNow,
         ExpireTime = RandomDateTime.NextDateTime(DateTime.UtcNow, new DateTime(2010, 1, 1)),
         Completed = RandomBoolean.NextBoolean()
     });
 }
Пример #3
0
 internal SerializedDataStorage()
 {
     try
     {
         _persons = SerializationManager.Deserialize <List <Person> >(FileFolderHelper.StorageFilePath);
     }
     catch (FileNotFoundException)
     {
         _persons = new List <Person>();
         for (int i = 0; i < 50; i++)
         {
             RandomDateTime random = new RandomDateTime();
             _persons.Add(new Person(random.GenRandomString(i), "Person_" + i, "user_" + i + "@gmail.com",
                                     random.GenRandomDateTime(new DateTime(1960 + i, i % 12 + 1, 1, 8, 30, 52), DateTime.Today)));
         }
         SaveChanges();
     }
 }
Пример #4
0
        public async Task ReturnsPublishedFundingTemplatesForGivenFundingStreamAndPeriod()
        {
            DateTime expectedPublishDate = new RandomDateTime();

            IEnumerable <PolicyApiClientModel.PublishedFundingTemplate> publishedFundingTemplates =
                new List <PolicyApiClientModel.PublishedFundingTemplate>
            {
                new PolicyApiClientModel.PublishedFundingTemplate()
                {
                    AuthorName      = "AuthName",
                    AuthorId        = "AuthId",
                    PublishDate     = expectedPublishDate,
                    PublishNote     = "SomeComments",
                    SchemaVersion   = "1.2",
                    TemplateVersion = "2.3"
                }
            };

            GivenApiPublishedFundingTemplates(_fundingStreamId, _fundingPeriodId, publishedFundingTemplates);

            OkObjectResult result = await WhenGetPublishedFundingTemplates(_fundingStreamId, _fundingPeriodId) as OkObjectResult;

            result
            .Should()
            .NotBeNull();

            PublishedFundingTemplate template = result.Value.As <IEnumerable <PublishedFundingTemplate> >().FirstOrDefault();

            template
            .Should()
            .NotBeNull();

            template
            .Should()
            .BeEquivalentTo(new PublishedFundingTemplate
            {
                AuthorName    = "AuthName",
                PublishNote   = "SomeComments",
                MinorVersion  = "3",
                MajorVersion  = "2",
                PublishDate   = expectedPublishDate,
                SchemaVersion = "1.2"
            });
        }
Пример #5
0
        public async Task DelegatesToRepositoryAndReturnsQueryResult()
        {
            string fundingPeriodId = NewRandomString();
            string fundingStreamId = NewRandomString();

            DateTime?expectedResult = new RandomDateTime();

            _publishedFundingRepository.Setup(_ => _.GetLatestPublishedDate(fundingStreamId, fundingPeriodId))
            .ReturnsAsync(expectedResult);

            OkObjectResult result = await _service.GetLatestPublishedDate(fundingStreamId, fundingPeriodId) as OkObjectResult;

            result?.Value
            .Should()
            .BeEquivalentTo(new LatestPublishedDate
            {
                Value = expectedResult
            });
        }
Пример #6
0
        public void EvictDeletesAllCachedFilesCreatedBeforeSuppliedDateTimeOffset()
        {
            string expectedEvictedFileOne   = NewRandomString();
            string expectedEvictedFileTwo   = NewRandomString();
            string expectedEvictedFileThree = NewRandomString();
            string expectedEvictedFileFour  = NewRandomString();

            DateTimeOffset evictBefore = new RandomDateTime();

            GivenTheMatchingFileCreatesBefore(evictBefore,
                                              expectedEvictedFileOne,
                                              expectedEvictedFileTwo,
                                              expectedEvictedFileThree,
                                              expectedEvictedFileFour);

            WhenTheFilesAreEvicted(evictBefore);

            ThenTheFilesWereDeleted(expectedEvictedFileOne,
                                    expectedEvictedFileTwo,
                                    expectedEvictedFileThree,
                                    expectedEvictedFileFour);
        }
Пример #7
0
        public async Task GetLatestPublishedDateGetsMaxUpdateAtForPublishedProvidersByFundingStreamAndPeriod()
        {
            string fundingPeriodId = NewRandomString();
            string fundingStreamId = NewRandomString();

            DateTime expectedLastPublishedDate = new RandomDateTime();

            GivenTheDynamicResultsForTheQuery(_ => _.QueryText?.Equals(@"SELECT MAX(c.updatedAt)
                                  FROM c
                                  WHERE c.documentType = 'PublishedProvider'
                                  AND c.deleted = false
                                  AND c.content.current.fundingStreamId = @fundingStreamId
                                  AND c.content.current.fundingPeriodId = @fundingPeriodId") == true &&
                                              HasParameter(_, "@fundingPeriodId", fundingPeriodId) &&
                                              HasParameter(_, "@fundingStreamId", fundingStreamId),
                                              JObject.Parse($"{{\"$1\" : \"{expectedLastPublishedDate.ToString(CultureInfo.InvariantCulture)}\"}}"));

            DateTime?actualLastPublishedDate = await _repository.GetLatestPublishedDate(fundingStreamId, fundingPeriodId);

            actualLastPublishedDate
            .Should()
            .BeCloseTo(expectedLastPublishedDate, 999);
        }
Пример #8
0
        public static void Main()
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            do
            {
                Console.Clear();
                List <Item>    items      = new List <Item>();
                RandomDateTime randomDate = new RandomDateTime();

                for (int i = 0; i < 100; i++)
                {
                    int choice = rnd.Next(0, 3);
                    try
                    {
                        // Равновероятностное создание объектов разных типов
                        if (choice == 0)
                        {
                            items.Add(new Cake(Helper.RandomName(rnd.Next(5, 15)), rnd.Next(0, 100001), rnd.Next(0, 201), randomDate.Next()));;
                        }
                        else if (choice == 1)
                        {
                            items.Add(new Electronics(Helper.RandomName(rnd.Next(5, 15)), rnd.Next(0, 100001), rnd.Next(0, 201), 14.1 * rnd.NextDouble() + 0.9));
                        }
                        else
                        {
                            items.Add(new Medicine(Helper.RandomName(rnd.Next(5, 15)), rnd.Next(0, 100001), rnd.Next(0, 201), Helper.IsAntibio()));
                        }
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("NullReferenceException found...");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                try
                {
                    Stock stock = new Stock(items);

                    Console.WriteLine("Список созданных объектов: \n");
                    Thread.Sleep(1000);
                    foreach (var item in items)
                    {
                        Console.WriteLine(item.ToString());
                    }

                    stock.SendItems(); // Отправка (сериализация) объектов
                    items = null;

                    Stock stock1 = new Stock(items); // Создание нового склада

                    Console.WriteLine("\n\nРезультат десериализации:\n");
                    Thread.Sleep(1500);
                    stock1.ReceiveItems(); // Получение (десериализация) объектов

                    SuperMarket superMarket = new SuperMarket();
                    OnlineStore onlineStore = new OnlineStore();
                    Mall        mall        = new Mall();


                    // Распределение объектов по различным типам магазинов
                    foreach (var item in stock1.allitems)
                    {
                        if (item.GetType() == typeof(Cake))
                        {
                            superMarket.AcceptItem(item);
                        }
                        else if (item.Name.Length < 10)
                        {
                            mall.AcceptItem(item);
                        }
                        else
                        {
                            onlineStore.AcceptItem(item);
                        }
                    }

                    // Сортировка объектов в разных магазинах согласно спецификации
                    superMarket.SortItems();
                    mall.SortItems();
                    onlineStore.SortItems();

                    // Вывод всех объектов на экран
                    Console.WriteLine("\n\n\nПредметы в онлайн магазине: \n");
                    Thread.Sleep(1500);
                    for (int i = 0; i < onlineStore.Count; i++)
                    {
                        Console.WriteLine(onlineStore[i]);
                    }
                    Console.WriteLine("\n\nПредметы в торговом центре:\n");
                    Thread.Sleep(1500);
                    for (int i = 0; i < mall.Count; i++)
                    {
                        Console.WriteLine(mall[i]);
                    }
                    Console.WriteLine("\n\nПредметы в супермаркете: \n");
                    Thread.Sleep(1500);
                    for (int i = 0; i < superMarket.Count; i++)
                    {
                        Console.WriteLine(superMarket[i]);
                    }
                }
                catch (NullReferenceException)
                {
                    Console.WriteLine("NullReferenceException found...");
                }
                catch (ArgumentNullException)
                {
                    Console.WriteLine("ArgumentNullException found");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                Console.WriteLine("\nНажмите ESC для завершения программы или другую клавишу для нового запуска\n");
            }while (Console.ReadKey().Key != ConsoleKey.Escape);
        }
Пример #9
0
        public void GeneratesCsvRows()
        {
            DateTime openedDate1 = new RandomDateTime();
            DateTime closedDate1 = new RandomDateTime();

            IEnumerable <PublishedProviderVersion> publishedProviderVersions =
                NewPublishedProviderVersions(ppv => ppv.WithProvider(
                                                 NewProvider(pr => pr
                                                             .WithSuccessor("successor1")
                                                             .WithName("prname1")
                                                             .WithLACode("lacode1")
                                                             .WithAuthority("laname1")
                                                             .WithURN("urn1")
                                                             .WithUKPRN("ukprn1")
                                                             .WithProviderType("pt1")
                                                             .WithProviderSubType("pst1")
                                                             .WithDateOpened(openedDate1)
                                                             .WithDateClosed(closedDate1)
                                                             .WithReasonEstablishmentOpened("openReason1")
                                                             .WithReasonEstablishmentClosed("closeReason1")
                                                             .WithTrustCode("trustCode1")
                                                             .WithTrustName("trustName1"))
                                                 )
                                             .WithAuthor(NewReference(auth => auth.WithName("author1")))
                                             .WithVariationReasons(new[] { VariationReason.LACodeFieldUpdated, VariationReason.MiddleSuperOutputAreaCodeFieldUpdated })
                                             .WithVersion(2)
                                             .WithProviderId("providerId")
                                             .WithPublishedProviderStatus(PublishedProviderStatus.Updated),
                                             ppv => ppv.WithProvider(
                                                 NewProvider(pr => pr
                                                             .WithSuccessor("")
                                                             .WithName("prname2")
                                                             .WithLACode("lacode2")
                                                             .WithAuthority("laname2")
                                                             .WithURN("urn2")
                                                             .WithUKPRN("ukprn2")
                                                             .WithDateOpened(null)
                                                             .WithDateClosed(null)
                                                             .WithReasonEstablishmentClosed("closeReason2")
                                                             .WithProviderType("pt2")
                                                             .WithProviderSubType("pst2")
                                                             .WithTrustCode("trustCode2")
                                                             .WithTrustName("trustName2")))
                                             .WithAuthor(NewReference(auth => auth.WithName("author2")))
                                             .WithVersion(1)
                                             .WithProviderId("providerId")
                                             .WithPublishedProviderStatus(PublishedProviderStatus.Released));

            dynamic[] expectedCsvRows =
            {
                new Dictionary <string, object>
                {
                    { "UKPRN",          "ukprn1"                                                   },
                    { "Provider Has Successor","True"                                                     },
                    { "Provider Data Changed","True"                                                     },
                    { "Provider Has Closed","True"                                                     },
                    { "Provider Has Opened","True"                                                     },
                    { "Variation Reason","LACodeFieldUpdated|MiddleSuperOutputAreaCodeFieldUpdated" },
                    { "Current URN",    "urn1"                                                     },
                    { "Current Provider Name","prname1"                                                  },
                    { "Current Provider Type","pt1"                                                      },
                    { "Current Provider Subtype","pst1"                                                     },
                    { "Current LA Code","lacode1"                                                  },
                    { "Current LA Name","laname1"                                                  },
                    { "Current Open Date",openedDate1.ToString("s")                                  },
                    { "Current Open Reason","openReason1"                                              },
                    { "Current Close Date",closedDate1.ToString("s")                                  },
                    { "Current Close Reason","closeReason1"                                             },
                    { "Current Successor Provider ID","successor1"                                               },
                    { "Current Trust Code","trustCode1"                                               },
                    { "Current Trust Name","trustName1"                                               },
                    { "Previous URN",   "urn2"                                                     },
                    { "Previous Provider Name","prname2"                                                  },
                    { "Previous Provider Type","pt2"                                                      },
                    { "Previous Provider Subtype","pst2"                                                     },
                    { "Previous LA Code","lacode2"                                                  },
                    { "Previous LA Name","laname2"                                                  },
                    { "Previous Close Date",null                                                       },
                    { "Previous Close Reason","closeReason2"                                             },
                    { "Previous Trust Code","trustCode2"                                               },
                    { "Previous Trust Name","trustName2"                                               },
                }
            };

            IEnumerable <IGrouping <string, PublishedProviderVersion> > publishedProviderVersionGroup
                = publishedProviderVersions.GroupBy(x => x.ProviderId);

            ExpandoObject[] transformProviderResultsIntoCsvRows = _transformation
                                                                  .Transform(publishedProviderVersionGroup)
                                                                  .ToArray();

            transformProviderResultsIntoCsvRows
            .Should()
            .BeEquivalentTo(expectedCsvRows,
                            cfg => cfg.WithStrictOrdering());
        }
Пример #10
0
        private static void SeedContas(ContasAPagarContext context)
        {
            if (!context.Boletos.Any())
            {
                #region Gera Novos Boletos

                Random         rand    = new Random();
                RandomDateTime randdt  = new RandomDateTime();
                int            tam     = rand.Next(1, 25);
                List <Boleto>  boletos = new List <Boleto>(tam);

                for (int x = 0; x < tam; x++)
                {
                    Boleto b = new Boleto();
                    b.DataAlteracao  = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null;
                    b.DataCriacao    = randdt.Next();
                    b.DataEmissao    = randdt.Next();
                    b.DataPagamento  = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null;
                    b.DataVencimento = randdt.Next();
                    b.FornecedorID   = context.Fornecedores.Find(rand.Next(1, context.Fornecedores.Count())).ID;
                    b.Juros          = rand.NextDouble() * rand.Next(250);

                    b.Multa           = rand.NextDouble() * rand.Next(250);
                    b.Status          = ((TipoStatusConta)rand.Next(2)).ToString();
                    b.TipoConta       = (int)TipoConta.Boleto;
                    b.UsuarioID       = context.Users.ToArray()[rand.Next(context.Users.Count())].Id;
                    b.ValorAPagar     = rand.NextDouble() * rand.Next(250);
                    b.ValorDocumento  = rand.NextDouble() * rand.Next(250);
                    b.LinhaDigitavel  = RandomString.NextString(15);
                    b.NumeroDocumento = rand.Next().ToString(CultureInfo.InvariantCulture);
                    b.Serie           = RandomString.NextString(25);
                    boletos.Add(b);
                }

                #endregion

                boletos.ForEach(i =>
                {
                    context.Boletos.Add(i);
                });
                context.SaveChanges();
            }

            if (!context.Impostos.Any())
            {
                #region Gera Novos Impostos

                Random         rand     = new Random();
                RandomDateTime randdt   = new RandomDateTime();
                int            tam      = rand.Next(1, 25);
                List <Imposto> impostos = new List <Imposto>(tam);

                for (int x = 0; x < tam; x++)
                {
                    DateTime dtaprIni, dtAprFim;

                    do
                    {
                        dtaprIni = randdt.Next();
                        dtAprFim = randdt.Next();
                    }while (dtaprIni > dtAprFim);
                    impostos.Add(new Imposto
                    {
                        DataAlteracao         = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null,
                        DataCriacao           = randdt.Next(),
                        DataEmissao           = randdt.Next(),
                        DataPagamento         = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null,
                        DataVencimento        = randdt.Next(),
                        Juros                 = rand.NextDouble() * rand.Next(250),
                        PeriodoApuracaoInicio = dtaprIni,
                        PeriodoApuracaoFim    = dtAprFim,
                        Multa                 = rand.NextDouble() * rand.Next(250),
                        Status                = ((TipoStatusConta)rand.Next(2)).ToString(),
                        TipoConta             = (int)TipoConta.Imposto,
                        UsuarioID             = context.Users.ToArray()[rand.Next(context.Users.Count())].Id,
                        ValorAPagar           = rand.NextDouble() * rand.Next(250),
                        ValorDocumento        = rand.NextDouble() * rand.Next(250),
                        LinhaDigitavel        = RandomString.NextString(15),
                        CNPJMatriz            = RandomString.NextString(18),
                        CodigoImposto         = rand.Next(),
                        NumeroDocumento       = rand.Next().ToString(CultureInfo.InvariantCulture),
                        Serie                 = RandomString.NextString(25)
                    });
                }

                #endregion

                impostos.ForEach(i =>
                {
                    context.Impostos.Add(i);
                });

                context.SaveChanges();
            }

            if (!context.OutrasContas.Any())
            {
                #region Gera novas outras contas

                Random            rand         = new Random();
                RandomDateTime    randdt       = new RandomDateTime();
                int               tam          = rand.Next(1, 25);
                List <OutraConta> outrasContas = new List <OutraConta>(tam);

                for (int x = 0; x < tam; x++)
                {
                    DateTime dtaprIni, dtAprFim;

                    do
                    {
                        dtaprIni = randdt.Next();
                        dtAprFim = randdt.Next();
                    }while (dtaprIni > dtAprFim);

                    outrasContas.Add(new OutraConta
                    {
                        DataAlteracao   = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null,
                        DataCriacao     = randdt.Next(),
                        DataEmissao     = randdt.Next(),
                        DataPagamento   = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null,
                        DataVencimento  = randdt.Next(),
                        Juros           = rand.NextDouble() * rand.Next(250),
                        Multa           = rand.NextDouble() * rand.Next(250),
                        Status          = ((TipoStatusConta)rand.Next(2)).ToString(),
                        TipoConta       = (int)TipoConta.Outras,
                        UsuarioID       = context.Users.ToArray()[rand.Next(context.Users.Count())].Id,
                        ValorAPagar     = rand.NextDouble() * rand.Next(250),
                        ValorDocumento  = rand.NextDouble() * rand.Next(250),
                        FornecedorID    = context.Fornecedores.ToArray()[rand.Next(context.Fornecedores.Count())].ID,
                        NumeroDocumento = rand.Next().ToString(CultureInfo.InvariantCulture),
                        Serie           = RandomString.NextString(25)
                    });
                }
                #endregion

                outrasContas.ForEach(o =>
                {
                    context.OutrasContas.Add(o);
                });

                context.SaveChanges();
            }

            if (!context.Reembolsos.Any())
            {
                #region Gera Novos Reembolsos

                Random           rand       = new Random();
                RandomDateTime   randdt     = new RandomDateTime();
                int              tam        = rand.Next(1, 10);
                List <Reembolso> reembolsos = new List <Reembolso>();

                for (int x = 0; x < tam; x++)
                {
                    DateTime dtaprIni, dtAprFim;

                    do
                    {
                        dtaprIni = randdt.Next();
                        dtAprFim = randdt.Next();
                    }while (dtaprIni > dtAprFim);

                    Reembolso r = new Reembolso();
                    r.DataAlteracao   = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null;
                    r.DataCriacao     = randdt.Next();
                    r.DataEmissao     = randdt.Next();
                    r.DataPagamento   = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null;
                    r.DataVencimento  = randdt.Next();
                    r.Juros           = rand.NextDouble() * rand.Next(250);
                    r.Multa           = rand.NextDouble() * rand.Next(250);
                    r.Status          = ((TipoStatusConta)rand.Next(2)).ToString();
                    r.TipoConta       = (int)TipoConta.Renegociacao;
                    r.UsuarioID       = context.Users.ToArray()[rand.Next(0, context.Users.Count())].Id;
                    r.ValorAPagar     = rand.NextDouble() * rand.Next(250);
                    r.ValorDocumento  = rand.NextDouble() * rand.Next(250);
                    r.ColaboradorID   = context.Colaboradores.ToArray()[rand.Next(0, context.Colaboradores.Count())].Id;
                    r.DataRecibo      = randdt.Next();
                    r.NumeroDocumento = rand.Next().ToString(CultureInfo.InvariantCulture);
                    r.Serie           = RandomString.NextString(25);

                    reembolsos.Add(r);
                }

                #endregion

                reembolsos.ForEach(r =>
                {
                    context.Add(r);
                });

                context.SaveChanges();
            }

            if (!context.Renegociacoes.Any())
            {
                #region Gera Novas Renegociacoes

                Random              rand          = new Random();
                RandomDateTime      randdt        = new RandomDateTime();
                int                 tam           = rand.Next(2);
                List <Renegociacao> renegociacoes = new List <Renegociacao>(tam);

                for (int x = 0; x < tam; x++)
                {
                    DateTime dtaprIni, dtAprFim;

                    do
                    {
                        dtaprIni = randdt.Next();
                        dtAprFim = randdt.Next();
                    }while (dtaprIni > dtAprFim);

                    renegociacoes.Add(new Renegociacao
                    {
                        DataAlteracao      = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null,
                        DataCriacao        = randdt.Next(),
                        DataEmissao        = randdt.Next(),
                        DataPagamento      = rand.NextDouble() > 0.5d ? randdt.Next() : (DateTime?)null,
                        DataVencimento     = randdt.Next(),
                        Juros              = rand.NextDouble() * rand.Next(250),
                        Multa              = rand.NextDouble() * rand.Next(250),
                        Status             = ((TipoStatusConta)rand.Next(2)).ToString(),
                        TipoConta          = (int)TipoConta.Renegociacao,
                        UsuarioID          = context.Users.ToArray()[rand.Next(context.Users.Count())].Id,
                        ValorAPagar        = rand.NextDouble() * rand.Next(250),
                        ValorDocumento     = rand.NextDouble() * rand.Next(250),
                        ContaID            = context.Conta.ToArray()[rand.Next(context.Conta.Count())].ID,
                        DataSolicitacao    = randdt.Next(),
                        NovaDataVencimento = randdt.Next(),
                        NovoValor          = rand.NextDouble() * rand.Next(250),
                        QuantidadeParcelas = rand.Next(1, 25),
                        TipoRenegociacao   = RandomString.NextString(15),
                        NumeroDocumento    = rand.Next().ToString(CultureInfo.InvariantCulture),
                        Serie              = RandomString.NextString(25)
                    });
                }

                #endregion

                renegociacoes.ForEach(r =>
                {
                    context.Renegociacoes.Add(r);
                });

                context.SaveChanges();
            }
        }
Пример #11
0
        private static void SeedInfoExt(ContasAPagarContext context)
        {
            if (!context.Fornecedores.Any())
            {
                #region Gera Lista de Fornecedores

                List <Fornecedor> fornecedores = new List <Fornecedor>()
                {
                    new Fornecedor {
                        Agencia = "001", Bairro = "Jardim Tropical", Cidade = "Sorocaba", CNPJ = "23.374.452/0001-39", CodBanco = "033", Conta = "1658", Email = "*****@*****.**", Endereco = "Rua André Luiz", Numero = "135", RazaoSocial = "Nair e Esther Construções ME", Telefone = "(11) 3685-5108", UF = "SP"
                    },

                    new Fornecedor {
                        Agencia = "137", Bairro = "Montanhão", Cidade = "São Bernardo do Campo", CNPJ = "83.775.353/0001-90", CodBanco = "001", Conta = "3547", Email = "*****@*****.**", Endereco = "Rua Janete Clair", Numero = "529", RazaoSocial = "Heloise e Erick Informática ME", Telefone = "(11) 3965-8118", UF = "SP"
                    },

                    new Fornecedor {
                        Agencia = "357", Bairro = "Jardim Novo Ângulo", Cidade = "Hortolândia", CNPJ = "26.703.156/0001-22", CodBanco = "025", Conta = "6523", Email = "*****@*****.**", Endereco = "Travessa E", Numero = "119", RazaoSocial = "Vitória e Nathan Advocacia ME", Telefone = "(19) 2894-5673", UF = "SP"
                    },

                    new Fornecedor {
                        Agencia = "112", Bairro = "Parque Maria Helena", Cidade = "Campinas", CNPJ = "08.957.455/0001-01", CodBanco = "001", Conta = "1325", Email = "*****@*****.**", Endereco = "Rua Jorge Rodrigues Dias", Numero = "930", RazaoSocial = "Renan e Lucas Consultoria Financeira Ltda", Telefone = "(19) 2573-9236", UF = "SP"
                    },

                    new Fornecedor {
                        Agencia = "120", Bairro = "Centro", Cidade = "Tupã", CNPJ = "13.706.098/0001-49", CodBanco = "033", Conta = "4523", Email = "*****@*****.**", Endereco = "Rua Potiguaras", Numero = "398", RazaoSocial = "Thiago e Yago Assessoria Jurídica Ltda", Telefone = "(14) 2855-3108", UF = "SP"
                    }
                };

                #endregion

                fornecedores.ForEach(f =>
                {
                    context.Fornecedores.Add(f);
                });
                context.SaveChanges();
            }
            if (!context.ContasMigracao.Any())
            {
                #region Gera Lista de contas para migração
                Random                rand           = new Random();
                RandomDateTime        randomDateTime = new RandomDateTime();
                int                   tam            = rand.Next(1, 100);
                List <ContasMigracao> contasMigracao = new List <ContasMigracao>(tam);

                for (int x = 0; x < tam; x++)
                {
                    contasMigracao.Add(new ContasMigracao
                    {
                        DataEmissao    = randomDateTime.Next(),
                        DataPagamento  = randomDateTime.Next(),
                        DataVencimento = randomDateTime.Next(),
                        ID             = rand.Next(),
                        Juros          = rand.NextDouble() * rand.Next(0, 25),
                        Multa          = rand.NextDouble() * rand.Next(0, 25),
                        Tipo           = ((TipoContaMigracao)rand.Next(0, 4)).ToString(),
                        Valor          = rand.NextDouble() * rand.Next(0, 25)
                    });
                }
                #endregion

                contasMigracao.ForEach(cm =>
                {
                    context.ContasMigracao.Add(cm);
                });
                context.SaveChanges();
            }
        }
Пример #12
0
        private static void Seed_Empire500XML_MovieInfo_Actors()
        {
            var listXmlContainer = XmlToXMLContainer();

            using (var context = new MovieDbContext())
            {
                var randomDate = new RandomDateTime();
                foreach (var xmlContainer in listXmlContainer)
                {
                    var movie = (from m in context.MovieSet
                                 where m.ImdbLink == xmlContainer.ImdbId
                                 select m).FirstOrDefault();

                    if (movie == null)
                    {
                        var movieToDB = new Movie();
                        movieToDB.ImdbLink    = xmlContainer.ImdbId;
                        movieToDB.Name        = xmlContainer.MovieTitle;
                        movieToDB.RunningTime = xmlContainer.Runtime;
                        movieToDB.Year        = xmlContainer.Year;
                        movieToDB.PlotOutline = xmlContainer.Plot;
                        movieToDB.CoverImage  = xmlContainer.MovieTitle
                                                .Replace(" ", "-").Replace(":", "")
                                                .Replace("?", "").Replace("*", "")
                                                .Replace("/", "").ToLowerInvariant() + ".jpg";

                        using (var ctx = new MovieDbContext())
                        {
                            bool directorMapped = false;
                            foreach (var directorName in xmlContainer.Directors)
                            {
                                var possibleNullDirector = new Director();
                                possibleNullDirector = ctx.DirectorSet.FirstOrDefault(t => t.FullName == directorName);

                                if (possibleNullDirector != null)
                                {
                                    movieToDB.DirectorId = possibleNullDirector.Id;
                                    directorMapped       = true;
                                }
                                break;
                            }

                            if (!directorMapped)
                            {
                                var    nameSplitted = xmlContainer.Directors[0].Split(' ');
                                string fname        = "";
                                string lname        = "";
                                string fullName     = "";

                                switch (nameSplitted.Count())
                                {
                                case 1:
                                    fullName = nameSplitted[0];
                                    break;

                                case 2:
                                    fname    = nameSplitted[0];
                                    lname    = nameSplitted[1];
                                    fullName = string.Format("{0} {1}", nameSplitted[0], nameSplitted[1]);
                                    break;

                                case 3:
                                    fname    = nameSplitted[0];
                                    lname    = nameSplitted[1] + " " + nameSplitted[2];
                                    fullName = string.Format("{0} {1} {2}", nameSplitted[0], nameSplitted[1], nameSplitted[2]);
                                    break;

                                case 4:
                                    fname    = nameSplitted[0];
                                    lname    = nameSplitted[1] + " " + nameSplitted[2] + " " + nameSplitted[3];
                                    fullName = string.Format("{0} {1} {2} {3}", nameSplitted[0], nameSplitted[1], nameSplitted[2], nameSplitted[3]);
                                    break;
                                }

                                var director = new Director
                                {
                                    FirstName = fname,
                                    LastName  = lname,
                                    FullName  = fullName,
                                    Biography = null,
                                    CountryId = 1,
                                    StateId   = 1,
                                    CountyId  = 1,
                                    CreatedAt = randomDate.Next(),
                                    Gender    = true,
                                    ImdbLink  = null,
                                    Photo     = null
                                };
                                ctx.DirectorSet.Add(director);
                                ctx.SaveChanges();

                                movieToDB.DirectorId = director.Id;
                            }
                        }

                        string movieLanguage        = xmlContainer.Language.Split(',')[0];
                        var    possibleNullLanguage = context.LanguageSet.FirstOrDefault(t => t.Name == movieLanguage);

                        if (possibleNullLanguage == null)
                        {
                            var language = new Language()
                            {
                                Name = movieLanguage
                            };
                            context.LanguageSet.Add(language);
                            context.SaveChanges();

                            movieToDB.LanguageId = language.Id;
                        }
                        else
                        {
                            movieToDB.LanguageId = possibleNullLanguage.Id;
                        }

                        var stringCountry       = xmlContainer.Country.Split(',')[0];
                        var possibleNullCountry = context.CountrySet.FirstOrDefault(t => t.Name == stringCountry);
                        if (possibleNullCountry == null)
                        {
                            var country = new Country()
                            {
                                Name = stringCountry
                            };

                            context.CountrySet.Add(country);
                            context.SaveChanges();

                            movieToDB.CountryId = country.Id;
                        }
                        else
                        {
                            movieToDB.CountryId = possibleNullCountry.Id;
                        }

                        context.MovieSet.Add(movieToDB);
                        context.SaveChanges();

                        foreach (var actor in xmlContainer.Actors)
                        {
                            var possibleNullActor = context.ActorSet.FirstOrDefault(t => t.FullName == actor);
                            if (possibleNullActor == null)
                            {
                                // aktör yoksa bir şey yapma
                            }
                            else
                            {
                                context.MovieActorMappingSet.Add(new MovieActorMapping()
                                {
                                    ActorId = possibleNullActor.Id,
                                    MovieId = movieToDB.Id,
                                });
                                context.SaveChanges();
                            }
                        }
                    }
                }
            }
        }
Пример #13
0
        public async Task AddJobLog_GivenJobUpdatedAndCompletedUnsuccesfully_EnsuresLatestCacheIsNotUpdated(CompletionStatus completionStatus)
        {
            //Arrange
            string         jobId       = "job-id-1";
            DateTimeOffset lastUpdated = new RandomDateTime();
            List <Outcome> outcomes    = new List <Outcome>
            {
                new Outcome
                {
                    Description = "outcome-1"
                }
            };

            string specificationId = "spec-id-1";
            string jobDefinitionId = "job-definition-id";

            JobLogUpdateModel jobLogUpdateModel = new JobLogUpdateModel
            {
                CompletedSuccessfully = false,
                Outcome        = "outcome",
                ItemsFailed    = 40,
                ItemsProcessed = 100,
                ItemsSucceeded = 60
            };

            Job job = new Job
            {
                Id                     = jobId,
                RunningStatus          = RunningStatus.InProgress,
                JobDefinitionId        = jobDefinitionId,
                InvokerUserDisplayName = "authorName",
                InvokerUserId          = "authorId",
                LastUpdated            = lastUpdated,
                ItemCount              = 100,
                SpecificationId        = specificationId,
                Trigger                = new Trigger
                {
                    EntityId   = "spec-id-1",
                    EntityType = "Specification",
                    Message    = "allocating"
                },
                Outcomes = outcomes
            };

            Job completedJob = new Job
            {
                Id                     = jobId,
                RunningStatus          = RunningStatus.Completed,
                JobDefinitionId        = jobDefinitionId,
                InvokerUserDisplayName = "authorName",
                InvokerUserId          = "authorId",
                LastUpdated            = lastUpdated,
                ItemCount              = 100,
                SpecificationId        = specificationId,
                Trigger                = new Trigger
                {
                    EntityId   = "spec-id-1",
                    EntityType = "Specification",
                    Message    = "allocating"
                },
                Outcomes         = outcomes,
                CompletionStatus = completionStatus,
            };

            IJobRepository jobRepository = CreateJobRepository();

            jobRepository
            .GetJobById(Arg.Is(jobId))
            .Returns(job);

            jobRepository
            .UpdateJob(Arg.Is(job))
            .Returns(HttpStatusCode.OK);

            jobRepository
            .CreateJobLog(Arg.Any <JobLog>())
            .Returns(HttpStatusCode.OK);

            jobRepository
            .GetLatestJobBySpecificationIdAndDefinitionId(Arg.Is(specificationId), Arg.Is(jobDefinitionId))
            .Returns(completedJob);

            ILogger logger = CreateLogger();

            ICacheProvider cacheProvider = CreateCacheProvider();

            JobManagementService jobManagementService = CreateJobManagementService(
                jobRepository: jobRepository,
                logger: logger,
                cacheProvider: cacheProvider);

            //Act
            IActionResult actionResult = await jobManagementService.AddJobLog(jobId, jobLogUpdateModel);

            //Assert
            actionResult
            .Should()
            .BeAssignableTo <OkObjectResult>();

            string cacheKey = $"{CacheKeys.LatestJobs}{job.SpecificationId}:{job.JobDefinitionId}";
            string latestSuccessfulJobCacheKey = $"{CacheKeys.LatestSuccessfulJobs}{job.SpecificationId}:{job.JobDefinitionId}";


            await cacheProvider
            .Received(1)
            .SetAsync(cacheKey, Arg.Is <Job>(_ => _.Id == jobId));

            await cacheProvider
            .Received(0)
            .SetAsync(latestSuccessfulJobCacheKey, Arg.Is <Job>(_ => _.Id == jobId));
        }
Пример #14
0
        public async Task AddJobLog_GivenJobUpdatedAndCompletedSuccessfully_EnsuresLatestCacheIsUpdated()
        {
            //Arrange
            string         jobId       = "job-id-1";
            DateTimeOffset lastUpdated = new RandomDateTime();
            List <Outcome> outcomes    = new List <Outcome>
            {
                new Outcome
                {
                    Description = "outcome-1"
                }
            };

            string specificationId = "spec-id-1";
            string jobDefinitionId = "job-definition-id";

            JobLogUpdateModel jobLogUpdateModel = new JobLogUpdateModel
            {
                CompletedSuccessfully = true,
                Outcome        = "outcome",
                ItemsFailed    = 40,
                ItemsProcessed = 100,
                ItemsSucceeded = 60
            };

            Job job = new Job
            {
                Id                     = jobId,
                RunningStatus          = RunningStatus.InProgress,
                JobDefinitionId        = jobDefinitionId,
                InvokerUserDisplayName = "authorName",
                InvokerUserId          = "authorId",
                LastUpdated            = lastUpdated,
                ItemCount              = 100,
                SpecificationId        = specificationId,
                Trigger                = new Trigger
                {
                    EntityId   = "spec-id-1",
                    EntityType = "Specification",
                    Message    = "allocating"
                },
                Outcomes = outcomes
            };

            IJobRepository jobRepository = CreateJobRepository();

            jobRepository
            .GetJobById(Arg.Is(jobId))
            .Returns(job);

            jobRepository
            .UpdateJob(Arg.Is(job))
            .Returns(HttpStatusCode.OK);

            jobRepository
            .CreateJobLog(Arg.Any <JobLog>())
            .Returns(HttpStatusCode.OK);

            jobRepository
            .GetLatestJobBySpecificationIdAndDefinitionId(Arg.Is(specificationId), Arg.Is(jobDefinitionId))
            .Returns(job);

            ILogger logger = CreateLogger();

            INotificationService notificationService = CreateNotificationsService();

            ICacheProvider cacheProvider = CreateCacheProvider();

            JobManagementService jobManagementService = CreateJobManagementService(
                jobRepository: jobRepository,
                logger: logger,
                notificationService: notificationService,
                cacheProvider: cacheProvider);

            //Act
            IActionResult actionResult = await jobManagementService.AddJobLog(jobId, jobLogUpdateModel);

            //Assert
            actionResult
            .Should()
            .BeAssignableTo <OkObjectResult>();

            await
            notificationService
            .Received(1)
            .SendNotification(Arg.Is <JobSummary>(m =>
                                                  m.JobId == jobId &&
                                                  m.JobType == "job-definition-id" &&
                                                  m.CompletionStatus == CompletionStatus.Succeeded &&
                                                  m.InvokerUserDisplayName == "authorName" &&
                                                  m.InvokerUserId == "authorId" &&
                                                  m.ItemCount == 100 &&
                                                  m.Outcome == "outcome" &&
                                                  m.OverallItemsFailed == 40 &&
                                                  m.OverallItemsProcessed == 100 &&
                                                  m.OverallItemsSucceeded == 60 &&
                                                  m.ParentJobId == null &&
                                                  m.SpecificationId == "spec-id-1" &&
                                                  string.IsNullOrWhiteSpace(m.SupersededByJobId) &&
                                                  m.Trigger.EntityId == "spec-id-1" &&
                                                  m.Trigger.EntityType == "Specification" &&
                                                  m.Trigger.Message == "allocating" &&
                                                  m.RunningStatus == RunningStatus.Completed &&
                                                  m.LastUpdated == lastUpdated &&
                                                  m.Outcomes.SequenceEqual(outcomes) &&
                                                  m.OutcomeType == OutcomeType.Succeeded
                                                  ));

            string cacheKey = $"{CacheKeys.LatestJobs}{job.SpecificationId}:{job.JobDefinitionId}";
            string latestSuccessfulJobCacheKey = $"{CacheKeys.LatestSuccessfulJobs}{job.SpecificationId}:{job.JobDefinitionId}";


            await cacheProvider
            .Received(1)
            .SetAsync(cacheKey, Arg.Is <Job>(_ => _.Id == jobId));

            await cacheProvider
            .Received(1)
            .SetAsync(latestSuccessfulJobCacheKey, Arg.Is <Job>(_ => _.Id == jobId));
        }
Пример #15
0
            public static void GenerateReview(ApplicationDbContext context, Album album, IdentityUser user, int type, string adminID)
            {
                var rand    = new Random();
                var dateGen = new RandomDateTime(album.ReleaseDate);
                var date    = dateGen.Next();
                int rate    = 0;

                switch (type)
                {
                case 0:
                    rate = (rand.Next() % 5) + 1;
                    break;

                case 1:
                    rate = (rand.Next() % 5) + 4;
                    break;

                case 2:
                    rate = (rand.Next() % 4) + 7;
                    break;
                }
                string comment = "Best Album Ever!";

                switch (rate)
                {
                case 1:
                    comment = "Pure garbage! I regret listening to it";
                    break;

                case 2:
                    comment = "Bad album! Didn't feel it this time";
                    break;

                case 3:
                    comment = "Won't listen to it again...";
                    break;

                case 4:
                    comment = "Heard worst than that one";
                    break;

                case 5:
                    comment = "It's OK, nothing more, nothing less";
                    break;

                case 6:
                    comment = "Nice one, good listing";
                    break;

                case 7:
                    comment = $"This album is totally {user.UserName} approved!";
                    break;

                case 8:
                    comment = "Loved it! Can't wait to hear it once again";
                    break;

                case 9:
                    comment = "Great album! Really recommended";
                    break;
                }
                var review = new Review {
                    Comment = comment, Rate = rate, Album = album, User = user, CreationTime = date, AlbumId = album.AlbumId
                };

                review.OwnerID = adminID;
                review.Status  = ReviewStatus.Approved;
                context.Reviews.Add(review);
                album.UpdateAlbumRate();
                album.PageViews++;
            }