Пример #1
0
        public static void CreateStudent()
        {
            using (var context = new EFContext())
            {
                User user = new User();
                user.UserType = UserTypeEnum.Student;

                Student toAdd = new Student();
                toAdd.FirstName = "Dennis";
                toAdd.LastName  = "Nyberg";
                toAdd.Birthdate = new DateTime(1995, 2, 16);
                toAdd.User      = user;
                context.Add(toAdd);

                User user1 = new User();
                user1.UserType = UserTypeEnum.Student;

                Student toAdd1 = new Student();
                toAdd1.FirstName = "Erik";
                toAdd1.LastName  = "Häregård";
                toAdd1.Birthdate = new DateTime(1997, 2, 9);
                toAdd1.User      = user1;
                context.Add(toAdd1);

                context.SaveChanges();
            }
        }
        public async Task GetApproverName_IPM()
        {
            //Arrange
            var costId = Guid.NewGuid();
            var cost   = new Cost
            {
                Id = costId
            };
            var approverUserId       = Guid.NewGuid();
            var expectedApproverName = "John Connor";
            var approverUser         = new CostUser
            {
                Id       = approverUserId,
                FullName = expectedApproverName
            };
            var approvalType = "IPM";

            _efContext.Add(approverUser);
            _efContext.Add(cost);
            _efContext.SaveChanges();

            //Act
            var result = await _costUserService.GetApprover(costId, approverUserId, approvalType);

            //Assert
            result.Should().NotBeNull();
            result.Should().Be(expectedApproverName);
        }
Пример #3
0
        private static void InsertProduct()
        {
            // Create a new instance of the DbContext class.
            using (var db = new EFContext())
            {
                // Create a new instance of the domain class product and assign values to its properties.
                Product product = new Product
                {
                    Name = "Pen Drive"
                };
                // add it to the DbContext class so that Context becomes aware of the entity.
                db.Add(product);

                product = new Product
                {
                    Name = "Memory Card"
                };

                // add it to the DbContext class so that Context becomes aware of the entity.
                db.Add(product);

                // call the saveChanges method of the DBContext to persist the changes to the database.
                db.SaveChanges();
            }
            return;
        }
Пример #4
0
        public async Task <IActionResult> CreateChannel([Bind("ID,Name,Color")] ChannelModel channelModel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(channelModel);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(channelModel));
        }
        public async Task <IActionResult> Create([Bind("ID,Nome,Duracao,Caminho,IdGeneros")] Series series)
        {
            if (ModelState.IsValid)
            {
                _context.Add(series);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["IdGeneros"] = new SelectList(_context.generos, "Id", "Id", series.IdGeneros);
            return(View(series));
        }
Пример #6
0
        public List <int> CreateInvoices(int idUser, List <int> idAllocatedTimes)
        {
            using (IDbContextTransaction transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    IEnumerable <AllocatedTime> allocatedTimes = _projectService.GetAllocatedTimes().Where(at => at.Project.User.Id == idUser && idAllocatedTimes.Any(idt => idt == at.Id));
                    if (allocatedTimes == null)
                    {
                        throw new NotFoundException();
                    }
                    if (allocatedTimes.Any(at => at.Invoice != null) || allocatedTimes.Any(at => at.EndDate == null))
                    {
                        throw new Exception("In the allocated times set to be invoiced there are invalid items");
                    }

                    var allocatedTimesGroupedByCustomerList = allocatedTimes.GroupBy(at => at.Project.CustomerId).Select(atg => new {
                        customerId = atg.Key,
                        amount     = atg.Sum(s => (decimal)s.EndDate.Value.Subtract(s.StartDate).TotalHours)
                    });

                    List <Invoice> newInvoiceList = new List <Invoice>();

                    foreach (var allocatedTimesGroupedByCustomer in allocatedTimesGroupedByCustomerList)
                    {
                        Invoice invoice = new Invoice();

                        invoice.CustomerId = allocatedTimesGroupedByCustomer.customerId;
                        invoice.Status     = INVOICESTATUS.CREATED;
                        _context.Add(invoice);
                        newInvoiceList.Add(invoice);

                        InvoiceLine invoiceLine = new InvoiceLine {
                            Invoice = invoice,
                            Amount  = allocatedTimesGroupedByCustomer.amount
                        };
                        //invoiceLine.InvoiceId = invoice.Id;
                        _context.Add(invoiceLine);
                    }
                    _context.SaveChanges();

                    transaction.Commit();

                    return(newInvoiceList.Select(i => i.Id).ToList());
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
            }
        }
        public async Task <IActionResult> Create(int?id, [Bind("DescripcionAtencion")] Evolucion evolucion)
        {
            if (ModelState.IsValid)
            {
                evolucion.Medico        = User.Identity.Name;
                evolucion.FechaYHora    = DateTime.Now;
                evolucion.EstadoAbierto = true;
                evolucion.EpisodioId    = (int)id;

                Episodio e = _context.Episodios.Where(e => e.Id == id).FirstOrDefault();
                evolucion.Episodio = e;
                evolucion.Notas    = new List <Nota>();

                if (e.Evoluciones == null)
                {
                    e.Evoluciones = new List <Evolucion>();
                }
                e.Evoluciones.Add(evolucion);

                _context.Add(evolucion);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", new { id }));
            }
            return(View(evolucion));
        }
Пример #8
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            cat.EnableValidation = true;

            if (string.IsNullOrEmpty(cat.Error))
            {
                if (!string.IsNullOrEmpty(file_selected))
                {
                    string ext = Path.GetExtension(file_selected);

                    string fileName = Path.GetRandomFileName() + ext;

                    string fileSavePath = Path.Combine(Directory.GetCurrentDirectory(),
                                                       "images", fileName);

                    var bmp = ResizeImage.ResizeOrigImg(
                        new Bitmap(System.Drawing.Image.FromFile(file_selected)), 75, 75);

                    bmp.Save(fileSavePath, ImageFormat.Jpeg);

                    file_name = fileSavePath;
                }
                var cat_info =
                    new AppCat
                {
                    Name        = tbname.Text,
                    Birth       = (DateTime)bdcat.SelectedDate,
                    Description = tbdesc.Text,
                    Gender      = cbitem.Text.ToString(),
                    Image       = file_name
                };
                cat_info.AppCatPrices = new List <AppCatPrice>
                {
                    new AppCatPrice
                    {
                        CatId      = cat_info.Id,
                        DateCreate = DateTime.Now,
                        Price      = decimal.Parse(tbprice.Text)
                    }
                };

                _cats.Add(new CatVM
                {
                    Id          = cat_info.Id.ToString(),
                    Name        = cat_info.Name,
                    Birthday    = cat_info.Birth,
                    Description = cat_info.Description,
                    Image       = cat_info.Image
                });

                _context.Add(cat_info);
                _context.SaveChanges();

                Close();
            }
            else
            {
                MessageBox.Show(cat.Error);
            }
        }
Пример #9
0
        /// <summary>
        /// Create data - the C in CRUD
        /// </summary>
        public static void CreateItem()
        {
            using (var context = new EFContext())
            {
                string[] lines = File.ReadAllLines(filePath);

                foreach (var filePosts in lines)
                {
                    rowsAffected++;
                    string[] fields        = filePosts.Split(','); //Seperates date and timespan + each post.
                    var      databaseInput = new Temperature();

                    DateTime date     = DateTime.Parse(fields[0]);
                    string   place    = fields[1];
                    double?  temp     = double.Parse(fields[2], CultureInfo.InvariantCulture);
                    int?     humidity = int.Parse(fields[3]);

                    databaseInput.Date     = date;
                    databaseInput.Place    = place;
                    databaseInput.Temp     = temp;
                    databaseInput.Humidity = humidity;
                    context.Add(databaseInput);
                }
                context.SaveChanges();
                Console.WriteLine($"Seeding complete. {rowsAffected} rows affected");
            }
        }
Пример #10
0
            public async Task IsValidForSubmission_When_Invalid_Should_SendNotificationToSupportTeam()
            {
                // Arrange
                var          costId     = Guid.NewGuid();
                const string message    = "Any message";
                const string costNumber = "PO12312313";

                EFContext.Add(new Cost
                {
                    Id         = costId,
                    CostNumber = costNumber
                });
                EFContext.SaveChanges();

                CostBuilderMock.Setup(cb => cb.IsValidForSubmittion(costId)).ReturnsAsync(new OperationResponse(false, message));

                // Act
                var result = await CostService.IsValidForSubmission(User, costId);

                // Assert
                result.Should().NotBeNull();
                result.Success.Should().Be(false);
                SupportNotificationServiceMock.Verify(sn =>
                                                      sn.SendSupportSubmissionFailedNotification(costNumber, null), Times.Once);
            }
        public async Task <IActionResult> Create(int?id, [Bind("Mensaje")] Nota nota)
        {
            if (ModelState.IsValid)
            {
                nota.NombreAutor = User.Identity.Name;
                nota.FechaYHora  = DateTime.Now;
                nota.EvolucionId = (int)id;

                var evolucion = await _context.Evoluciones.FindAsync(id);

                nota.Evolucion = evolucion;

                if (evolucion.Notas == null)
                {
                    evolucion.Notas = new List <Nota>();
                }
                evolucion.Notas.Add(nota);

                _context.Add(nota);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", new { id }));
            }
            ViewData["EvolucionId"] = new SelectList(_context.Evoluciones, "Id", "Id", nota.EvolucionId);
            return(View(nota));
        }
Пример #12
0
        static void insertProduct()
        {
            using (var db = new EFContext())
            {
                Product product = new Product();
                product.Name = "Pen Drive";
                db.Add(product);

                product      = new Product();
                product.Name = "Memory Card";
                db.Add(product);

                db.SaveChanges();
            }
            return;
        }
Пример #13
0
            private async Task <Guid> GetDictionaryEntryId(string dictionaryName, string value)
            {
                var root = await GetRootModule();

                var dictionary = await EFContext.Dictionary.FirstOrDefaultAsync(d => d.Name == dictionaryName);

                if (dictionary == null)
                {
                    dictionary = new Dictionary
                    {
                        Name           = dictionaryName,
                        AbstractTypeId = root.Id
                    };
                    EFContext.Add(dictionary);
                    await EFContext.SaveChangesAsync();
                }
                var entry = await EFContext.DictionaryEntry.FirstOrDefaultAsync(de => de.DictionaryId == dictionary.Id && de.Key == value);

                if (entry == null)
                {
                    entry = new DictionaryEntry
                    {
                        DictionaryId = dictionary.Id,
                        Key          = value
                    };
                    EFContext.DictionaryEntry.Add(entry);
                    await EFContext.SaveChangesAsync();
                }
                return(entry.Id);
            }
        public async Task <IActionResult> Create([Bind("Descripcion,Recomendacion,EpicrisisId")] Diagnostico diagnostico)
        {
            if (ModelState.IsValid)
            {
                var epicrisis = await _context.Epicrisis
                                .FirstOrDefaultAsync(m => m.Id == diagnostico.EpicrisisId);

                diagnostico.Epicrisis = epicrisis;

                if (User.IsInRole("Empleado"))
                {
                    diagnostico.Recomendacion = "CIERRE ADMINISTRATIVO";
                }

                var episodio = await _context.Episodios
                               .FirstOrDefaultAsync(m => m.Id == epicrisis.EpisodioId);

                episodio.FechaYHoraCierre = DateTime.Now;


                _context.Update(episodio);
                _context.Add(diagnostico);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", "Home"));
            }

            return(View());
        }
Пример #15
0
        private Agency CreateAgency(string name, bool prime)
        {
            var agency = new Agency
            {
                Name            = name,
                CountryId       = _country.Id,
                GdamAgencyId    = name,
                Labels          = prime ? new [] { PgOwnerLabel } : new string[0],
                PrimaryCurrency = _defaultCurrecy.Id
            };

            if (prime)
            {
                agency.AbstractTypes = new List <AbstractType>
                {
                    new AbstractType
                    {
                        ObjectId = agency.Id,
                        Parent   = _module,
                        Type     = AbstractObjectType.Agency.ToString()
                    }
                };
            }
            EFContext.Add(agency);
            return(agency);
        }
Пример #16
0
        public IActionResult Create([FromBody] CreateUserDTO createUser)
        {
            var user = new User();

            user.Id       = createUser.UserId;
            user.Username = createUser.User;
            user.Password = Guid.NewGuid().ToString();
            _context.Add(user);
            _context.SaveChanges();
            return(new ObjectResult(createUser.User)
            {
                StatusCode = (int)HttpStatusCode.Created
            });

            /*
             * if (_users.TryAdd(createUser.UserId, createUser.User))
             * {
             *  return new ObjectResult(createUser.User)
             *  {
             *      StatusCode = (int) HttpStatusCode.Created
             *  };
             * }
             * return BadRequest("Usuário já existe.");
             */
        }
Пример #17
0
        static void insertProduct()
        {
            using (var db = new EFContext())
            {
                Product product = new Product();
                product.Name = "Good Drive";
                db.Add(product);

                product      = new Product();
                product.Name = "Memory Card";
                db.Add(product);

                db.SaveChanges();
                Console.WriteLine("Inserted 2 new products");
            }
            return;
        }
Пример #18
0
        public async Task <int> CreateAsync(FieldDTO dto)
        {
            var entity = dto.ConvertToEntity();

            _context.Add(entity);
            await _context.SaveChangesAsync();

            return(entity.Id);
        }
        public async Task <int> CreateAsync(ClassificationCriterionDTO dto)
        {
            var entity = dto.ConvertToEntity();

            _context.Add(entity);
            await _context.SaveChangesAsync();

            return(entity.Id);
        }
        protected void SetupDataSharedAcrossTests(Agency agency, Country country,
                                                  Cost cost, CostStageRevision latestRevision, Project project, CostUser costOwner, Guid costOwnerId, CostStage costStage,
                                                  Brand brand, Guid costId, Guid costStageRevisionId, Guid projectId, string budgetRegion = Constants.BudgetRegion.AsiaPacific)
        {
            agency.Country  = country;
            cost.CostNumber = CostNumber;
            cost.LatestCostStageRevision = latestRevision;
            cost.Project             = project;
            costOwner.Agency         = agency;
            costOwner.Id             = costOwnerId;
            latestRevision.CostStage = costStage;
            project.Brand            = brand;

            agency.Name           = AgencyName;
            brand.Name            = BrandName;
            cost.Id               = costId;
            costStage.Name        = CostStageName.ToString();
            costOwner.FullName    = CostOwnerFullName;
            costOwner.GdamUserId  = CostOwnerGdamUserId;
            latestRevision.Id     = costStageRevisionId;
            project.Id            = projectId;
            project.Name          = ProjectName;
            project.GdamProjectId = ProjectGdamId;
            project.AdCostNumber  = ProjectNumber;
            country.Name          = AgencyLocation;

            var stageDetails = new PgStageDetailsForm
            {
                ContentType = new core.Builders.DictionaryValue
                {
                    Id  = Guid.NewGuid(),
                    Key = ContentType
                },
                CostType       = cost.CostType.ToString(),
                ProductionType = new core.Builders.DictionaryValue
                {
                    Id  = Guid.NewGuid(),
                    Key = CostProductionType
                },
                Title = CostTitle,
                AgencyTrackingNumber = AgencyTrackingNumber,
                BudgetRegion         = new AbstractTypeValue
                {
                    Key  = budgetRegion,
                    Name = budgetRegion
                }
            };
            var existingUser = EFContext.CostUser.FirstOrDefault(a => a.GdamUserId == CostOwnerGdamUserId);

            if (existingUser == null)
            {
                EFContext.Add(costOwner);
                EFContext.SaveChanges();
            }

            CostStageRevisionServiceMock.Setup(csr => csr.GetStageDetails <PgStageDetailsForm>(costStageRevisionId)).ReturnsAsync(stageDetails);
        }
Пример #21
0
 public IActionResult Signup([FromBody] UserModel model)
 {
     _context.Add(new User {
         Gmail    = model.Gmail,
         Name     = model.Name,
         Password = model.Password
     });
     _context.SaveChanges();
     return(Ok());
 }
 public IActionResult Create(Pessoa pessoa)
 {
     if (ModelState.IsValid)
     {
         _context.Add(pessoa);
         _context.SaveChanges();
         return(RedirectToAction(nameof(Index)));
     }
     return(View(pessoa));
 }
Пример #23
0
        public IActionResult NovoCarro(Carro carro)
        {
            if (ModelState.IsValid)
            {
                contexto.Add(carro);
                contexto.SaveChanges();
                return(RedirectToAction(nameof(Index)));
            }

            return(View());
        }
Пример #24
0
        public async Task <int> SaveLightInfo(TNL_TunnelLight tunnelLight)
        {
            try
            {
                using (var context = new EFContext())
                {
                    //var light = (from d in context.TNL_TunnelLights
                    //             where d.TunnelLight_ID == 1000044L && d.DeviceId != null
                    //             select d).FirstOrDefault();
                    TNL_TunnelLight light = null;
                    if (light == null)
                    {
                        light = new TNL_TunnelLight();
                        light.TunnelLight_ID = await DataBaseHelper.GetKey("TNL_TunnelLight", "TunnelLight_ID");
                    }
                    light.TunnelLight_ID          = -1;
                    light.TunnelSection_ID        = -1;
                    light.TunnelGateway_ID        = -1;
                    light.Tunnel_ID               = -1;
                    light.LightPhysicalAddress_TX = string.Empty;
                    light.LightLocationNumber_NR  = -1;
                    light.LightUsage_NR           = -1;
                    light.GroupNumber_TX          = string.Empty;
                    light.LightFunction_NR        = -1;
                    light.LightSource_NR          = -1;
                    light.LampType_NR             = -1;
                    light.DimmingFactor_NR        = 1;
                    light.DefaultDimmingValue_NR  = 1;
                    light.PowerOnDimmingValue_NR  = 1;
                    light.MaximumDimmingValue_NR  = 1;
                    light.MinimumDimmingValue_NR  = 1;

                    light.Active_YN                      = '0';
                    light.EnablePIRFunction_YN           = '0';
                    light.PIRLastTimeMinutesOfDimming_NR = -1;
                    light.PIRRestoreTime_NR              = -1;
                    light.PIRGroupNumber_NR              = -1;
                    light.PIRIdleDimmingValue_NR         = -1;
                    light.PIRDimmingValue_NR             = -1;
                    light.PIRTTL_NR                      = -1;
                    light.LightConfig_ID                 = -1;
                    light.LightTimeControl_ID            = -1;

                    light.PIRSensorPlan_ID = -1;

                    context.Add(light);
                    return(await context.SaveChangesAsync());
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task <IActionResult> Create([Bind("Code,Model,Manufacturer,WTC,ID,IsDeleted,CreationDate,ModifiedDate,DeletedDate")] AircraftType aircraftType)
        {
            if (ModelState.IsValid)
            {
                _context.Add(aircraftType);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(aircraftType));
        }
        public async Task <IActionResult> Create([Bind("ReceitaId,Valor,Descricao,Pago,ReceitaFixa,ReceitaParcelada,QtdParcelas,Observacao,DhReceita")] Receita receita)
        {
            if (ModelState.IsValid)
            {
                _context.Add(receita);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(receita));
        }
Пример #27
0
        public async Task <IActionResult> Create([Bind("TarefasId,Nome,Descricao,Inicio,Fim,Importancia")] Tarefas tarefas)
        {
            if (ModelState.IsValid)
            {
                _context.Add(tarefas);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(tarefas));
        }
Пример #28
0
        public async Task <IActionResult> Create([Bind("id,FirstName,LastName,Company,Email,PhoneNumber")] Contact contact)
        {
            if (ModelState.IsValid)
            {
                _context.Add(contact);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(contact));
        }
        public async Task <IActionResult> Create([Bind("Id,Nome")] Generos generos)
        {
            if (ModelState.IsValid)
            {
                _context.Add(generos);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(generos));
        }
Пример #30
0
        public async Task <IActionResult> Create([Bind("BlogId,Url")] Blog blog)
        {
            if (ModelState.IsValid)
            {
                _context.Add(blog);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(blog));
        }