コード例 #1
0
 public async Task Add(ApplicationUser user)
 {
     _dbContext.Add(user);
     await _dbContext.SaveChangesAsync();
 }
コード例 #2
0
 public void AddVehicle(Vehicle vehicle)
 {
     _context.Add(vehicle);
 }
コード例 #3
0
        public ApplicationDbContextFixtureServiceRequisitions()
        {
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();
            var options = new DbContextOptionsBuilder <ApplicationDbContext>().UseSqlite(connection).Options;

            DbContext = new ApplicationDbContext(options);
            DbContext.Database.EnsureCreated();

            CreateRoles_Users();


            //Creates and adds a Category to the context
            CleaningCategory = new ServiceCategory()
            {
                CategoryID    = 1,
                Name          = "Limpeza",
                IsSubcategory = false
            };
            DbContext.Add(CleaningCategory);
            DbContext.SaveChanges();


            //Creates and adds a Service to the context
            CleaningService = new Service()
            {
                ServiceID         = 1,
                UserID            = Prestador.Id,
                ServiceCategoryID = 1,
                ServiceName       = "Faço limpezas ao domicilio",
                Description       = "Faço limpezas ao domicilio durante a semana de manha"
            };
            DbContext.Add(CleaningService);
            DbContext.SaveChanges();


            //Creates and Adds service requisitions to the context
            PendingServiceRequisition = new ServiceRequisition()
            {
                ServiceRequisitionID     = 1,
                RequisitionerID          = Cliente.Id,
                ServiceID                = CleaningService.ServiceID,
                ServiceRequisitionStatus = ServiceRequisitionStatus.Pending,
                AdditionalRequestInfo    = "Limpeza de Prédio - 2x por semana",
                CreationDate             = DateTime.Now,
                LastUpdatedTime          = DateTime.Now,
                LastUpdatedBy            = Cliente.UserName,
                Service       = CleaningService,
                Requisitioner = Cliente
            };

            AcceptedServiceRequisition = new ServiceRequisition()
            {
                ServiceRequisitionID     = 2,
                RequisitionerID          = Cliente.Id,
                ServiceID                = CleaningService.ServiceID,
                ServiceRequisitionStatus = ServiceRequisitionStatus.Accepted,
                AdditionalRequestInfo    = "Limpeza de Prédio - 2x por semana",
                CreationDate             = PendingServiceRequisition.CreationDate,
                LastUpdatedTime          = DateTime.Now,
                LastUpdatedBy            = Prestador.UserName,
                Service       = CleaningService,
                Requisitioner = Cliente
            };

            ConcludedServiceRequisition = new ServiceRequisition()
            {
                ServiceRequisitionID     = 3,
                RequisitionerID          = Cliente.Id,
                ServiceID                = CleaningService.ServiceID,
                ServiceRequisitionStatus = ServiceRequisitionStatus.Concluded,
                AdditionalRequestInfo    = "Limpeza de Prédio - 2x por semana",
                CreationDate             = PendingServiceRequisition.CreationDate,
                LastUpdatedTime          = DateTime.Now,
                LastUpdatedBy            = Prestador.UserName,
                Service       = CleaningService,
                Requisitioner = Cliente
            };

            CancelledServiceRequisition = new ServiceRequisition()
            {
                ServiceRequisitionID     = 4,
                RequisitionerID          = Cliente.Id,
                ServiceID                = CleaningService.ServiceID,
                ServiceRequisitionStatus = ServiceRequisitionStatus.Cancelled,
                AdditionalRequestInfo    = "Limpeza de Prédio - 2x por semana",
                CreationDate             = PendingServiceRequisition.CreationDate,
                LastUpdatedTime          = DateTime.Now,
                LastUpdatedBy            = Prestador.UserName,
                Service       = CleaningService,
                Requisitioner = Cliente
            };

            RejectedServiceRequisition = new ServiceRequisition()
            {
                ServiceRequisitionID     = 5,
                RequisitionerID          = Cliente.Id,
                ServiceID                = CleaningService.ServiceID,
                ServiceRequisitionStatus = ServiceRequisitionStatus.Rejected,
                AdditionalRequestInfo    = "Limpeza de Prédio - 2x por semana",
                CreationDate             = PendingServiceRequisition.CreationDate,
                LastUpdatedTime          = DateTime.Now,
                LastUpdatedBy            = Prestador.UserName,
                Service       = CleaningService,
                Requisitioner = Cliente
            };

            AcceptedServiceRequisition2 = new ServiceRequisition()
            {
                ServiceRequisitionID     = 6,
                RequisitionerID          = Cliente.Id,
                ServiceID                = CleaningService.ServiceID,
                ServiceRequisitionStatus = ServiceRequisitionStatus.Accepted,
                AdditionalRequestInfo    = "Limpeza de Prédio - 2x por semana",
                CreationDate             = PendingServiceRequisition.CreationDate,
                LastUpdatedTime          = DateTime.Now,
                LastUpdatedBy            = Prestador.UserName,
                ConclusionDate           = DateTime.Now,
                Service       = CleaningService,
                Requisitioner = Cliente
            };

            DbContext.Add(PendingServiceRequisition);
            DbContext.Add(AcceptedServiceRequisition);
            DbContext.Add(CancelledServiceRequisition);
            DbContext.Add(ConcludedServiceRequisition);
            DbContext.Add(RejectedServiceRequisition);
            DbContext.Add(AcceptedServiceRequisition2);
            DbContext.SaveChanges();
        }
コード例 #4
0
 public void AddSubscription(Subscription subscription)
 {
     _context.Add(subscription);
     _context.SaveChanges();
 }
コード例 #5
0
 public void Add(Book book)
 {
     _context.Add(book);
     _context.SaveChanges();
 }
コード例 #6
0
ファイル: Startup.cs プロジェクト: ChavFDG/Old-Stolons
        private void CreateProductsSamples(ApplicationDbContext context)
        {
            if (context.Products.Any())
                return;
            Product pain = new Product();
            pain.Name = "Pain complet";
            pain.Description = "Pain farine complete T80";
            pain.Labels.Add(Product.Label.Ab);
            pain.PicturesSerialized= Path.Combine(Configurations.ProductsStockagePath, "pain.png");
            pain.Price = 15.5F;
	    pain.UnitPrice = 4;
            pain.Producer = context.Producers.First();
            pain.ProductUnit = Product.Unit.Kg;
            pain.RemainingStock = 10;
            pain.State = Product.ProductState.Enabled;
            pain.Type = Product.SellType.Piece;
            pain.WeekStock = 10;
            pain.Familly = context.ProductFamillys.First(x => x.FamillyName == "Pains");
            context.Add(pain);
            Product tomate = new Product();
            tomate.Name = "Tomates grappe";
            tomate.Description = "Avec ces tomates, c'est nous qui rougissons même si elles ne sont pas toutes nues!";
            tomate.Labels.Add(Product.Label.Ab);
            tomate.PicturesSerialized = Path.Combine(Configurations.ProductsStockagePath, "tomate.jpg");
	    tomate.Price = 3;
	    tomate.UnitPrice = 1.5F;
	    tomate.QuantityStep = 500;
            tomate.Producer = context.Producers.First();
            tomate.ProductUnit = Product.Unit.Kg;
            tomate.RemainingStock = 10;
            tomate.Familly = context.ProductFamillys.First(x => x.FamillyName == "Légumes");
            tomate.State = Product.ProductState.Enabled;
            tomate.Type = Product.SellType.Weigh;
            tomate.WeekStock = 10;
            context.Add(tomate);
            Product pommedeterre = new Product();
            pommedeterre.Name = "Pomme de terre";
            pommedeterre.Description = "Pataaaaaaaaaaaaaaaates!!";
            pommedeterre.Labels.Add(Product.Label.Ab);
            pommedeterre.PicturesSerialized = Path.Combine(Configurations.ProductsStockagePath, "pommedeterre.jpg");
            pommedeterre.Price = 1.99F;
	    pommedeterre.UnitPrice = 1.99F;
	    pommedeterre.QuantityStep = 1000;
            pommedeterre.Producer = context.Producers.First();
            pommedeterre.ProductUnit = Product.Unit.Kg;
            pommedeterre.RemainingStock = 10;
            pommedeterre.Familly = context.ProductFamillys.First(x => x.FamillyName == "Légumes");
            pommedeterre.State = Product.ProductState.Enabled;
            pommedeterre.Type = Product.SellType.Weigh;
            pommedeterre.WeekStock = 10;
            context.Add(pommedeterre);
            Product radis = new Product();
            radis.Name = "Radis";
            radis.Description = "Des supers radis (pour ceux qui aiment)";
            radis.Labels.Add(Product.Label.Ab);
            radis.PicturesSerialized = Path.Combine(Configurations.ProductsStockagePath, "radis.jpg");
            radis.Price = 0;
	    radis.UnitPrice = 4;
            radis.Producer = context.Producers.First();
            radis.ProductUnit = Product.Unit.Kg;
            radis.RemainingStock = 10;
            radis.Familly = context.ProductFamillys.First(x => x.FamillyName == "Légumes");
            radis.State = Product.ProductState.Enabled;
            radis.Type = Product.SellType.Piece;
            radis.WeekStock = 10;
            context.Add(radis);
            Product salade = new Product();
            salade.Name = "Salade";
            salade.Description = "Une bonne salade pour aller avec les bonnes tomates!";
            salade.Labels.Add(Product.Label.Ab);
            salade.PicturesSerialized = Path.Combine(Configurations.ProductsStockagePath, "salade.jpg");
            salade.UnitPrice = 0.80F;
	    salade.Price = 0;
            salade.Producer = context.Producers.First();
            salade.ProductUnit = Product.Unit.Kg;
            salade.RemainingStock = 10;
            salade.Familly = context.ProductFamillys.First(x => x.FamillyName == "Légumes");
            salade.State = Product.ProductState.Enabled;
            salade.Type = Product.SellType.Piece;
            salade.WeekStock = 10;
            context.Add(salade);

            //
            context.SaveChanges();
        }
コード例 #7
0
ファイル: ActionService.cs プロジェクト: taylorrobert/WebRPG
        public static void PerformActions(ApplicationDbContext db, ClientActionModel model, DataCache data)
        {
            var actionCounter = new Dictionary<string, int>();
            actionCounter[Constants.Constants.ActionTypeResearch] = 0;
            string currentObjectName = "";

            if (string.IsNullOrEmpty(model.Actions))
            {
                LogService.Log(db, data.Corporation, "You made no actions the previous turn.");
                return;
            }

            var actions = model.Actions.Split('|');
            foreach (var actionType in actions)
            {
                var currentActionDict = new Dictionary<string, string>();
                var actionItems = actionType.Split(';');
                foreach (var a in actionItems)
                {
                    var parameters = a.Split('=');
                    if (string.IsNullOrEmpty(parameters[0])) continue;
                    currentActionDict[parameters[0]] = parameters[1];
                }

                //Handle action types---
                if (currentActionDict.ContainsKey(Constants.Constants.ActionType))
                {
                    if (currentActionDict[Constants.Constants.ActionType] == Constants.Constants.ActionTypeResearch)
                        actionCounter[Constants.Constants.ActionTypeResearch]++;
                }

                //Handle actions---
                if (currentActionDict.ContainsKey(Constants.Constants.Action))
                {
                    var specifierSplit = currentActionDict[Constants.Constants.Action].Split(':');
                    currentObjectName = specifierSplit[1];

                    //#LearnResearch
                    if (specifierSplit[0] == Constants.Constants.LearnResearch)
                    {
                        var researchNode = db.ResearchNodes.FirstOrDefault(n => n.Name == currentObjectName);

                        if (currentActionDict[Constants.Constants.ActionParameter] == Constants.Constants.LearnByCash) //Research is bought with cash
                        {
                            var node = data.ResearchNodes.FirstOrDefault(n => n.Name == currentObjectName);
                            if (node == null)
                                LogService.Log(db, data.Corporation, "ERROR: Attempting to add node " + currentObjectName +
                                             " that does not exist.");
                            else
                            {
                                if (node.CashCost > data.Corporation.Cash)
                                    LogService.Log(db, data.Corporation, "Error: Not enough cash to purchase research node " + currentObjectName);
                                else
                                {
                                    data.Corporation.Cash -= node.CashCost;
                                    var lrn = new LearnedResearchNode
                                    {
                                        Corporation = data.Corporation,
                                        ResearchNode = researchNode
                                    };
                                    db.Add(lrn);
                                    LogService.Log(db, data.Corporation, "Research " + currentObjectName + " purchased.");
                                }
                            }
                        }
                        else if (currentActionDict[Constants.Constants.ActionParameter] == Constants.Constants.SetActiveResearch) //Research is set to active
                        {

                            data.ActiveResearchNodes.ForEach(n => n.Active = false);

                            var active =
                                data.ActiveResearchNodes.FirstOrDefault(n => n.ResearchNode.Name == currentObjectName);

                            if (active != null) //If not null, we have already started researching it, so set to false
                            {
                                active.Active = true;
                                var toRemove = data.ActiveResearchNodes.Where(n => n.Id != active.Id);
                                db.Remove(toRemove);
                            }
                            else
                            {
                                active = new ActiveResearchNode();
                                active.ResearchNode = researchNode;
                                active.Corporation = data.Corporation;
                                active.Active = true;
                                db.Add(active);
                            }
                            LogService.Log(db, data.Corporation, "Set " + currentObjectName + " to active research. ");
                        }

                        var validated = data.LearnableResearchNodeNames.Contains(currentObjectName);
                        if (!validated)
                        {
                            LogService.Log(db, data.Corporation, "Error: Already learned node " + currentObjectName);
                        }
                    }
                    //#CancelActiveResearch
                    else if (specifierSplit[0] == Constants.Constants.CancelActiveResearch)
                    {
                        if (!data.ActiveResearchNodesSchemaNodes.Select(n => n.Name).Contains(specifierSplit[1]))
                        {
                            LogService.Log(db, data.Corporation, "Cannot cancel research for " + specifierSplit[1] + ". It is not currently being researched.");
                            continue;
                        }
                        var nodeToCancel = db.ActiveResearchNodes.FirstOrDefault(
                            n => n.Corporation.Id == data.Corporation.Id && n.ResearchNode.Name == specifierSplit[1]);
                        if (nodeToCancel == null)
                        {
                            LogService.Log(db, data.Corporation, specifierSplit[1] + " is not a valid research node name.");
                            continue;
                        }
                        db.Remove(nodeToCancel);
                        LogService.Log(db, data.Corporation, "Canceled research for " + specifierSplit[1] + ".");
                    }
                    //#HirePerson
                    else if (specifierSplit[0] == Constants.Constants.HirePerson)
                    {
                        var alreadyHired =
                            CorporationPerson.GetPeopleByHiredStatus(true, data.CorporationPersons).ToList();
                        var entity = data.CorporationPersons.FirstOrDefault(cp => cp.Person.Name == currentObjectName);
                        if (entity == null)
                        {
                            LogService.Log(db, data.Corporation, "Cannot find entity with name: " + currentObjectName + "!");
                            continue;
                        }
                        if (alreadyHired.Select(h => h.Person.Name).Contains(currentObjectName))
                        {
                            LogService.Log(db, data.Corporation, "Already hired " + currentObjectName + "! Action could not be completed.");
                            continue;
                        }
                        if ((data.Corporation.Cash + entity.Person.SigningBonus) < entity.Person.TurnSalary)
                        {
                            LogService.Log(db, data.Corporation, "Not enough funds to hire " + entity.Person.Name + "!");
                            continue;
                        }
                        entity.Hired = true;
                        data.Corporation.Cash -= entity.Person.SigningBonus;
                        data.Corporation.PublicInterest += entity.Person.Celebrity ? Constants.Constants.CelebrityBonus : 0;
                        data.Corporation.Reputation += entity.Person.Celebrity ? Constants.Constants.CelebrityBonus : 0;
                        data.Corporation.RD += entity.Person.Intelligence;
                        data.Corporation.Readiness += entity.Person.Experience;
                        data.Corporation.BusinessMultiplier += (double)entity.Person.Business / 100;
                        LogService.Log(db, data.Corporation, "Hired " + currentObjectName + " as " + entity.Person.Position + " for $" + entity.Person.TurnSalary + " salary and a signing bonus of $" + entity.Person.SigningBonus + ".");
                    }
                    //#FirePerson
                    else if (specifierSplit[0] == Constants.Constants.FirePerson)
                    {
                        var alreadyHired =
                            CorporationPerson.GetPeopleByHiredStatus(true, data.CorporationPersons).ToList();
                        var entity = data.CorporationPersons.FirstOrDefault(cp => cp.Person.Name == currentObjectName);
                        if (entity == null)
                        {
                            LogService.Log(db, data.Corporation, "Cannot find entity with name: " + currentObjectName + "!");
                            continue;
                        }
                        if (!alreadyHired.Select(h => h.Person.Name).Contains(currentObjectName))
                        {
                            LogService.Log(db, data.Corporation, "Cannot fire " + currentObjectName + " because they are not hired!");
                            continue;
                        }
                        entity.Hired = false;
                        data.Corporation.Cash -= entity.Person.SeverancePayout;
                        data.Corporation.PublicInterest -= entity.Person.Celebrity ? Constants.Constants.CelebrityBonus : 0;
                        data.Corporation.Reputation -= entity.Person.Celebrity ? Constants.Constants.CelebrityBonus : 0;
                        data.Corporation.RD -= entity.Person.Intelligence;
                        data.Corporation.Readiness -= entity.Person.Experience;
                        data.Corporation.BusinessMultiplier -= (double)entity.Person.Business / 100;
                        LogService.Log(db, data.Corporation, "Fired " + currentObjectName + ", saving $" + entity.Person.TurnSalary + " per turn, with a severance payout of $" + entity.Person.SeverancePayout + ".");
                    }
                    if (specifierSplit[0] == Constants.Constants.StartContract)
                    {
                        var contractName = specifierSplit[1];
                        var contract = data.CorporationContracts.FirstOrDefault(c => c.Contract.Name == contractName);
                        if (contract == null || contract.Accepted || !contract.Active || contract.Complete)
                        {
                            LogService.Log(db, data.Corporation, "Unable to begin contract " + contractName + ".");
                            continue;
                        }

                        LogService.Log(db, data.Corporation, "Accepted contract " + contractName + ".");

                        contract.Accepted = true;
                        contract.Active = true;
                        contract.Complete = false;
                        contract.NodeNumber = 1;
                    }
                    if (specifierSplit[0] == Constants.Constants.AdvanceContract)
                    {
                        var contractName = specifierSplit[1];
                        var corpContract =
                            data.CorporationContracts.FirstOrDefault(cc => cc.Contract.Name == contractName);
                        var memContract = data.ContractsInMemory.FirstOrDefault(mc => mc.Name == contractName);

                        if (corpContract == null || memContract == null || !corpContract.Active ||
                            !corpContract.Accepted || corpContract.Complete)
                        {
                            LogService.Log(db, data.Corporation, "Cannot advance contract " + contractName + ".");
                            continue;
                        }

                        var node =
                            memContract.ContractNodes.FirstOrDefault(cn => cn.NodeNumber == corpContract.NodeNumber);

                        if (node == null)
                        {
                            LogService.Log(db, data.Corporation, "Invalid contract node identifier. Cannot advance contract state for " + contractName + ".");
                            continue;
                        }

                        var param = currentActionDict[Constants.Constants.ActionParameter];
                        var option = node.ContractOptions.FirstOrDefault(o => o.OptionCommand == param);

                        if (option == null)
                        {
                            LogService.Log(db, data.Corporation, "Invalid contract option parameter. Cannot advance contract " + contractName + ".");
                            continue;
                        }

                        if (option.NextNode == Constants.Constants.Complete)
                        {
                            LogService.Log(db, data.Corporation, "Completed contract " + contractName + ".");
                            corpContract.Complete = true;
                            corpContract.Active = false;
                            continue;
                        }
                        else if (option.NextNode == Constants.Constants.Fail)
                        {
                            LogService.Log(db, data.Corporation, "Failed contract " + contractName + ".");
                            corpContract.Complete = false;
                            corpContract.Active = false;
                            continue;
                        }
                        else
                        {
                            //The quest isn't being completed or failed at this point,
                            //so change the current contract node to the advanced state.
                            corpContract.NodeNumber = Convert.ToInt32(option.NextNode);
                        }
                    }
                }
            }

            db.SaveChanges();
        }
コード例 #8
0
 public void Add(Category category)
 {
     _context.Add(category);
     _context.SaveChanges();
 }
コード例 #9
0
 public async Task Create(GPSIDEquipment gpsidEquipment)
 {
     _context.Add(gpsidEquipment);
     await _context.SaveChangesAsync();
 }
コード例 #10
0
 public async Task CreateGameUserAsync(GameUserModel gameUserModel)
 {
     db.Add(gameUserModel);
     await db.SaveChangesAsync();
 }
コード例 #11
0
        public async Task <IActionResult> Register(Register model)
        {
            if (string.IsNullOrEmpty(model.BrainTreePayment.Nonce))
            {
                ModelState.AddModelError("", "incomplete payment information provided");
            }
            else
            {
                try
                {
                    // get model state errors
                    var errors = ModelState.Values.SelectMany(v => v.Errors);

                    // if paying with a credit card the fields for credit card number/cvs/month/year will be invalid because we do not send them to the server
                    // so count the errors on the field validation that do not start with 'card ' (comes from the property attributes in the model class Apply.cs)
                    // TODO validate if this is still needed - all card validation has been removed b/c client side validation requires 'name' properties
                    //      which have been removed for PCI compliance.
                    var errorCount = errors.Count(m => !m.ErrorMessage.StartsWith("card "));
                    var result     = new ServiceResult();
                    if (errorCount == 0)
                    {
                        #region Process Payment
                        var paymentMethod = (PaymentTypeEnum)Enum.Parse(typeof(PaymentTypeEnum), model.BrainTreePayment.PaymentMethod);
                        var phone         = model.Attendee1PhoneNumber;
                        var paymentResult = new ServiceResult();

                        var paymentRequestResult = new ServiceResult();

                        if (paymentMethod == PaymentTypeEnum.Paypal)
                        {
                            paymentResult = _paymentService.SendPayment(model.TotalAmountDue,
                                                                        model.BrainTreePayment.Nonce,
                                                                        true,
                                                                        paymentMethod,
                                                                        model.BrainTreePayment.DeviceData,
                                                                        "golf reg fee",
                                                                        model.CustomerNotes,
                                                                        model.BrainTreePayment.PayeeFirstName,
                                                                        model.BrainTreePayment.PayeeLastName,
                                                                        phone,
                                                                        model.Attendee1EmailAddress);
                        }
                        else
                        {
                            var stateCode = _context.States.First(p => p.Id == model.BrainTreePayment.PayeeAddressStateId).Code;

                            paymentRequestResult = _paymentService.SendPayment(model.TotalAmountDue,
                                                                               model.BrainTreePayment.Nonce,
                                                                               true,
                                                                               paymentMethod,
                                                                               model.BrainTreePayment.DeviceData,
                                                                               "golf reg fee",
                                                                               model.CustomerNotes,
                                                                               model.BrainTreePayment.PayeeFirstName,
                                                                               model.BrainTreePayment.PayeeLastName,
                                                                               model.BrainTreePayment.PayeeAddressStreet1,
                                                                               model.BrainTreePayment.PayeeAddressStreet2,
                                                                               model.BrainTreePayment.PayeeAddressCity,
                                                                               stateCode,
                                                                               model.BrainTreePayment.PayeeAddressPostalCode,
                                                                               "US",
                                                                               phone,
                                                                               model.Attendee1EmailAddress);
                        }

                        if (!paymentRequestResult.IsSuccess)
                        {
                            // TODO: handle failure to pay
                            result.IsSuccess = false;
                            result.Messages.Add("Payment Failure - see below for details: ");
                            result.Messages.AddRange(paymentRequestResult.Messages);

                            _logger.LogError("Golf Registration Fee Payment Failed {@GolfRegFeePaymentErrors}", result.Messages);
                            ModelState.AddModelError("", "Unable to process your payment. Try again, and if the problem persists see your system administrator.");
                            foreach (var error in paymentRequestResult.Messages)
                            {
                                ModelState.AddModelError("", error);
                            }

                            RedirectToAction("Register");
                        }

                        // payment is a success. capture the transaction id from braintree
                        model.BrainTreePayment.BraintreeTransactionId = paymentRequestResult.NewKey;
                        #endregion

                        #region Database

                        var eventId        = new Guid(_systemServices.GetSetting("GolfTournamentId").Value);
                        var registrationId = Guid.NewGuid();

                        var numberOfTickets = 0;
                        if (!string.IsNullOrEmpty(model.Attendee1FirstName))
                        {
                            numberOfTickets += 1;
                        }
                        if (!string.IsNullOrEmpty(model.Attendee2FirstName))
                        {
                            numberOfTickets += 1;
                        }
                        if (!string.IsNullOrEmpty(model.Attendee3FirstName))
                        {
                            numberOfTickets += 1;
                        }
                        if (!string.IsNullOrEmpty(model.Attendee4FirstName))
                        {
                            numberOfTickets += 1;
                        }


                        #region Copy ViewModel to database Model
                        var dbRegistration = new Models.EventRegistration
                        {
                            Id                     = registrationId,
                            EventId                = eventId,
                            AmountPaid             = model.TotalAmountDue,
                            CommentsFromRegistrant = model.CustomerNotes,
                            HasPaid                = true,
                            SubmittedTimestamp     = DateTime.Now,
                            NumberTicketsBought    = numberOfTickets
                        };

                        dbRegistration.EventRegistrationPersons = new List <Models.EventRegistrationPerson>();

                        if (!string.IsNullOrEmpty(model.Attendee1FirstName))
                        {
                            dbRegistration.EventRegistrationPersons.Add(new Models.EventRegistrationPerson
                            {
                                Id                            = 1,
                                Address1                      = model.Attendee1AddressStreet1,
                                Address2                      = model.Attendee1AddressStreet2,
                                AmountPaid                    = model.Attendee1TicketPrice,
                                City                          = model.Attendee1AddressCity,
                                EmailAddress                  = model.Attendee1EmailAddress,
                                EventRegistrationId           = registrationId,
                                EventRegistrationPersonTypeId = int.Parse(model.Attendee1Type),
                                FirstName                     = model.Attendee1FirstName,
                                LastName                      = model.Attendee1LastName,
                                IsPrimaryPerson               = true,
                                FullName                      = model.Attendee1FullName,
                                StatesId                      = model.Attendee1AddressStateId,
                                PhoneNumber                   = model.Attendee1PhoneNumber,
                                ZipCode                       = model.Attendee1AddressPostalCode
                            });
                        }

                        if (!string.IsNullOrEmpty(model.Attendee2FirstName))
                        {
                            dbRegistration.EventRegistrationPersons.Add(new Models.EventRegistrationPerson
                            {
                                Id                            = 2,
                                Address1                      = model.Attendee2AddressStreet1,
                                Address2                      = model.Attendee2AddressStreet2,
                                AmountPaid                    = model.Attendee2TicketPrice,
                                City                          = model.Attendee2AddressCity,
                                EmailAddress                  = model.Attendee2EmailAddress,
                                EventRegistrationId           = registrationId,
                                EventRegistrationPersonTypeId = int.Parse(model.Attendee2Type),
                                FirstName                     = model.Attendee2FirstName,
                                LastName                      = model.Attendee2LastName,
                                IsPrimaryPerson               = false,
                                FullName                      = model.Attendee2FullName,
                                StatesId                      = model.Attendee2AddressStateId,
                                PhoneNumber                   = model.Attendee2PhoneNumber,
                                ZipCode                       = model.Attendee2AddressPostalCode
                            });
                        }

                        if (!string.IsNullOrEmpty(model.Attendee3FirstName))
                        {
                            dbRegistration.EventRegistrationPersons.Add(new Models.EventRegistrationPerson
                            {
                                Id                            = 3,
                                Address1                      = model.Attendee3AddressStreet1,
                                Address2                      = model.Attendee3AddressStreet2,
                                AmountPaid                    = model.Attendee3TicketPrice,
                                City                          = model.Attendee3AddressCity,
                                EmailAddress                  = model.Attendee3EmailAddress,
                                EventRegistrationId           = registrationId,
                                EventRegistrationPersonTypeId = int.Parse(model.Attendee3Type),
                                FirstName                     = model.Attendee3FirstName,
                                LastName                      = model.Attendee3LastName,
                                IsPrimaryPerson               = true,
                                FullName                      = model.Attendee3FullName,
                                StatesId                      = model.Attendee3AddressStateId,
                                PhoneNumber                   = model.Attendee3PhoneNumber,
                                ZipCode                       = model.Attendee3AddressPostalCode
                            });
                        }

                        if (!string.IsNullOrEmpty(model.Attendee4FirstName))
                        {
                            dbRegistration.EventRegistrationPersons.Add(new Models.EventRegistrationPerson
                            {
                                Id                            = 4,
                                Address1                      = model.Attendee4AddressStreet1,
                                Address2                      = model.Attendee4AddressStreet2,
                                AmountPaid                    = model.Attendee4TicketPrice,
                                City                          = model.Attendee4AddressCity,
                                EmailAddress                  = model.Attendee4EmailAddress,
                                EventRegistrationId           = registrationId,
                                EventRegistrationPersonTypeId = int.Parse(model.Attendee4Type),
                                FirstName                     = model.Attendee4FirstName,
                                LastName                      = model.Attendee4LastName,
                                IsPrimaryPerson               = true,
                                FullName                      = model.Attendee4FullName,
                                StatesId                      = model.Attendee4AddressStateId,
                                PhoneNumber                   = model.Attendee4PhoneNumber,
                                ZipCode                       = model.Attendee4AddressPostalCode
                            });
                        }
                        #endregion

                        #region Add to Database
                        _context.Add(dbRegistration);
                        #endregion

                        #region Save to Database and check exceptions
                        try
                        {
                            _logger.LogInformation("Saving golf registration to database: {@dbRegistration}", dbRegistration);
                            var numChanges = _context.SaveChanges();
                            if (numChanges > 0)
                            {
                                result.IsSuccess = true;
                            }
                        }
                        catch (DbUpdateException ex)
                        {
                            _logger.LogError(new EventId(1), ex, "Database Update Exception saving golf registration");
                        }
                        catch (InvalidOperationException ex)
                        {
                            _logger.LogError(new EventId(1), ex, "Invalid Operation Exception saving golf registration");
                        }
                        #endregion

                        #endregion

                        #region Send Emails
                        var groupEmail = _systemServices.GetSetting("Email-Golf").Value;

                        var subject = string.Join(" - ", "[TXHR Web]", "6th Annual Texas Husky Rescue Golf Registration");

                        var bodyText = @" 
Thank you for registering for Texas Husky Rescue's 6th Annual Golf Tournament.  We are very excited for this year's event and we have no doubt you will have a fabulous time.

You will be sent an email closer to the tournament with detailed information.  If you have any questions prior to then, please feel free to email us at [email protected].

Thanks again,
Texas Husky Rescue Golf Committee
1-877-TX-HUSKY (894-8759) (phone/fax)
PO Box 118891, Carrollton, TX 75011
";


                        // Send email to the primary registrant
                        if (model.Attendee1IsAttending)
                        {
                            var emailAppResult = await _emailService.SendEmailAsync(model.Attendee1EmailAddress, groupEmail, groupEmail, subject, bodyText, "golf-registration");
                        }
                        if (model.Attendee2IsAttending)
                        {
                            var emailAppResult = await _emailService.SendEmailAsync(model.Attendee2EmailAddress, groupEmail, groupEmail, subject, bodyText, "golf-registration");
                        }
                        if (model.Attendee3IsAttending)
                        {
                            var emailAppResult = await _emailService.SendEmailAsync(model.Attendee3EmailAddress, groupEmail, groupEmail, subject, bodyText, "golf-registration");
                        }
                        if (model.Attendee4IsAttending)
                        {
                            var emailAppResult = await _emailService.SendEmailAsync(model.Attendee4EmailAddress, groupEmail, groupEmail, subject, bodyText, "golf-registration");
                        }

                        bodyText  = "Golf registration for " + numberOfTickets + " attendees.";
                        bodyText += Environment.NewLine;
                        bodyText += Environment.NewLine;
                        bodyText += "Attendee 1: " + Environment.NewLine;
                        bodyText += "Name: " + model.Attendee1FullName + Environment.NewLine;
                        bodyText += "Address: " + model.Attendee1AddressStreet1 + " " + model.Attendee1AddressStreet2 + ", " + model.Attendee1AddressCity + ", " + model.Attendee1AddressPostalCode + Environment.NewLine;
                        bodyText += "Phone: " + (string.IsNullOrEmpty(model.Attendee1PhoneNumber) ? "not provided" : model.Attendee1PhoneNumber) + Environment.NewLine;
                        bodyText += "Email: " + (string.IsNullOrEmpty(model.Attendee1EmailAddress) ? "not provided" : model.Attendee1EmailAddress) + Environment.NewLine;
                        bodyText += "Mailable?: " + model.Attendee1FutureContact + Environment.NewLine;
                        bodyText += "Attendance Type: " + model.Attendee1Type + Environment.NewLine;
                        bodyText += "Ticket Price: " + model.Attendee1TicketPrice + Environment.NewLine;
                        bodyText += "-------------------------------------------------------------" + Environment.NewLine;
                        if (model.Attendee2IsAttending)
                        {
                            bodyText += "Attendee 2: " + Environment.NewLine;
                            bodyText += "Name: " + model.Attendee2FullName + Environment.NewLine;
                            bodyText += "Address: " + model.Attendee2AddressStreet1 + " " + model.Attendee2AddressStreet2 + ", " + model.Attendee2AddressCity + ", " + model.Attendee2AddressPostalCode + Environment.NewLine;
                            bodyText += "Phone: " + (string.IsNullOrEmpty(model.Attendee2PhoneNumber) ? "not provided" : model.Attendee2PhoneNumber) + Environment.NewLine;
                            bodyText += "Email: " + (string.IsNullOrEmpty(model.Attendee2EmailAddress) ? "not provided" : model.Attendee2EmailAddress) + Environment.NewLine;
                            bodyText += "Mailable?: " + model.Attendee2FutureContact + Environment.NewLine;
                            bodyText += "Attendance Type: " + model.Attendee2Type + Environment.NewLine;
                            bodyText += "Ticket Price: " + model.Attendee2TicketPrice + Environment.NewLine;
                            bodyText += "-------------------------------------------------------------" + Environment.NewLine;
                        }
                        if (model.Attendee3IsAttending)
                        {
                            bodyText += "Attendee 3: " + Environment.NewLine;
                            bodyText += "Name: " + model.Attendee3FullName + Environment.NewLine;
                            bodyText += "Address: " + model.Attendee3AddressStreet1 + " " + model.Attendee3AddressStreet2 + ", " + model.Attendee3AddressCity + ", " + model.Attendee3AddressPostalCode + Environment.NewLine;
                            bodyText += "Phone: " + (string.IsNullOrEmpty(model.Attendee3PhoneNumber) ? "not provided" : model.Attendee3PhoneNumber) + Environment.NewLine;
                            bodyText += "Email: " + (string.IsNullOrEmpty(model.Attendee3EmailAddress) ? "not provided" : model.Attendee3EmailAddress) + Environment.NewLine;
                            bodyText += "Mailable?: " + model.Attendee3FutureContact + Environment.NewLine;
                            bodyText += "Attendance Type: " + model.Attendee3Type + Environment.NewLine;
                            bodyText += "Ticket Price: " + model.Attendee3TicketPrice + Environment.NewLine;
                            bodyText += "-------------------------------------------------------------" + Environment.NewLine;
                        }
                        if (model.Attendee4IsAttending)
                        {
                            bodyText += "Attendee 4: " + Environment.NewLine;
                            bodyText += "Name: " + model.Attendee4FullName + Environment.NewLine;
                            bodyText += "Address: " + model.Attendee4AddressStreet1 + " " + model.Attendee4AddressStreet2 + ", " + model.Attendee4AddressCity + ", " + model.Attendee4AddressPostalCode + Environment.NewLine;
                            bodyText += "Phone: " + (string.IsNullOrEmpty(model.Attendee4PhoneNumber) ? "not provided" : model.Attendee4PhoneNumber) + Environment.NewLine;
                            bodyText += "Email: " + (string.IsNullOrEmpty(model.Attendee4EmailAddress) ? "not provided" : model.Attendee4EmailAddress) + Environment.NewLine;
                            bodyText += "Mailable?: " + model.Attendee4FutureContact + Environment.NewLine;
                            bodyText += "Attendance Type: " + model.Attendee4Type + Environment.NewLine;
                            bodyText += "Ticket Price: " + model.Attendee4TicketPrice + Environment.NewLine;
                            bodyText += "-------------------------------------------------------------" + Environment.NewLine;
                        }
                        bodyText += "Notes from the register: " + model.CustomerNotes + Environment.NewLine;
                        bodyText += "-------------------------------------------------------------" + Environment.NewLine;
                        bodyText += "Payee: " + Environment.NewLine;
                        bodyText += "Paid with " + model.BrainTreePayment.PaymentMethod + Environment.NewLine;
                        bodyText += "Name: " + model.BrainTreePayment.PayeeFirstName + " " + model.BrainTreePayment.PayeeLastName + Environment.NewLine;

                        var emailGroupResult = await _emailService.SendEmailAsync(groupEmail, groupEmail, groupEmail, subject, bodyText, "golf-registration");

                        #endregion

                        if (result.IsSuccess)
                        {
                            return(RedirectToAction("RegisterThankYou"));
                        }
                        else
                        {
                            foreach (var error in result.Messages)
                            {
                                ModelState.AddModelError(error.GetHashCode().ToString(), error);
                                _logger.LogError("Data Exception saving Golf Registration {@modelGolfReg}", model);
                            }

                            return(RedirectToAction("Register"));
                        }
                    }
                    _logger.LogInformation("Adoption App Model Errors {@errors} {@modelGolfReg}", result.Messages, model);
                }
                catch (Exception dex)
                {
                    //Log the error (uncomment dex variable name and add a line here to write a log.
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
                    _logger.LogError(new EventId(6), dex, "Data Exception saving Golf Registration {@modelGolfReg}", model);
                }
            }
            return(RedirectToAction("Register"));
        }
コード例 #12
0
        public async Task <IActionResult> Create([Bind("CharacterId,CharacterName,Gender,Level,ApplicationUserId,AncestryId")] Character character)
        {
            if (ModelState.IsValid)

            {
                //get current user and set user property on character to user
                ApplicationUser user = await GetCurrentUserAsync();

                character.ApplicationUserId = user.Id;

                //connection to veiw model
                CharacterCreateViewModel model = new CharacterCreateViewModel(_context);

                //make dropdown and assign to property on viewmodel
                model.AncestriesList = new SelectList(_context.Ancestry, "AncestryId", "AncestryId", character.AncestryId);

                //assign to property character on model
                model.Character = character;

                //if user selects non-human
                _context.Add(character);
                await _context.SaveChangesAsync();

                //if User select Human
                if (model.Character.AncestryId == 1)
                {
                    return(RedirectToAction("HumanAbilitiesForm", "HumanAbilities"));
                }

                else if (model.Character.AncestryId == 2)
                {
                    var abt = (from ab in _context.AncestryBaseTraits
                               join a in _context.Ancestry on ab.AncestryId equals a.AncestryId
                               where ab.AncestryId == 2
                               select ab.BaseValue)
                              .ToList();

                    CharTrait changelingTraitStrength = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 1,
                        CharTraitValue = abt.ElementAt(0).ToString()
                    };

                    //add to hold in db context
                    _context.Add(changelingTraitStrength);

                    CharTrait changelingTraitAgility = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 2,
                        CharTraitValue = abt.ElementAt(1).ToString()
                    };

                    //add to hold in db context
                    _context.Add(changelingTraitAgility);

                    CharTrait changelingTraitIntellect = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 3,
                        CharTraitValue = abt.ElementAt(2).ToString()
                    };

                    //add to hold in db context
                    _context.Add(changelingTraitIntellect);

                    CharTrait changelingTraitWill = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 4,
                        CharTraitValue = abt.ElementAt(3).ToString()
                    };

                    //add to hold in db context and save context to db
                    _context.Add(changelingTraitWill);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("UserHome", "ApplicationUser"));
                }
                //begin clockwork
                if (model.Character.AncestryId == 3)
                {
                    var abt = (from ab in _context.AncestryBaseTraits
                               join a in _context.Ancestry on ab.AncestryId equals a.AncestryId
                               where ab.AncestryId == 3
                               select ab.BaseValue)
                              .ToList();

                    CharTrait clockworkTraitStrength = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 1,
                        CharTraitValue = abt.ElementAt(0).ToString()
                    };

                    //add to hold in db context
                    _context.Add(clockworkTraitStrength);

                    CharTrait clockworkTraitAgility = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 2,
                        CharTraitValue = abt.ElementAt(1).ToString()
                    };

                    //add to hold in db context
                    _context.Add(clockworkTraitAgility);

                    CharTrait clockworkTraitIntellect = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 3,
                        CharTraitValue = abt.ElementAt(2).ToString()
                    };

                    //add to hold in db context
                    _context.Add(clockworkTraitIntellect);

                    CharTrait clockworkTraitWill = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 4,
                        CharTraitValue = abt.ElementAt(3).ToString()
                    };

                    //add to hold in db context and save context to db
                    _context.Add(clockworkTraitWill);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Create", "ClockworkPurposes"));
                }
                //end clockwork
                //begin dwarf
                if (model.Character.AncestryId == 4)
                {
                    var abt = (from ab in _context.AncestryBaseTraits
                               join a in _context.Ancestry on ab.AncestryId equals a.AncestryId
                               where ab.AncestryId == 4
                               select ab.BaseValue)
                              .ToList();

                    CharTrait dwarfTraitStrength = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 1,
                        CharTraitValue = abt.ElementAt(0).ToString()
                    };

                    //add to hold in db context
                    _context.Add(dwarfTraitStrength);

                    CharTrait dwarfTraitAgility = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 2,
                        CharTraitValue = abt.ElementAt(1).ToString()
                    };

                    //add to hold in db context
                    _context.Add(dwarfTraitAgility);

                    CharTrait dwarfTraitIntellect = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 3,
                        CharTraitValue = abt.ElementAt(2).ToString()
                    };

                    //add to hold in db context
                    _context.Add(dwarfTraitIntellect);

                    CharTrait dwarfTraitWill = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 4,
                        CharTraitValue = abt.ElementAt(3).ToString()
                    };

                    //add to hold in db context and save context to db
                    _context.Add(dwarfTraitWill);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("UserHome", "ApplicationUser"));
                }
                //end dwarf
                //begin goblin
                if (model.Character.AncestryId == 5)
                {
                    var abt = (from ab in _context.AncestryBaseTraits
                               join a in _context.Ancestry on ab.AncestryId equals a.AncestryId
                               where ab.AncestryId == 5
                               select ab.BaseValue)
                              .ToList();

                    CharTrait goblinTraitStrength = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 1,
                        CharTraitValue = abt.ElementAt(0).ToString()
                    };

                    //add to hold in db context
                    _context.Add(goblinTraitStrength);

                    CharTrait goblinTraitAgility = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 2,
                        CharTraitValue = abt.ElementAt(1).ToString()
                    };

                    //add to hold in db context
                    _context.Add(goblinTraitAgility);

                    CharTrait goblinTraitIntellect = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 3,
                        CharTraitValue = abt.ElementAt(2).ToString()
                    };

                    //add to hold in db context
                    _context.Add(goblinTraitIntellect);

                    CharTrait goblinTraitWill = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 4,
                        CharTraitValue = abt.ElementAt(3).ToString()
                    };

                    //add to hold in db context and save context to db
                    _context.Add(goblinTraitWill);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("UserHome", "ApplicationUser"));
                }
                //end goblin
                //begin orc
                if (model.Character.AncestryId == 6)
                {
                    var abt = (from ab in _context.AncestryBaseTraits
                               join a in _context.Ancestry on ab.AncestryId equals a.AncestryId
                               where ab.AncestryId == 6
                               select ab.BaseValue)
                              .ToList();

                    CharTrait orcTraitStrength = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 1,
                        CharTraitValue = abt.ElementAt(0).ToString()
                    };

                    //add to hold in db context
                    _context.Add(orcTraitStrength);

                    CharTrait orcTraitAgility = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 2,
                        CharTraitValue = abt.ElementAt(1).ToString()
                    };

                    //add to hold in db context
                    _context.Add(orcTraitAgility);

                    CharTrait orcTraitIntellect = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 3,
                        CharTraitValue = abt.ElementAt(2).ToString()
                    };

                    //add to hold in db context
                    _context.Add(orcTraitIntellect);

                    CharTrait orcTraitWill = new CharTrait
                    {
                        CharacterId    = model.Character.CharacterId,
                        TraitId        = 4,
                        CharTraitValue = abt.ElementAt(3).ToString()
                    };

                    //add to hold in db context and save context to db
                    _context.Add(orcTraitWill);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("UserHome", "ApplicationUser"));
                }
                //end orc

                return(View(character));
            }
            return(View());
        }
コード例 #13
0
 public CompraCreateDto Create(CompraCreateDto CompraCreateDto)
 {
     _context.Add(_mapper.Map <Compra>(CompraCreateDto));
     _context.SaveChanges();
     return(CompraCreateDto);
 }
コード例 #14
0
 public void Add(Client client)
 {
     _context.Add(client);
 }
コード例 #15
0
        private void SeedOfficers(IServiceProvider applicationServices)
        {
            using (var context = new ApplicationDbContext(
                applicationServices.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
            {
                if (context.List2.Any())
                {
                    return;   // DB has been seeded
                }

                var lines = File.ReadAllLines("wwwroot/MUleader_V2.csv");

                for (int i = 1; i < lines.Count(); i++)
                {
                    var items = lines[i].Split(',');
                    context.Add(new List2
                    {
                        //officerID,nameID,name,beginyr,endyr,cname,pos,cityID
                        officerID = long.Parse(items[0]),
                        nameID = long.Parse(items[1]),
                        name = items[2],
                        beginyr = long.Parse(items[3]),
                        endyr = long.Parse(items[4]),
                        cname = items[5],
                        pos = items[6],
                        cityID = items[7] != "" ? long.Parse(items[7]) : 0,
                        rid = -1
                    });
                }
                context.SaveChanges();
            }
        }
コード例 #16
0
        public async Task <IActionResult> Create(
            [Bind("RollNo,DepartmentId,FacultyId,Name,LastName,Image,Email,Phone,Id, Gender, ProjectId, Role")] Student student)
        {
            if (ModelState.IsValid)
            {
                _context.Add(student);
                await _context.SaveChangesAsync();

                // Here we will work on image
                var webRootPath   = _webHostEnvironment.WebRootPath;
                var files         = HttpContext.Request.Form.Files;
                var studentFromDb = await _context.Students.FindAsync(student.Id);

//======================== ===================== mean we choose a photo for student =============================================
                if (files.Any())
                {
                    // validate only the image is allowed
                    if (files[0].ContentType != "image/jpeg")
                    {
                        ModelState.AddModelError(string.Empty, "Failed! Only image type is allowed.");
                        ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "Name", student.DepartmentId);
                        ViewData["FacultyId"]    = new SelectList(_context.Faculties, "Id", "Description", student.FacultyId);
                        ViewData["ProjectId"]    = new SelectList(_context.Projects, "Id", "Name", student.ProjectId);

                        return(View(student));
                    }
                    var upload   = Path.Combine(webRootPath, "images");
                    var fileName = files[0].FileName;

                    await using (var fileStream =
                                     new FileStream(Path.Combine(upload, studentFromDb.Id + "_" + fileName), FileMode.Create))
                    {
                        files[0].CopyTo(fileStream);
                    }

                    studentFromDb.Image = @"\images\" + studentFromDb.Id + "_" + fileName;
                }
                // mean we didn't upload photo, so we use the default one
                else
                {
                    if (studentFromDb.Gender.ToString() == "Male")
                    {
                        var upload = Path.Combine(webRootPath,
                                                  @"images\" + StaticDetails.DefaultMale);
                        System.IO.File.Copy(upload, webRootPath + @"\images\" + studentFromDb.Id + "_" + StaticDetails.DefaultMale);
                        studentFromDb.Image = @"\images\" + studentFromDb.Id + "_" + StaticDetails.DefaultMale;
                    }
                    else
                    {
                        var upload = Path.Combine(webRootPath,
                                                  @"images\" + StaticDetails.DefaultFemale);
                        System.IO.File.Copy(upload, webRootPath + @"\images\" + studentFromDb.Id + "_" + StaticDetails.DefaultFemale);
                        studentFromDb.Image = @"\images\" + studentFromDb.Id + "_" + StaticDetails.DefaultFemale;
                    }
                }
                await _context.SaveChangesAsync();

//=================================================== End Of Image ============================================================
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "Name", student.DepartmentId);
            ViewData["FacultyId"]    = new SelectList(_context.Faculties, "Id", "Description", student.FacultyId);
            ViewData["ProjectId"]    = new SelectList(_context.Projects, "Id", "Name", student.ProjectId);

            return(View(student));
        }
コード例 #17
0
ファイル: Startup.cs プロジェクト: ChavFDG/Stolons
        private List<Stolon> CreateStolons(ApplicationDbContext context)
        {
            List<Stolon> stolons = new List<Stolon>();
            Stolon stolon = new Stolon();
            stolon.IsInMaintenance = false;
            stolon.IsModeSimulated = false;

            stolon.Label = "Stolons de Privas";
            stolon.AboutPageText = "Les Stolons de Privas est une association loi 1901";
            stolon.Address = "07000 PRIVAS";
            stolon.PhoneNumber = "06 64 86 66 93";
            stolon.ContactMailAddress = "*****@*****.**";

            stolon.DeliveryAndStockUpdateDayStartDate = DayOfWeek.Wednesday;
            stolon.DeliveryAndStockUpdateDayStartDateHourStartDate = 12;
            stolon.DeliveryAndStockUpdateDayStartDateMinuteStartDate = 00;
            stolon.OrderDayStartDate = DayOfWeek.Sunday;
            stolon.OrderHourStartDate = 16;
            stolon.OrderMinuteStartDate = 00;

            stolon.UseSubscipstion = true;
            stolon.SubscriptionStartMonth = Stolon.Month.September;

            stolon.OrderDeliveryMessage = "Votre panier est disponible jeudi de 17h30 à 19h au : 10 place de l'hotel de ville, 07000 Privas";

            stolon.UseProducersFee = true;
            stolon.ProducersFee = 5;

            stolon.UseSympathizer = true;
            stolon.SympathizerSubscription = 2;
            stolon.ConsumerSubscription = 10;
            stolon.ProducerSubscription = 20;

            context.Add(stolon);
            context.SaveChanges();

            stolons.Add(stolon);
            return stolons;
        }
コード例 #18
0
        public async Task <IActionResult> Create([Bind("sector,TypeOfWork,Salary")] Work work)
        {
            if (ModelState.IsValid)
            {
                //int bid = (int)TempData["Bid"];
                string person = TempData.Peek("Person") as string;

                if (TempData["Field"] != null)
                {
                    work.BeneficiarID = (int)TempData.Peek("BenId");
                    _context.Add(work);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("ChooseField", "Home"));
                }
                if (TempData["Field2"] != null)
                {
                    if (TempData.Peek("wid") != null)
                    {
                        work.WifeID = (int)TempData["wid"];
                    }
                    else if (TempData.Peek("cid") != null)
                    {
                        work.ChildID = (int)TempData["cid"];
                    }

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

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

                CreateModel model = TempData.Get <CreateModel>("model");
                string      s     = model.beneficiar.FirstName;


                if (person == "Wife")
                {
                    model.wife.work = work;
                    //TempData["model"] = model;
                    TempData.Put <CreateModel>("model", model);
                    return(Redirect("~/Beneficiars/New/AddingInfo/Children"));
                }

                if (person == "Child")
                {
                    //TempData["ChildWork"] = work;
                    //TempData["model"] = model;

                    model.children[model.children.Count - 1].work = work;
                    string t = model.children[model.children.Count - 1].work.TypeOfWork;
                    TempData.Put <CreateModel>("model", model);
                    return(Redirect("~/Beneficiars/New/AddingInfo/Children"));
                }

                //work.BeneficiarID = bid;
                //TempData["Work"] = work;

                model.work = work;
                string w = model.work.TypeOfWork;

                TempData.Put <CreateModel>("model", model);
                //TempData["model"] = model;

                int wi = model.work.Id;
                return(Redirect("~/Beneficiars/New/AddingInfo/Addresses"));
            }
            return(View(work));
        }
コード例 #19
0
ファイル: GestionDeCursos.cs プロジェクト: CarlosOlivares/web
        /// <summary>
        /// Método para crear un curso pasando como parámetro los atributos del curso.
        /// </summary>
        /// <param name="Nombre">Nombre del Curso</param>
        /// <param name="IdProfesor">Identificador de profesor</param>
        /// <param name="Version">Versión del curso</param>
        /// <param name="IdImagen">Identificador de imagen</param>
        /// <returns></returns>
        public bool CrearCurso(string Nombre, int IdProfesor,string Version,int IdImagen, int IdCategoria, string Contenido, string Requisitos)
        {
            this._Curso = new Cursos();
            this._Curso.Nombre = Nombre;
            this._Curso.UsuarioId = IdProfesor;
            this._Curso.CategoriaId = IdCategoria;
            this._Curso.Contenido = Contenido;
            this._Curso.Requisitos = Requisitos;

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                //TODO: Crear Gestión de Profesores
                 var q = from p in db.Usuario where p.UsuarioId == IdProfesor select p;
                this._Curso.Usuario = q.FirstOrDefault();
            }
            this._Curso.Version = Version;

            if(IdImagen != -1)
            {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                //TODO: Crear Gestión de Imagenes
                var q = from p in db.Imagen where p.ImagenId == IdImagen select p;
                this._Curso.Imagen = q.FirstOrDefault();
            }
            }
            else
            {
                this._Curso.ImagenId = 1;
            }
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                try
                {
                    db.Add(this._Curso);
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    return false;
                }

            }
            return true;
        }
コード例 #20
0
 public Task Subscribe(NewsletterSubscription newsletterSubscription)
 {
     _context.Add(newsletterSubscription);
     return(_context.SaveChangesAsync());
 }
コード例 #21
0
 public void Create(T entity)
 {
     _context.Add(entity);
     Save();
 }
コード例 #22
0
 //Inserindo Um Multa no banco de dados
 public void Insert(Multa obj)
 {
     _context.Add(obj);
     _context.SaveChanges();
 }
コード例 #23
0
        public async Task <ActionResult> Save(IEnumerable <IFormFile> files)
        {
            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {
                    var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

                    // Some browsers send file names with full path.
                    // We are only interested in the file name.
                    var fileName     = Path.GetFileName(fileContent.FileName.Trim('"'));
                    var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, DIR_IMAGE, fileName);
                    if (file.Length > 0)
                    {
                        using (var stream = new FileStream(physicalPath, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);

                            // Image.Load(string path) is a shortcut for our default type. Other pixel formats use Image.Load<TPixel>(string path))
                        }

                        using (Image <Rgba32> image = Image.Load(physicalPath))
                        {
                            var folderSave = Path.Combine(HostingEnvironment.WebRootPath, DIR_IMAGE + "\\1300x500", fileName);
                            image.Resize(1300, 500)
                            .Save(folderSave);      // automatic encoder selected based on extension.
                            folderSave = Path.Combine(HostingEnvironment.WebRootPath, DIR_IMAGE + "\\182x268", fileName);
                            image.Resize(182, 268)
                            .Save(folderSave);      // automatic encoder selected based on extension.
                            folderSave = Path.Combine(HostingEnvironment.WebRootPath, DIR_IMAGE + "\\115x175", fileName);
                            image.Resize(115, 175)
                            .Save(folderSave);      // automatic encoder selected based on extension.
                            folderSave = Path.Combine(HostingEnvironment.WebRootPath, DIR_IMAGE + "\\1140x641", fileName);
                            image.Resize(1140, 641)
                            .Save(folderSave);
                            folderSave = Path.Combine(HostingEnvironment.WebRootPath, DIR_IMAGE + "\\268x268", fileName);
                            image.Resize(268, 268)
                            .Save(folderSave);
                            folderSave = Path.Combine(HostingEnvironment.WebRootPath, DIR_IMAGE + "\\640x351", fileName);
                            image.Resize(640, 351)
                            .Save(folderSave);
                            var user = await GetCurrentUserAsync();

                            _context.Add(new Images
                            {
                                CreateDT    = System.DateTime.Now,
                                Name        = fileName,
                                Pic1300x500 = "\\" + DIR_IMAGE + "\\1300x500\\" + fileName,
                                Pic182x268  = "\\" + DIR_IMAGE + "\\182x268\\" + fileName,
                                Pic115x175  = "\\" + DIR_IMAGE + "\\115x175\\" + fileName,
                                Pic1140x641 = "\\" + DIR_IMAGE + "\\1140x641\\" + fileName,
                                Pic268x268  = "\\" + DIR_IMAGE + "\\268x268\\" + fileName,
                                Pic640x351  = "\\" + DIR_IMAGE + "\\640x351\\" + fileName,
                                Active      = "A",
                                Approved    = "A",
                                AuthorID    = user.Id,
                                IsDeleted   = false
                            });
                            await _context.SaveChangesAsync();
                        }
                    }
                }
            }

            // Return an empty string to signify success
            return(Content(""));
        }
コード例 #24
0
 public async Task Add(Post post)
 {
     post.Created = DateTime.Now;
     _context.Add(post);
     await _context.SaveChangesAsync();
 }
コード例 #25
0
 public IActionResult Create(Item itemToAdd)
 {
     dbContext.Add(itemToAdd);
     dbContext.SaveChanges();
     return(RedirectToAction(nameof(Index)));
 }
コード例 #26
0
 public void Add(Religion newReligion)
 {
     _context.Add(newReligion);
     _context.SaveChanges();
 }
コード例 #27
0
        public async Task <IActionResult> SuccessAsync()
        {
            var applicationDbContext = await _context.Orders.Include(o => o.Category)
                                       .Include(o => o.CustomUser)
                                       .Include(o => o.OrderStatus)
                                       .Include(o => o.Item)
                                       .OrderByDescending(o => o.Updated).ToListAsync();

            List <Order> orderList = new List <Order>();

            foreach (var item in applicationDbContext)
            {
                var trackingNumber = item.TrackingNumber;
                if (!orderList.Select(o => o.TrackingNumber).Contains(trackingNumber))
                {
                    orderList.Add(item);
                }
            }

            await DeleteOrder180DayAgoAsync();

            var TrackingNumber = CreateTrackingNumber();

            var CartList = await _context.Cart.Where(i => i.CustomUserId == _userManager.GetUserId(User) && !i.IsSold)
                           .Include(i => i.Category)
                           .Include(i => i.CustomUser)
                           .ToListAsync();

            var ReceivedStatus = _context.OrderStatuses.FirstOrDefault(o => o.Name == "Received").Id;
            var user           = await _userManager.FindByIdAsync(CartList.First().CustomUserId);

            var currentTime = DateTimeOffset.Now;

            foreach (var items in CartList)
            {
                //update number of sold item
                var item_of_shop = _context.Item.FirstOrDefault(i => i.Id == items.ItemId);
                item_of_shop.Number_Of_Sold += 1;
                await _canUserComment.AddUserToItemAsync(user.Id, items.ItemId);

                _context.Update(item_of_shop);
                await _context.SaveChangesAsync();

                Order newOrder = new Order
                {
                    TrackingNumber = TrackingNumber,
                    Name           = items.Name,
                    Price          = items.Price,
                    CustomUserId   = items.CustomUserId,
                    CategoryId     = items.CategoryId,
                    ItemId         = items.ItemId,
                    Quantity       = items.Quantity,
                    IsSold         = true,
                    ImageData      = items.ImageData,
                    ContentType    = items.ContentType,
                    Date           = currentTime,
                    Notes          = items.Notes,
                    Slug           = items.Slug,
                    IsViewByOwner  = false,
                    OrderStatusId  = ReceivedStatus,
                    TrackingLink   = "We are currently working on tracking link!",
                    Created        = currentTime,
                    Updated        = currentTime,
                    FirstName      = user.FirstName,
                    LastName       = user.LastName,
                    PhoneNumber    = user.PhoneNumber,
                    Email          = user.Email,
                    Adress         = user.Street,
                    State          = user.State,
                    City           = user.City,
                    Zipcode        = user.Zipcode
                };
                _context.Add(newOrder);
                await _context.SaveChangesAsync();

                _context.Cart.Remove(items);
                await _context.SaveChangesAsync();
            }


            var callbackUrl = Url.Action(
                "TrackOrderDetails",
                "Orders",
                values: new { TrackingNumber = TrackingNumber },
                protocol: Request.Scheme);

            await _emailSender.SendEmailAsync(user.Email, "Lan's Market received your order",
                                              $"<h1>You successfully placed an order on Lan's Market at {(currentTime).ToString("dd MMMM yyyy - hh:mm tt")}</h1> <br> <a style='background-color: #555555;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;' href='{HtmlEncoder.Default.Encode(callbackUrl)}'>Clicking here to track your order</a>  <br> <h3>Your Tracking Number is: {TrackingNumber} </h3> <br>");


            await _emailSender.SendEmailAsync("*****@*****.**", "New order has been placed at Lan's Market",
                                              $"<h1>A new order have been placed at {(currentTime).ToString("dd MMMM yyyy - hh:mm tt")}</h1> <br> <a style='background-color: #555555;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;' href='{HtmlEncoder.Default.Encode(callbackUrl)}'>Clicking here to go to order</a>  <br> <h3>Tracking Number is: {TrackingNumber} </h3> <br>");


            ViewData["TrackingNumber"] = TrackingNumber;
            return(View());
        }
コード例 #28
0
 public void AddDislikePost(DislikePost dislikePost)
 {
     context.Add(dislikePost);
     context.SaveChanges();
 }
コード例 #29
0
 public void Add <T>(T entity) where T : class
 {
     _context.Add(entity);
 }
コード例 #30
0
        public async Task <IActionResult> PushToDB()
        {
            CreateModel model = TempData.Get <CreateModel>("model");

            // CreateModel model = null;
            string n = model.beneficiar.FirstName;

            //int dw = model.wife.disease.ID;

            _context.Add(model.beneficiar);
            await _context.SaveChangesAsync();

            int B = model.beneficiar.Id;

            if (model.disease != null)
            {
                model.disease.BeneficiarID = B;
                _context.Add(model.disease);
                await _context.SaveChangesAsync();
            }
            if (model.work != null)
            {
                model.work.BeneficiarID = B;
                _context.Add(model.work);
                await _context.SaveChangesAsync();
            }
            if (model.wife != null)
            {
                model.wife.BeneficiarID = B;
                _context.Add(model.wife);
                await _context.SaveChangesAsync();

                // int W = model.wife.Id;
            }

            model.address.BeneficiarID = B;
            _context.Add(model.address);
            await _context.SaveChangesAsync();

            if (model.loans != null)
            {
                model.loans.BeneficiarID = B;
                _context.Add(model.loans);
                await _context.SaveChangesAsync();
            }
            if (model.belongings != null)
            {
                string t = model.belongings.rentIncomeType;
                model.belongings.BeneficiarID = B;
                _context.Add(model.belongings);
                await _context.SaveChangesAsync();
            }
            if (model.SocialHelp != null)
            {
                model.SocialHelp.BeneficiarID = B;
                _context.Add(model.SocialHelp);
                await _context.SaveChangesAsync();
            }
            for (int i = 0; i < model.children.Count; i++)
            {
                model.children[i].BeneficiarID = B;
                _context.Add(model.children[i]);
                await _context.SaveChangesAsync();
            }


            return(Redirect("~/Beneficiars"));
        }
コード例 #31
0
        public async Task <IActionResult> Create(CustomEstimateCostCreateViewModel customEstimateCosts)
        {
            List <CustomEstimateCost> CustomEstimateCostsInContext = await _context.CustomEstimateCost
                                                                     .Where(cec => cec.EstimateId == customEstimateCosts.EstimateId).ToListAsync();

            List <CustomEstimateCost> CostsEntered = (customEstimateCosts.CustomCosts?.Count > 0) ?
                                                     customEstimateCosts.CustomCosts : customEstimateCosts.RejectedEntries;
            List <CustomEstimateCost> RejectecdEntries = new List <CustomEstimateCost>();
            List <CustomEstimateCost> UpdatedRecords   = new List <CustomEstimateCost>();

            Estimate Estimate = await _context.Estimate.FirstOrDefaultAsync(e => e.Id == customEstimateCosts.EstimateId);

            foreach (var cost in CostsEntered.ToList())
            {
                CustomEstimateCost ExistingCost = new CustomEstimateCost();

                if (cost.ItemName != null)
                {
                    ExistingCost = CustomEstimateCostsInContext
                                   .FirstOrDefault(cec => cec.EstimateId == cost.EstimateId && cec.ItemName.ToUpper() == cost.ItemName.ToUpper());
                }
                else
                {
                    ExistingCost = null;
                }

                if (cost.ItemName == null || cost.UnitOfMeasure == null || cost.CostPerUnit <= 0 ||
                    cost.Quantity == 0 || cost.MarkupPercent <= 0)
                {
                    CostsEntered.Remove(cost);
                    RejectecdEntries.Add(cost);
                }

                if (ExistingCost != null)
                {
                    ExistingCost.Quantity += cost.Quantity;
                    CostsEntered.Remove(cost);
                    UpdatedRecords.Add(ExistingCost);

                    _context.Update(ExistingCost);
                    await _context.SaveChangesAsync();
                }
            }

            foreach (var estimateCost in CostsEntered)
            {
                _context.Add(estimateCost);
                await _context.SaveChangesAsync();
            }

            if (RejectecdEntries.Count > 0 || UpdatedRecords.Count > 0)
            {
                CustomEstimateCostCreateViewModel viewModel = new CustomEstimateCostCreateViewModel {
                    EstimateId      = customEstimateCosts.EstimateId,
                    RejectedEntries = RejectecdEntries,
                    UpdatedRecords  = UpdatedRecords
                };


                ViewData["EstimateId"] = customEstimateCosts.EstimateId;
                return(View("CreateFinish", viewModel));
            }
            return(RedirectToAction("Details", "Estimate", new { id = customEstimateCosts.EstimateId }));
        }
コード例 #32
0
 public void Create(T entity)
 {
     _context.Add(entity);
     _context.SaveChanges();
 }
コード例 #33
0
ファイル: Startup.cs プロジェクト: ChavFDG/Stolons
        private void CreateProductsSamples(ApplicationDbContext context)
        {
            if (context.Products.Any())
                return;
            Product pain = new Product();
            pain.Name = "Pain complet";
            pain.Description = "Pain farine complete T80";
            pain.Labels.Add(Product.Label.Ab);
            pain.PicturesSerialized = Path.Combine("pain.png");
            pain.Price = Convert.ToDecimal(15.5);
            pain.UnitPrice = 4;
            pain.TaxEnum = Product.TAX.Ten;
            pain.Producer = context.Producers.First();
            pain.ProductUnit = Product.Unit.Kg;
            pain.StockManagement = Product.StockType.Week;
            pain.RemainingStock = 10;
            pain.State = Product.ProductState.Enabled;
            pain.Type = Product.SellType.Piece;
            pain.WeekStock = 10;
            pain.Familly = context.ProductFamillys.First(x => x.FamillyName == "Pains");
            context.Add(pain);
            Product tomate = new Product();
            tomate.Name = "Tomates grappe";
            tomate.Description = "Avec ces tomates, c'est nous qui rougissons même si elles ne sont pas toutes nues!";
            tomate.Labels.Add(Product.Label.Ab);
            tomate.PicturesSerialized = Path.Combine("tomate.jpg");
            tomate.Price = 3;
            tomate.TaxEnum = Product.TAX.FiveFive;
            tomate.UnitPrice = Convert.ToDecimal(1.5);
            tomate.QuantityStep = 500;
            tomate.Producer = context.Producers.First();
            tomate.ProductUnit = Product.Unit.Kg;
            tomate.StockManagement = Product.StockType.Week;
            tomate.RemainingStock = 10;
            tomate.Familly = context.ProductFamillys.First(x => x.FamillyName == "Légumes");
            tomate.State = Product.ProductState.Enabled;
            tomate.Type = Product.SellType.Weigh;
            tomate.WeekStock = 10;
            context.Add(tomate);
            Product pommedeterre = new Product();
            pommedeterre.Name = "Pomme de terre";
            pommedeterre.Description = "Pataaaaaaaaaaaaaaaates!!";
            pommedeterre.Labels.Add(Product.Label.Ab);
            pommedeterre.PicturesSerialized = Path.Combine("pommedeterre.jpg");
            pommedeterre.Price = Convert.ToDecimal(1.99);
            pommedeterre.TaxEnum = Product.TAX.FiveFive;
            pommedeterre.UnitPrice = Convert.ToDecimal(1.99);
            pommedeterre.QuantityStep = 1000;
            pommedeterre.Producer = context.Producers.First();
            pommedeterre.ProductUnit = Product.Unit.Kg;
            pommedeterre.StockManagement = Product.StockType.Week;
            pommedeterre.RemainingStock = 10;
            pommedeterre.Familly = context.ProductFamillys.First(x => x.FamillyName == "Légumes");
            pommedeterre.State = Product.ProductState.Enabled;
            pommedeterre.Type = Product.SellType.Weigh;
            pommedeterre.WeekStock = 10;
            context.Add(pommedeterre);
            Product radis = new Product();
            radis.Name = "Radis";
            radis.Description = "Des supers radis (pour ceux qui aiment)";
            radis.Labels.Add(Product.Label.Ab);
            radis.PicturesSerialized = Path.Combine("radis.jpg");
            radis.Price = 0;
            radis.UnitPrice = 4;
            radis.TaxEnum = Product.TAX.FiveFive;
            radis.Producer = context.Producers.First();
            radis.ProductUnit = Product.Unit.Kg;
            radis.StockManagement = Product.StockType.Week;
            radis.RemainingStock = 10;
            radis.Familly = context.ProductFamillys.First(x => x.FamillyName == "Légumes");
            radis.State = Product.ProductState.Enabled;
            radis.Type = Product.SellType.Piece;
            radis.WeekStock = 10;
            context.Add(radis);
            Product salade = new Product();
            salade.Name = "Salade";
            salade.Description = "Une bonne salade pour aller avec les bonnes tomates!";
            salade.Labels.Add(Product.Label.Ab);
            salade.PicturesSerialized = Path.Combine("salade.jpg");
            salade.UnitPrice = Convert.ToDecimal(0.80);
            salade.TaxEnum = Product.TAX.FiveFive;
            salade.Price = 0;
            salade.Producer = context.Producers.First();
            salade.ProductUnit = Product.Unit.Kg;
            salade.StockManagement = Product.StockType.Week;
            salade.RemainingStock = 10;
            salade.Familly = context.ProductFamillys.First(x => x.FamillyName == "Légumes");
            salade.State = Product.ProductState.Enabled;
            salade.Type = Product.SellType.Piece;
            salade.WeekStock = 10;
            context.Add(salade);
            Product conserveTomate = new Product();
            conserveTomate.Name = "Bocaux de tomate 500ml";
            conserveTomate.Description = "Bocaux de tomate du jardin, cuillie mur et transformé dans la semaine. Bocaux en verre d'une contenance de 500ml";
            conserveTomate.PicturesSerialized = Path.Combine("ConserveTomate.jpg");
            conserveTomate.UnitPrice = Convert.ToDecimal(4);
            conserveTomate.TaxEnum = Product.TAX.None;
            conserveTomate.Price = 0;
            conserveTomate.Producer = context.Producers.First();
            conserveTomate.ProductUnit = Product.Unit.L;
            conserveTomate.StockManagement = Product.StockType.Fixed;
            conserveTomate.RemainingStock = 10;
            conserveTomate.Familly = context.ProductFamillys.First(x => x.FamillyName == "Légumes");
            conserveTomate.State = Product.ProductState.Enabled;
            conserveTomate.Type = Product.SellType.Piece;
            conserveTomate.WeekStock = 0;
            context.Add(conserveTomate);


            //
            context.SaveChanges();
        }
コード例 #34
0
 public void Add(UserProfile userprofile)
 {
     _context.Add(userprofile);
     _context.SaveChanges();
 }
コード例 #35
0
ファイル: Startup.cs プロジェクト: ChavFDG/Old-Stolons
        private void SetGlobalConfigurations(ApplicationDbContext context)
        {

            if (context.ApplicationConfig.Any())
            {
                Configurations.ApplicationConfig = context.ApplicationConfig.First();
            }
            else
            {
                Configurations.ApplicationConfig = new ApplicationConfig();
                context.Add(Configurations.ApplicationConfig);
                context.SaveChanges();
            }

        }
コード例 #36
0
 public async Task Create(TAGIDEquipment tAGIDEquipment)
 {
     _context.Add(tAGIDEquipment);
     await _context.SaveChangesAsync();
 }
コード例 #37
0
ファイル: GestionDeCursos.cs プロジェクト: CarlosOlivares/web
        /// <summary>
        /// Método para crear un nuevo curso si se ha declarado antes el atributo curso.
        /// </summary>
        /// <returns></returns>
        public bool CrearCurso()
        {
            if (this._Curso == null) return false;

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                db.Add(this._Curso);
                db.SaveChanges();
                return true;
            }
        }
コード例 #38
0
 public BankAccount Add(BankAccount bankAccount)
 {
     _context.Add(bankAccount);
     _context.SaveChanges();
     return(bankAccount);
 }
コード例 #39
0
ファイル: GestionDeCursos.cs プロジェクト: CarlosOlivares/web
        public bool CrearClase(Clase clase)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                try
                {
                    db.Add(clase);
                    db.SaveChanges();
                    return true;
                }
                catch (Exception)
                {

                    return false;
                }

            }
        }
コード例 #40
0
ファイル: ResearchTree.cs プロジェクト: taylorrobert/WebRPG
        public static void CreateTestTreeInDB(ApplicationDbContext db, Corporation corp)
        {
            var node1 = new ResearchNode
            {
                Name = "Basic Rocketry",
                Description = "The basics.",
                RDCost = 10,
                CashCost = 50000,
                Script = "Action=LearnResearch:Basic Rocketry;Unlocks=Intermediate Rocketry;"
            };

            var node2 = new ResearchNode
            {
                Name = "Intermediate Rocketry",
                Description = "Werner von Braun would be delighted.",
                RDCost = 30,
                CashCost = 400000,
                Script = "Action=LearnResearch:Intermediate Rocketry;Prereq=Basic Rocketry;Unlocks=Advanced Rocketry"
            };

            var node3 = new ResearchNode
            {
                Name = "Advanced Rocketry",
                Description = "Einstein ain't got shit on these badass rockets.",
                RDCost = 75,
                CashCost = 4000000,
                Script = "Action=LearnResearch:Advanced Rocketry;Prereq=Intermediate Rocketry&Basic Rocketry;"
            };

            var learnedNode1 = new LearnedResearchNode()
            {
                Corporation = corp,
                ResearchNode = node1
            };

            db.Add(node1);
            db.Add(node2);
            db.Add(node3);
            db.Add(learnedNode1);
            db.SaveChanges();
        }