Exemple #1
0
 public void RemoveBudget(Budget budget)
 {
     if (budgets.Contains(budget))
     {
         budgets.Remove(budget);
     }
 }
 protected override void Initialize()
 {
     user = new User { Id = Guid.NewGuid(), FirstName = "Test", LastName = "User", Email = "*****@*****.**", DisplayName = "Sir. Test User" };
     budget = new Budget { Id = Guid.NewGuid(), StartDate = DateTime.Now, EndDate = DateTime.Now.AddMonths(12), Frequency = Frequency.Monthly };
     category = new Category { Id = Guid.NewGuid(), Name = "Bills", Frequency = budget.Frequency };
     transaction = new Transaction { Id = Guid.NewGuid(), Description = "Test Transaction", Amount = 15.00m, Date = DateTime.Now, TransactionType = TransactionType.Outgoing };
 }
        /// <summary>
        ///     Validates budget
        /// </summary>
        /// <param name="budget">Budget to validate</param>
        /// <returns>True if budget is valid, false otherwise</returns>
        public void Validate(Budget budget)
        {
            if (budget == null)
                throw new ArgumentNullException(nameof(budget));

            this._validator.ValidateAndThrowCustomException(budget);
        }
 public static Budget createObj(Budget e)
 {
     using (var context = new EventContainer())
     {
         context.Budgets.Add(e);
         context.SaveChanges();
         return e;
     }
 }
        public static Budget updateObj(Budget e)
        {
            using (var context = new EventContainer())
            {
                context.Entry(e).State = EntityState.Modified;
                context.SaveChanges();

                return e;
            }
        }
        public Budget Create(CreateBudgetCommand command)
        {
            var service = new Budget(command.Proposal, command.Price, command.ProposalDate, command.Status, command.SessionPrice, command.IdCoachingProcess);
            service.Validate();
            _repository.Create(service);

            if (Commit())
                return service;

            return null;
        }
        void When(BudgetCreated evnt)
        {
            if (_budgets.ContainsKey(evnt.BudgetId.ToString()))
                return;

            //var userName = _userNames[evnt.Owner.ToString()];
            var userName = "******";

            var s = new Budget();
            s.Apply(evnt, userName);
            _budgets.Add(evnt.BudgetId.ToString(), s);
        }
 public static Budget create(int allocatedBudget)
 {
     using (var context = new EventContainer())
     {
         Budget budget = new Budget
         {
             AllocatedBudget = allocatedBudget
         };
         context.Budgets.Add(budget);
         context.SaveChanges();
         return budget;
     }
 }
 public static Budget update(int allocatedBudget)
 {
     using (var context = new EventContainer())
     {
         Budget budget = new Budget
         {
             AllocatedBudget = allocatedBudget
         };
         context.Budgets.Attach(budget);
         context.Entry(budget).State = EntityState.Modified;
         context.SaveChanges();
         return budget;
     }
 }
Exemple #10
0
 public void AddBudget(Budget budget)
 {
     if (periodType != PeriodType.Custom)
     {
         if (budget.Period != getPeriod(budget.Period.StartDate, 0))
             throw new InvalidOperationException("Invalid Period Specified.");
     }
     if (budgets.Exists(b => b.Period == budget.Period))
     {
         throw new DuplicateObjectException(ErrorStrings.BudgetExists);
     }
     budget.Manager = this;
     budgets.Add(budget);
 }
        protected override void LoadState(object navigationParameter, Dictionary<string, object> pageState)
        {
            App.Instance.Share = null;

            currBudget = navigationParameter as Budget;

            DefaultViewModel["Budget"] = currBudget;

            this.IsEnabled = currBudget != null;

            this.UpdateLayout();

            InitControls();
        }
        public Budget AddBudget(EditBudgetViewModel vm, string username)
        {
            var budget = new Budget
            {
                Name = vm.Name,
                StartDate = vm.StartDate,
                EndDate = vm.EndDate,
                Username = username
            };

            FinancialPlannerRepository.AddBudget(budget);
            FinancialPlannerRepository.Save();

            return budget;
        }
    public long CreateBudget(AdWordsUser user) {
      BudgetService budgetService =
          (BudgetService) user.GetService(AdWordsService.v201509.BudgetService);

      // Create the campaign budget.
      Budget budget = new Budget();
      budget.name = "Interplanetary Cruise Budget #" + DateTime.Now.ToString(
          "yyyy-M-d H:m:s.ffffff");
      budget.period = BudgetBudgetPeriod.DAILY;
      budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
      budget.amount = new Money();
      budget.amount.microAmount = 500000;

      BudgetOperation budgetOperation = new BudgetOperation();
      budgetOperation.@operator = Operator.ADD;
      budgetOperation.operand = budget;

      BudgetReturnValue budgetRetval = budgetService.mutate(new BudgetOperation[] { budgetOperation });
      return budgetRetval.value[0].budgetId;
    }
Exemple #14
0
 private decimal GetIncomeVsExpenditure(Budget budget)
 {
     return(budget.Incomes.Sum(x => x.Actual) - budget.Outgoings.Sum(x => x.Actual));
 }
Exemple #15
0
 public Task <CommandLineResult> Publish(string args, Budget budget = null) =>
 Execute("publish".AppendArgs(args), budget);
Exemple #16
0
 protected override void OnPanelMessage(string panelName, string msgType, string[] msgParams)
 {
     if (msgType == "button_clicked")
     {
         if (panelName == "okButton")
         {
             this._app.UI.CloseDialog((Dialog)this, true);
         }
         else if (panelName.Contains("startButton"))
         {
             SpecialProjectInfo specialProjectInfo = this._app.GameDatabase.GetSpecialProjectInfo(int.Parse(panelName.Split('|')[1]));
             if (specialProjectInfo == null || specialProjectInfo.Progress != -1)
             {
                 return;
             }
             this._contextProject             = specialProjectInfo;
             this._confirmProjectChangeDialog = this._app.UI.CreateDialog((Dialog) new GenericQuestionDialog(this._app, App.Localize("@UI_SALVAGE_RESEARCH_START_TITLE"), App.Localize("@UI_SALVAGE_RESEARCH_START_DESC"), "dialogGenericQuestion"), null);
         }
         else
         {
             if (!panelName.Contains("cancelButton"))
             {
                 return;
             }
             SpecialProjectInfo specialProjectInfo = this._app.GameDatabase.GetSpecialProjectInfo(int.Parse(panelName.Split('|')[1]));
             if (specialProjectInfo == null || specialProjectInfo.Progress <= -1)
             {
                 return;
             }
             this._contextProject             = specialProjectInfo;
             this._confirmProjectChangeDialog = this._app.UI.CreateDialog((Dialog) new GenericQuestionDialog(this._app, App.Localize("@UI_SALVAGE_RESEARCH_CANCEL_TITLE"), App.Localize("@UI_SALVAGE_RESEARCH_CANCEL_DESC"), "dialogGenericQuestion"), null);
         }
     }
     else if (msgType == "slider_value")
     {
         if (panelName.Contains("projectRate"))
         {
             this.SetRate(int.Parse(panelName.Split('|')[1]), (float)int.Parse(msgParams[0]) / 100f);
         }
         else
         {
             PlayerInfo playerInfo = this._app.GameDatabase.GetPlayerInfo(this._app.LocalPlayer.ID);
             if (panelName == SalvageProjectDialog.UIGovernmentResearchSlider)
             {
                 float num = ((float)int.Parse(msgParams[0]) / 100f).Clamp(0.0f, 1f);
                 playerInfo.RateGovernmentResearch = 1f - num;
                 if (this._app.GameDatabase.GetSliderNotchSettingInfo(playerInfo.ID, UISlidertype.SecuritySlider) != null)
                 {
                     EmpireSummaryState.DistributeGovernmentSpending(this._app.Game, EmpireSummaryState.GovernmentSpendings.Security, (float)Math.Min((double)Budget.GenerateBudget(this._app.Game, playerInfo, (IEnumerable <DesignInfo>)null, BudgetProjection.Pessimistic).RequiredSecurity / 100.0, 1.0), playerInfo);
                 }
                 else
                 {
                     this._app.GameDatabase.UpdatePlayerSliders(this._app.Game, playerInfo);
                 }
                 this._researchPoints = this._app.Game.ConvertToResearchPoints(this._app.LocalPlayer.ID, Budget.GenerateBudget(this._app.Game, playerInfo, (IEnumerable <DesignInfo>)null, BudgetProjection.Actual).ResearchSpending.RequestedTotal);
                 this._salvagePoints  = (int)((double)this._researchPoints * (double)playerInfo.RateResearchSalvageResearch);
                 Budget budget = Budget.GenerateBudget(this._app.Game, playerInfo, (IEnumerable <DesignInfo>)null, BudgetProjection.Pessimistic);
                 this._piechart.SetSlices(budget);
                 this._behindPiechart.SetSlices(budget);
                 this._app.UI.ShakeViolently("piechartD");
             }
             else if (panelName == SalvageProjectDialog.UICurrentProjectSlider)
             {
                 EmpireSummaryState.DistibuteResearchSpending(this._app.Game, this._app.GameDatabase, EmpireSummaryState.ResearchSpendings.CurrentProject, (float)int.Parse(msgParams[0]) / 100f, playerInfo);
                 this._salvagePoints = (int)((double)this._researchPoints * (double)playerInfo.RateResearchSalvageResearch);
             }
             else if (panelName == SalvageProjectDialog.UISpecialProjectSlider)
             {
                 EmpireSummaryState.DistibuteResearchSpending(this._app.Game, this._app.GameDatabase, EmpireSummaryState.ResearchSpendings.SpecialProject, (float)int.Parse(msgParams[0]) / 100f, playerInfo);
                 this._salvagePoints = (int)((double)this._researchPoints * (double)playerInfo.RateResearchSalvageResearch);
             }
             else if (panelName == SalvageProjectDialog.UISalvageResearchSlider)
             {
                 EmpireSummaryState.DistibuteResearchSpending(this._app.Game, this._app.GameDatabase, EmpireSummaryState.ResearchSpendings.SalvageResearch, (float)int.Parse(msgParams[0]) / 100f, playerInfo);
                 this._salvagePoints = (int)((double)this._researchPoints * (double)playerInfo.RateResearchSalvageResearch);
             }
             this.UpdateResearchSliders(playerInfo, panelName);
             this.RefreshSliders();
         }
     }
     else
     {
         if (!(msgType == "dialog_closed") || !(panelName == this._confirmProjectChangeDialog))
         {
             return;
         }
         if (bool.Parse(msgParams[0]) && this._contextProject != null)
         {
             if (this._contextProject.Progress == -1)
             {
                 this._app.GameDatabase.UpdateSpecialProjectProgress(this._contextProject.ID, 0);
                 this.RefreshProjects();
             }
             else
             {
                 this._app.GameDatabase.RemoveSpecialProject(this._contextProject.ID);
                 this.RefreshProjects();
             }
         }
         this._contextProject             = (SpecialProjectInfo)null;
         this._confirmProjectChangeDialog = "";
     }
 }
Exemple #17
0
        private void RefreshProjects()
        {
            this._app.UI.ClearItems(this._app.UI.Path(this.ID, "specialList"));
            this.SyncRates();
            this._rates.Clear();
            List <SpecialProjectInfo> list = this._app.GameDatabase.GetSpecialProjectInfosByPlayerID(this._app.LocalPlayer.ID, true).Where <SpecialProjectInfo>((Func <SpecialProjectInfo, bool>)(x => x.Type == SpecialProjectType.Salvage)).ToList <SpecialProjectInfo>().OrderBy <SpecialProjectInfo, bool>((Func <SpecialProjectInfo, bool>)(x => x.Progress < 0)).ToList <SpecialProjectInfo>();

            if ((double)list.Sum <SpecialProjectInfo>((Func <SpecialProjectInfo, float>)(x => x.Rate)) < 0.99)
            {
                SpecialProjectInfo specialProjectInfo = list.FirstOrDefault <SpecialProjectInfo>((Func <SpecialProjectInfo, bool>)(x => x.Progress >= 0));
                if (specialProjectInfo != null)
                {
                    specialProjectInfo.Rate = 1f;
                }
            }
            PlayerInfo playerInfo = this._app.GameDatabase.GetPlayerInfo(this._app.LocalPlayer.ID);

            this._researchPoints = this._app.Game.ConvertToResearchPoints(this._app.LocalPlayer.ID, Budget.GenerateBudget(this._app.Game, playerInfo, (IEnumerable <DesignInfo>)null, BudgetProjection.Actual).ResearchSpending.RequestedTotal);
            this._salvagePoints  = (int)((double)this._researchPoints * (double)playerInfo.RateResearchSalvageResearch);
            foreach (SpecialProjectInfo specialProjectInfo in list)
            {
                this._app.UI.AddItem(this._app.UI.Path(this.ID, "specialList"), "", specialProjectInfo.ID, "");
                string itemGlobalId = this._app.UI.GetItemGlobalID(this._app.UI.Path(this.ID, "specialList"), "", specialProjectInfo.ID, "");
                this._app.UI.SetPropertyString(this._app.UI.Path(itemGlobalId, "projectName"), "text", specialProjectInfo.Name);
                this._app.UI.SetPropertyString(this._app.UI.Path(itemGlobalId, "description"), "text", GameSession.GetSpecialProjectDescription(specialProjectInfo.Type));
                if (specialProjectInfo.Progress >= 0)
                {
                    this._app.UI.SetVisible(this._app.UI.Path(itemGlobalId, "startButton"), false);
                    this._app.UI.SetVisible(this._app.UI.Path(itemGlobalId, "cancelButton"), true);
                    this._app.UI.SetVisible(this._app.UI.Path(itemGlobalId, "activeIndicator"), true);
                    this._app.UI.SetVisible(this._app.UI.Path(itemGlobalId, "projectRate"), true);
                }
                else
                {
                    this._app.UI.SetVisible(this._app.UI.Path(itemGlobalId, "startButton"), true);
                    this._app.UI.SetVisible(this._app.UI.Path(itemGlobalId, "cancelButton"), false);
                    this._app.UI.SetVisible(this._app.UI.Path(itemGlobalId, "activeIndicator"), false);
                    this._app.UI.SetVisible(this._app.UI.Path(itemGlobalId, "projectRate"), false);
                }
                this._app.UI.SetPropertyString(this._app.UI.Path(itemGlobalId, "startButton"), "id", "startButton|" + specialProjectInfo.ID.ToString());
                this._app.UI.SetPropertyString(this._app.UI.Path(itemGlobalId, "cancelButton"), "id", "cancelButton|" + specialProjectInfo.ID.ToString());
                this._app.UI.SetSliderValue(this._app.UI.Path(itemGlobalId, "projectProgress"), (int)((double)specialProjectInfo.Progress / (double)specialProjectInfo.Cost * 100.0));
                this._app.UI.SetPropertyString(this._app.UI.Path(itemGlobalId, "projectRate"), "id", "projectRate|" + specialProjectInfo.ID.ToString());
                this._app.UI.SetPropertyString(this._app.UI.Path(itemGlobalId, "projectTurnCount"), "id", "projectTurnCount|" + specialProjectInfo.ID.ToString());
                this._rates.Add(specialProjectInfo);
            }
            this.RefreshSliders();
            this.UpdateResearchSliders(playerInfo, "");
        }
Exemple #18
0
        public Task <CommandLineResult> AddPackage(string packageId, string version = null, Budget budget = null)
        {
            var versionArg = string.IsNullOrWhiteSpace(version)
                ? ""
                : $"--version {version}";

            return(Execute($"add package {versionArg} {packageId}", budget));
        }
Exemple #19
0
        public BudgetSummary GetBudgetSummaryById(int budgetId)
        {
            string loggedUser = _httpContextAccessor.HttpContext.User.FindFirstValue("userId");

            Budget budget = dbContext.Budgets
                            .Where(b => b.PersonId.Equals(loggedUser) && b.BudgetId.Equals(budgetId))
                            .Include(b => b.BudgetItems)
                            .FirstOrDefault();

            if (budget == null)
            {
                throw new SkrillaApiException("not_found", "Budget not found.");
            }


            List <Consumption> consumptionsSet = dbContext.Consumptions
                                                 .Where(c => c.PersonId.Equals(loggedUser) &&
                                                        budget.StartDate.CompareTo(c.Date) <= 0 &&
                                                        budget.EndDate.CompareTo(c.Date) >= 0).
                                                 Include(c => c.Category).ToList();


            List <BudgetItem> budgetItems = budget.BudgetItems.ToList();

            List <Category> categories = dbContext.Categories
                                         .Where(c => c.PersonId.Equals(loggedUser))
                                         .ToList();

            List <BudgetCategorySummaryItem> summaryItems = new List <BudgetCategorySummaryItem>();

            categories.ForEach(category =>
            {
                BudgetCategorySummaryItem item = consumptionsSet
                                                 .Where(c => c.Category.Equals(category))
                                                 .AsEnumerable()
                                                 .GroupBy(c => c.Category)
                                                 .Select(g =>
                {
                    var budgetItem      = budgetItems.Where(b => b.Category.Equals(g.Key)).FirstOrDefault();
                    double budgetAmount = (budgetItem == null) ? -1 : budgetItem.BudgetedAmount;
                    return(new BudgetCategorySummaryItem(g.Key, budgetAmount, g.Sum(c => c.Amount)));
                }).FirstOrDefault();

                if (item != null)
                {
                    summaryItems.Add(item);
                }
                else
                {
                    var budgetItem      = budgetItems.Where(b => b.Category.Equals(category)).FirstOrDefault();
                    double budgetAmount = -1;
                    if (budgetItem != null && budgetItem.BudgetedAmount != 0)
                    {
                        budgetAmount = budgetItem.BudgetedAmount;
                    }

                    summaryItems.Add(new BudgetCategorySummaryItem(category, budgetAmount, 0));
                }
            });

            var totalRes = consumptionsSet
                           .GroupBy(c => c.PersonId)
                           .Select(g => new { total = g.Sum(c => c.Amount) })
                           .FirstOrDefault();

            double totalSpent = (totalRes == null) ? 0 : totalRes.total;

            totalSpent   = Math.Round(totalSpent, 2);
            summaryItems = summaryItems.OrderByDescending(i => i.TotalSpent).ToList();

            BudgetSummary summary = new BudgetSummary(budget.Amount, (double)totalSpent, summaryItems, budget.BudgetId);

            return(summary);
        }
        public static async Task <SignatureHelpResult> GetSignatureHelp(Document document, int position, Budget budget = null)
        {
            var invocation = await GetInvocation(document, position);

            return(InternalGetSignatureHelp(invocation));
        }
Exemple #21
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            Budget <Account> budget = new Budget <Account>("Provice budget");

            string description = "Commands:\n<> 'new' - open a new account.\n<> 'put' - put on the account.\n<> 'withdraw' - withdraw from the account.\n" +
                                 "<> 'transfer' - transfer to another account.\n<> 'search' - account search.\n<> 'mylist' - list of my accounts.\n" +
                                 "<> 'ainfo' - account information.\n<> 'hinfo' - transaction history.\n<> 'tchange' - change account type.\n<> 'close' - close account.\n" +
                                 "<> 'help' - list of commands.\n<> 'exit' - exit.";

            Console.WriteLine(description);

            while (true)
            {
                try
                {
                    string command = Convert.ToString(Console.ReadLine());
                    switch (command)
                    {
                    case "new":
                        BudgetUSOperations.OpenAccount(budget);
                        break;

                    case "put":
                        BudgetUSOperations.Put(budget);
                        break;

                    case "withdraw":
                        BudgetUSOperations.Withdraw(budget);
                        break;

                    case "transfer":
                        BudgetUSOperations.Transfer(budget);
                        break;

                    case "search":
                        BudgetUSOperations.FindAccountInMyBudget(budget);
                        break;

                    case "mylist":
                        BudgetUSOperations.AccountIdsList(budget);
                        break;

                    case "ainfo":
                        BudgetUSOperations.GetAccountInfo(budget);
                        break;

                    case "hinfo":
                        BudgetUSOperations.HistoryInfo(budget);
                        break;

                    case "tchange":
                        BudgetUSOperations.ChangeTypeAccount(budget);
                        break;

                    case "help":
                        Console.WriteLine(description);
                        break;

                    case "close":
                        BudgetUSOperations.CloseAccount(budget);
                        break;

                    case "exit":
                        Environment.Exit(0);
                        break;

                    default:
                        Console.WriteLine("Unrecognized command.");
                        break;
                    }
                }
                catch (ArgumentNullException e)
                {
                    ErrorHandler.Logs(e);
                }
                catch (ArgumentOutOfRangeException e)
                {
                    Console.WriteLine("Runtime error. Repeat the procedure again!");
                    ErrorHandler.Logs(e);
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine("Runtime error. Check that the input values are correct!");
                    ErrorHandler.Logs(e);
                }
                catch (NullReferenceException e)
                {
                    Console.WriteLine("The procedure was aborted. Check that the input values are correct.");
                    ErrorHandler.Logs(e);
                }
                catch (IOException)
                {
                    Console.WriteLine("The program does not work correctly. Try restarting!");
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine("The procedure was aborted. Check that the input values are correct.");
                    ErrorHandler.Logs(e);
                }
            }
        }
Exemple #22
0
        public int Add(Budget budget)
        {
            int budgetId = budgetService.Add(budget);

            return(budgetId);
        }
 //Add and Save to DB Methods.
 public bool InsertBudget(Budget budget)
 {
     _db.Budget.Add(budget);
     return(_db.SaveChanges() == 1);
 }
Exemple #24
0
 public static Task <(Compilation compilation, IReadOnlyCollection <Document> documents)> GetCompilationForRun(
     this Package package,
     IReadOnlyCollection <SourceFile> sources,
     SourceCodeKind sourceCodeKind,
     IEnumerable <string> defaultUsings,
     Budget budget) =>
Exemple #25
0
 public Task <CommandLineResult> ToolInstall(string args = null, Budget budget = null) =>
 Execute("tool install".AppendArgs(args), budget);
Exemple #26
0
 public Task <CommandLineResult> VSTest(string args, Budget budget = null) =>
 Execute("vstest".AppendArgs(args), budget);
 public void Create(Budget Budget)
 {
     _context.Budget.Add(Budget);
 }
Exemple #28
0
 public void SaveBudget(Budget budget)
 {
     BudgetManager.Edit(budget);
 }
 public void Update(Budget Budget)
 {
     _context.Entry<Budget>(Budget).State = System.Data.Entity.EntityState.Modified;
 }
Exemple #30
0
        private static void CopyBudgetItemDependsOnlyForBudgetItems(Dictionary<object, object> replaceIds,List<Guid> budgetItemIds,
         out Dictionary<object, object> budgetAllocationReplaceIds)
        {
            var tableList = new Dictionary<string, string>
            {
                {"BudgetItemAllocation", "BudgetItemId"},
                {"MetadataEntityVersion", "BaseEntityId"},
                {"WorkflowMultipleSighting", "ProcessId"},
                {"WorkflowProcessInstance", "Id"},
                {"WorkflowProcessInstancePersistence", "ProcessId"},
                {"WorkflowProcessInstanceStatus", "Id"},
                {"WorkflowProcessScheme", "Id"},
                {"WorkflowProcessTransitionHistory", "ProcessId"},
                {"WorkflowHistory", "ProcessId"},
                {"WorkflowInbox", "ProcessId"}
            };

            var b = new Budget();
            budgetAllocationReplaceIds = null;
            foreach (var t in tableList)
            {
                var param = new Dictionary<string, Dictionary<object, object>>();
                param.Add(t.Value, replaceIds);

                var tmpFilter =
                    FilterCriteriaSet.And.In(budgetItemIds, t.Value);
                var dependsReplaceId = b.CopyDependsEntity(t.Key, (t.Value == "Id" ? null : "Id"), tmpFilter, param);

                if (t.Key == "BudgetItemAllocation")
                {
                    budgetAllocationReplaceIds = dependsReplaceId;
                }
            }
        }
 /// <summary>
 /// The operation to create or update a budget. Update operation requires
 /// latest eTag to be set in the request mandatorily. You may obtain the latest
 /// eTag by performing a get operation. Create operation does not require eTag.
 /// <see href="https://docs.microsoft.com/en-us/rest/api/consumption/" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Azure Resource Group Name.
 /// </param>
 /// <param name='budgetName'>
 /// Budget Name.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the Create Budget operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <Budget> CreateOrUpdateByResourceGroupNameAsync(this IBudgetsOperations operations, string resourceGroupName, string budgetName, Budget parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateOrUpdateByResourceGroupNameWithHttpMessagesAsync(resourceGroupName, budgetName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Exemple #32
0
        public static void CopyToNewBudgetVersion(object newBudgetId, object oldBudgetId, Dictionary<string, Dictionary<object, object>> replacesByTable)
        {
            var replaceIds = new Dictionary<object, object>();
            var changedDate = DateTime.Now;
            var repository = new DynamicEntityRepository();

            var newVersion = DynamicRepository.GetByEntity("BudgetVersion",
                FilterCriteriaSet.And.Equal(newBudgetId, "BudgetId")
                    .Merge(FilterCriteriaSet.And.Equal(true, "IsCurrent"))).FirstOrDefault();

            var oldVersion = DynamicRepository.GetByEntity("BudgetVersion",
                FilterCriteriaSet.And.Equal(oldBudgetId, "BudgetId")
                    .Merge(FilterCriteriaSet.And.Equal(true, "IsCurrent"))).FirstOrDefault();

            var newBudget = DynamicRepository.GetByEntity("Budget",
                FilterCriteriaSet.And.Equal(newBudgetId, "Id")).FirstOrDefault();

            bool internalTransaction = false;

            if (SharedCommunicationObjects.SharedTransaction == null)
            {
                SharedCommunicationObjects.CreateSharedTransaction();
                internalTransaction = true;
            }

            try
            {
                #region BudgetItems

                var biMetadata = repository.GetEntityMetadataByEntityName("BudgetItem");

                List<dynamic> records =
                    biMetadata.Get(
                        FilterCriteriaSet.And.Equal((Guid) oldVersion.Id, "BudgetVersionId")
                            .NotEqual(true, "IsDeleted")
                            .NotEqual("Deleted", "State")
                            .NotEqual(true, "IsPrevPeriod"));

                foreach (dynamic r in records)
                {
                    var oldId = r.Id;
                    r.Id = Guid.NewGuid();
                    r.BudgetVersionId = newVersion.Id;
                    r.WasBack = false;
                    r.State = "Draft";
                    r.StateName = "Draft";
                    r.EntityRouteId = null;
                    r.ChangedDate = changedDate;

                    //Заменяем ссылки на скопированные в новый бюджет справочники

                    ReplaceToNewIds(replacesByTable, biMetadata, r);

                    replaceIds.Add(oldId, r.Id);
                }

                var dynamicEntities = records.ConvertAll(d=> d as DynamicEntity);

                PrimaryKeyGenerator.SPGenerateKey(biMetadata, dynamicEntities,
                    new Dictionary<string, string>
                    {
                        {"StoredProcedure", "data_get_sequence"},
                        {"ColumnName", "NumberId"},
                        {"Value", "Value"},
                        {"Code", "BudgetItem"}
                    });

                //Перерасчет остатков
                //BudgetItemMethods.InitResidual(biMetadata, null, dynamicEntities);
                DWKitHelper.EMExecute("BudgetItem.InitResidual", biMetadata, null, dynamicEntities);

                DynamicRepository.InsertByEntity("BudgetItem", records);

                #endregion

                //Словарь со всеми заменами Id-ов
                var allReplaces = replacesByTable.Select(replaces => replaces.Value).ToList();
                allReplaces.Add(replaceIds);

                #region Depends
                var tableList = new Dictionary<string, string>
                {
                    {"BudgetItemAllocation", "BudgetItemId"}
                };

                var b = new Budget();
                foreach (var t in tableList)
                {
                    var replaceByPropertyName = new Dictionary<string, Dictionary<object, object>> { { t.Value, replaceIds } };

                    var tMetadata = repository.GetEntityMetadataByEntityName(t.Key);

                    foreach (var att in tMetadata.PlainAttributes.Where(a=>a.IsReference))
                    {
                        if (!replacesByTable.ContainsKey(att.ReferencedTableName))
                            continue;

                        var replace = replacesByTable[att.ReferencedTableName];

                        replaceByPropertyName.Add(att.PropertyName, replace);
                    }

                    var tmpFilter = FilterCriteriaSet.And.Custom(string.Format("{0} in (select Id from BudgetItem WHERE BudgetVersionId = '{1}')", t.Value, (Guid)oldVersion.Id));
                    var replaces = b.CopyDependsEntity(t.Key, (t.Value == "Id" ? null : "Id"), tmpFilter,
                        replaceByPropertyName, true);

                    allReplaces.Add(replaces);

                }
                #endregion

                #region UploadedFiles
                CopyUploadedFiles(replaceIds);
                #endregion

                #region EntityAccess

                //Все замены в один словарь
                var allReplacesDictionary = allReplaces.SelectMany(dict => dict)
                         .ToDictionary(pair => pair.Key, pair => pair.Value);

                CopyEntityAccess(oldVersion, newVersion, allReplacesDictionary);
                #endregion

                #region Created PrevPeriod BudgetItems

                var biIdsForReclc = BudgetItem.SyncFutureBudgetItem((int)newBudget.Name, replaceIds);
                VtbRestCalculator.Calc.RecalculateAccount(biIdsForReclc, newBudget.Id);

                #endregion

                if (internalTransaction)
                    SharedCommunicationObjects.CommitSharedTransaction();
            }
            catch (Exception ex)
            {
                if (internalTransaction)
                    SharedCommunicationObjects.RollbackSharedTransaction();
                throw ex;
            }
            finally
            {
                if (internalTransaction)
                    SharedCommunicationObjects.DestroySharedTransaction();
            }
        }
Exemple #33
0
 public Task <CommandLineResult> AddReference(FileInfo projectToReference, Budget budget = null)
 {
     return(Execute($"add reference {projectToReference.FullName}", budget));
 }
 private static void SetBudgetId(HomeIndexViewModel vm, Budget selectedBudget)
 {
     vm.SelectedBudgetId = selectedBudget.Id;
 }
Exemple #35
0
 public Task <CommandLineResult> Pack(string args = null, Budget budget = null) =>
 Execute("pack".AppendArgs(args), budget);
 public void CreateGroup(string name, Budget groupBudget)
 {
 }
Exemple #37
0
 public void Add(Budget budget)
 {
     this.budget = budget;
 }
Exemple #38
0
 public Task <CommandLineResult> Build(string args = null, Budget budget = null) =>
 Execute("build".AppendArgs(args), budget);
Exemple #39
0
 public Budget CreateBudget(Budget budget)
 {
     return(BudgetManager.Add(budget));
 }
Exemple #40
0
 public Task <CommandLineResult> Execute(string args, Budget budget = null) =>
 CommandLine.Execute(
     Path,
     args,
     _workingDirectory,
     budget);
Exemple #41
0
        private static void CopyHistory(dynamic currentBV, Dictionary<object, object> replaceIds, dynamic newBV,
            Dictionary<object, object> budgetAllocationReplaceIds)
        {
            List<dynamic> h_records = DynamicRepository.GetByEntity("H_BudgetItem",
                FilterCriteriaSet.And.Equal((Guid) currentBV.Id, "BudgetVersionId"));
            var h_replaceIds = new Dictionary<object, object>();

            for (int i = h_records.Count - 1; i >= 0; i--)
            {
                if (!replaceIds.ContainsKey(h_records[i].VersioningEntityId))
                    h_records.Remove(h_records[i]);
            }

            foreach (dynamic r in h_records)
            {
                var oldId = r.Id;
                r.Id = Guid.NewGuid();
                r.BudgetVersionId = newBV.Id;
                r.VersioningEntityId = replaceIds[r.VersioningEntityId];
                h_replaceIds.Add(oldId, r.Id);
            }
            DynamicRepository.InsertByEntity("H_BudgetItem", h_records);

            Dictionary<string, Dictionary<object, object>> h_param = new Dictionary<string, Dictionary<object, object>>();
            h_param.Add("VersioningBaseEntityId", h_replaceIds);
            if (budgetAllocationReplaceIds != null)
                h_param.Add("VersioningEntityId", budgetAllocationReplaceIds);

            var h_tmpFilter =
                FilterCriteriaSet.And.Custom(string.Format(
                    "{0} in (select Id from H_BudgetItem WHERE BudgetVersionId = '{1}')", "VersioningBaseEntityId",
                    (Guid) currentBV.Id));
            var b = new Budget();
            b.CopyDependsEntity("H_BudgetItemAllocation", "Id", h_tmpFilter, h_param);
        }
Exemple #42
0
 public ActionResult <long> Post([FromBody] Budget budget)
 {
     return(_BudgetBusiness.addBudget(budget));
 }
Exemple #43
0
 /// <summary>
 /// Open the specified bugdet and eventually merge it with the other specified budget
 /// </summary>
 /// <param name="filename">the budget file to open</param>
 /// <param name="budgetToMerge">the optionnal budget to merge with or null</param>
 /// <returns>true if the budget was correctly open</returns>
 private bool openBudget(string filename, Budget.Budget budgetToMerge)
 {
     // set the wait cursor
     this.Cursor = Cursors.WaitCursor;
     // load the file
     bool isFileValid = SaveLoadManager.load(filename);
     if (isFileValid)
     {
         // check if we need to merge a budget in the new opened budget or not
         if (budgetToMerge != null)
         {
             Budget.Budget.Instance.mergeWith(budgetToMerge);
             // give back the title of the original budget to the loaded budget
             changeCurrentBudgetFileName(budgetToMerge.BudgetFileName, true);
         }
         else
         {
             // change the filename in the title bar
             changeCurrentBudgetFileName(filename, true);
         }
         // recount the parts because, opening a new budget actually create a new instance of Budget, so the count is destroyed
         Budget.Budget.Instance.recountAllBricks();
         // update the part lib view (after recounting the bricks), and also the filtering on it
         this.PartsTabControl.updateAllPartCountAndBudget();
         this.PartsTabControl.updateFilterOnBudgetedParts();
     }
     // update the menu items
     updateEnableStatusForBudgetMenuItem();
     // then update the view of the part lib
     this.PartsTabControl.updateViewStyle();
     // restore the cursor after loading
     this.Cursor = Cursors.Default;
     // return if the file was correctly loaded
     return isFileValid;
 }
 internal static void Complete(
     this ConfirmationLogger logger,
     Budget budget) =>
 logger.Succeed("Completed with {budget}", budget);
 public void AssignBudget(Budget groupBudget)
 {
 }
        public CreateResponse Post(BudgetCreateCommand command)
        {
            var budget = new Budget
            {
                Id = Guid.NewGuid(),
                Name = command.Name,
                StartDate = command.StartDate,
                EndDate = command.EndDate,
                Frequency = command.Frequency
            };

            repositoryUnitOfWork.Budgets.Create(budget);

            return new CreateResponse { Id = budget.Id };
        }
        public void TestGetAllCampaignsMockAndCallServer()
        {
            ServiceSignature mockSignature = MockUtilities.RegisterMockService(user,
              AdWordsService.v201601.CampaignService, typeof(MockCampaignServiceEx));

              CampaignService campaignService = (CampaignService) user.GetService(mockSignature);
              Assert.That(campaignService is MockCampaignServiceEx);

              Campaign campaign = new Campaign();
              campaign.name = "Interplanetary Cruise #" + new TestUtils().GetTimeStamp();
              campaign.status = CampaignStatus.PAUSED;
              campaign.biddingStrategyConfiguration = new BiddingStrategyConfiguration();
              campaign.biddingStrategyConfiguration.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;

              Budget budget = new Budget();
              budget.budgetId = budgetId;

              campaign.budget = budget;

              campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

              // Set the campaign network options to GoogleSearch and SearchNetwork
              // only. Set ContentNetwork, PartnerSearchNetwork and ContentContextual
              // to false.
              campaign.networkSetting = new NetworkSetting() {
            targetGoogleSearch = true,
            targetSearchNetwork = true,
            targetContentNetwork = false,
            targetPartnerSearchNetwork = false
              };

              // Create operations.
              CampaignOperation operation = new CampaignOperation();
              operation.@operator = Operator.ADD;
              operation.operand = campaign;

              CampaignReturnValue retVal = null;

              Assert.DoesNotThrow(delegate() {
            retVal = campaignService.mutate((new CampaignOperation[] { operation }));
              });

              Assert.NotNull(retVal);
              Assert.NotNull(retVal.value);
              Assert.AreEqual(retVal.value.Length, 1);
              Assert.AreEqual(retVal.value[0].name, campaign.name);
              Assert.AreNotEqual(retVal.value[0].id, 0);
              Assert.True((campaignService as MockCampaignServiceEx).MutateCalled);
        }
        /// <summary>
        /// Builds an operation for creating a budget.
        /// </summary>
        /// <returns>The operation for creating a budget.</returns>
        private static BudgetOperation BuildBudgetOperation()
        {
            Budget budget = new Budget() {
            budgetId = NextId(),
            name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
            amount = new Money() {
              microAmount = 50000000L,
            },
            deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD,
            period = BudgetBudgetPeriod.DAILY
              };

              BudgetOperation budgetOperation = new BudgetOperation() {
            operand = budget,
            @operator = Operator.ADD
              };
              return budgetOperation;
        }
Exemple #49
0
 public async Task AddBudgetAsync(MonthEnumeration month, int year, List <BudgetDetail> budgetDetails)
 {
     var budget = new Budget(month, year, budgetDetails);
     await _budgetRepository.AddAsync(budget);
 }
        public string CreatHouseholdData()
        {
            var user = db.Users.Find(HttpContext.Current.User.Identity.GetUserId());

            if (user != null)
            {
                //Check for registered user
                //Check if user has household
                if (user.HouseholdId == null)
                {
                    return("You must create a household first");
                }

                //Get user household and delete existing bank accounts, budget, and categories, which will also delete items and transactions
                Household household    = db.Households.Include(h => h.Members).FirstOrDefault(h => h.Id == user.HouseholdId);
                var       bankAccounts = db.BankAccounts.Where(ba => ba.HouseholdId == user.HouseholdId).ToList();
                if (bankAccounts.Count > 0)
                {
                    foreach (var account in bankAccounts)
                    {
                        db.BankAccounts.Remove(account);
                    }
                }
                var budget = db.Budgets.FirstOrDefault(b => b.HouseholdId == user.HouseholdId);
                if (budget != null)
                {
                    var budgetItems = db.BudgetItems.Where(b => b.BudgetId == budget.Id).ToList();
                    var categories  = db.BudgetItemCategories.Where(b => b.BudgetId == budget.Id).ToList();
                    if (categories.Count > 0)
                    {
                        foreach (var category in categories)
                        {
                            db.BudgetItemCategories.Remove(category);
                        }
                    }

                    db.SaveChanges();
                }

                //If no budget exists yet
                if (budget == null)
                {
                    budget             = new Budget();
                    budget.HouseholdId = (int)user.HouseholdId;
                    budget.Name        = "Budget for " + household.Name;
                    budget.Amount      = 3000;
                    budget.Created     = DateTimeOffset.Now;
                    budget.Active      = true;
                    db.Budgets.Add(budget);
                    db.SaveChanges();
                }

                //Start to create new stuff
                var sampleCategories = db.SampleBudgetItemCategories;
                foreach (var c in sampleCategories)
                {
                    var category = new BudgetItemCategory();
                    category.Name     = c.Name;
                    category.BudgetId = budget.Id;
                    db.BudgetItemCategories.Add(category);
                }
                db.SaveChanges();

                var BudgetItems = db.SampleBudgetItems.Include(b => b.Category).ToList();
                foreach (var bi in BudgetItems)
                {
                    var budgetItem = new BudgetItem();
                    int catNameId  = db.BudgetItemCategories.FirstOrDefault(b => b.Name == bi.Category.Name && b.BudgetId == budget.Id).Id;
                    budgetItem.Name       = bi.Name;
                    budgetItem.Amount     = bi.Amount;
                    budgetItem.CategoryId = catNameId;
                    budgetItem.BudgetId   = budget.Id;
                    budgetItem.Active     = true;
                    db.BudgetItems.Add(budgetItem);
                }
                db.SaveChanges();

                var SavedBudgetItems = db.BudgetItems.Include(b => b.Category).ToList();

                for (int ba = 1; ba <= 4; ba++)
                {
                    var bankAccount = new BankAccount();
                    bankAccount.Name           = "Account " + ba + " for household " + household.Name;
                    bankAccount.Balance        = 3000;
                    bankAccount.WarningBalance = 100;
                    bankAccount.BankName       = "First Bank";
                    bankAccount.AccountNumber  = 123450 + ba;
                    bankAccount.HouseholdId    = household.Id;
                    bankAccount.AccountTypeId  = db.AccountTypes.FirstOrDefault(a => a.Type == "Checking").Id;
                    bankAccount.AccountOwnerId = user.Id;
                    db.BankAccounts.Add(bankAccount);
                    db.SaveChanges();

                    Transaction transaction;
                    for (int x = 0; x <= 36; x++)
                    {
                        decimal total = 0.00M;
                        foreach (var bi in SavedBudgetItems)
                        {
                            var count = 1;
                            transaction                 = new Transaction();
                            transaction.Description     = "Trans " + count + " for " + bankAccount.Name;
                            transaction.Created         = DateTimeOffset.Now.AddMonths(-x);
                            transaction.Amount          = Math.Abs((bi.Amount * .25M) + count - x);
                            transaction.EnteredById     = user.Id;
                            transaction.BudgetItemId    = bi.Id;
                            transaction.BankAccountId   = bankAccount.Id;
                            transaction.IncomeExpenseId = db.IncomeExpenses.FirstOrDefault(i => i.Type == "Expense").Id;
                            total += transaction.Amount;
                            db.Transactions.Add(transaction);
                        }

                        db.SaveChanges();

                        transaction                 = new Transaction();
                        transaction.Description     = "Deposit for " + bankAccount.Name;
                        transaction.Created         = DateTimeOffset.Now.AddMonths(-x);
                        transaction.Amount          = total * 1.05M;
                        transaction.EnteredById     = user.Id;
                        transaction.BudgetItemId    = null;
                        transaction.BankAccountId   = bankAccount.Id;
                        transaction.IncomeExpenseId = db.IncomeExpenses.FirstOrDefault(i => i.Type == "Income").Id;

                        db.Transactions.Add(transaction);

                        db.SaveChanges();
                    }
                }


                return("Data has been generated");
            }

            return("Something went wrong!");
        }
 public void AddBudget(Budget budget)
 {
 }
 /// <summary>
 /// Method analyzes if current object is a parent of <paramref name="other"/>
 /// if you override GetHashCode or provide a nifty bit array representation
 /// you can infer parent-child relationships with really fast bit shifting
 /// </summary>
 /// <param name="other">budget to compare with</param>
 public bool IsParentOf(Budget other)
 {
     // ommitted for too-time-consuming and 'your work obviously'
     // or 'not-the-purpose-of-this-site'reasons
     return(true);
 }
    /// <summary>
    /// Creates an explicit budget to be used only to create the Campaign.
    /// </summary>
    /// <param name="budgetService">The budget service.</param>
    /// <param name="name">The budget name.</param>
    /// <param name="amount">The budget amount.</param>
    /// <returns>The budget object.</returns>
    private Budget CreateSharedBudget(BudgetService budgetService, String name, long amount) {
      // Create a shared budget
      Budget budget = new Budget();
      budget.name = name;
      budget.period = BudgetBudgetPeriod.DAILY;
      budget.amount = new Money();
      budget.amount.microAmount = amount;
      budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
      budget.isExplicitlyShared = true;

      // Create operation.
      BudgetOperation operation = new BudgetOperation();
      operation.operand = budget;
      operation.@operator = Operator.ADD;

      // Make the mutate request.
      return budgetService.mutate(new BudgetOperation[] {operation}).value[0];
    }
 private void UpdateBudgetBeforeCategoryDelete(Budget budget, decimal sumToRemove)
 {
     budget.Sum -= sumToRemove;
     _budgetRepo.UpdateAmount(budget);
 }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the BudgetService.
              BudgetService budgetService =
              (BudgetService) user.GetService(AdWordsService.v201601.BudgetService);

              // Get the CampaignService.
              CampaignService campaignService =
              (CampaignService) user.GetService(AdWordsService.v201601.CampaignService);

              // Create the campaign budget.
              Budget budget = new Budget();
              budget.name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString();
              budget.period = BudgetBudgetPeriod.DAILY;
              budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
              budget.amount = new Money();
              budget.amount.microAmount = 500000;

              BudgetOperation budgetOperation = new BudgetOperation();
              budgetOperation.@operator = Operator.ADD;
              budgetOperation.operand = budget;

              try {
            BudgetReturnValue budgetRetval = budgetService.mutate(
            new BudgetOperation[] { budgetOperation });
            budget = budgetRetval.value[0];
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add shared budget.", e);
              }

              List<CampaignOperation> operations = new List<CampaignOperation>();

              for (int i = 0; i < NUM_ITEMS; i++) {
            // Create the campaign.
            Campaign campaign = new Campaign();
            campaign.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
            campaign.status = CampaignStatus.PAUSED;
            campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
            biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;
            campaign.biddingStrategyConfiguration = biddingConfig;

            campaign.budget = new Budget();
            campaign.budget.budgetId = budget.budgetId;

            // Set the campaign network options.
            campaign.networkSetting = new NetworkSetting();
            campaign.networkSetting.targetGoogleSearch = true;
            campaign.networkSetting.targetSearchNetwork = true;
            campaign.networkSetting.targetContentNetwork = false;
            campaign.networkSetting.targetPartnerSearchNetwork = false;

            // Set the campaign settings for Advanced location options.
            GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting();
            geoSetting.positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE;
            geoSetting.negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE;

            campaign.settings = new Setting[] { geoSetting };

            // Optional: Set the start date.
            campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd");

            // Optional: Set the end date.
            campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd");

            // Optional: Set the campaign ad serving optimization status.
            campaign.adServingOptimizationStatus = AdServingOptimizationStatus.ROTATE;

            // Optional: Set the frequency cap.
            FrequencyCap frequencyCap = new FrequencyCap();
            frequencyCap.impressions = 5;
            frequencyCap.level = Level.ADGROUP;
            frequencyCap.timeUnit = TimeUnit.DAY;
            campaign.frequencyCap = frequencyCap;

            // Create the operation.
            CampaignOperation operation = new CampaignOperation();
            operation.@operator = Operator.ADD;
            operation.operand = campaign;

            operations.Add(operation);
              }

              try {
            // Add the campaign.
            CampaignReturnValue retVal = campaignService.mutate(operations.ToArray());

            // Display the results.
            if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
              foreach (Campaign newCampaign in retVal.value) {
            Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.",
                newCampaign.name, newCampaign.id);
              }
            } else {
              Console.WriteLine("No campaigns were added.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add campaigns.", e);
              }
        }
Exemple #56
0
        void Valider()
        {
            if (lstBudget.SelectedIndex < 0)
            {
                MessageBox.Show("Budget ?"); return;
            }
            if (lstORG.SelectedIndex < 0)
            {
                MessageBox.Show("ORG ?"); return;
            }
            if (lstGEO.SelectedIndex < 0)
            {
                MessageBox.Show("GEO ?"); return;
            }
            //if (lstPeriode.SelectedIndex < 0) { MessageBox.Show("Période ?"); return; }

            Budget budget = listeBudget[lstBudget.SelectedIndex];

            int    budget_id    = budget.ID;
            string LibBudget    = lblLibelleBudget.Text.Trim();
            string Codebudget   = lblCodeGenere.Text.Trim().ToUpper();
            int    Enveloppe    = budget.Enveloppe;
            int    Periode      = budget.Periode;
            string DateDeb      = budget.DateDeb;
            string DateFin      = budget.DateFin;
            bool   OptActive    = OptActiveBudget.Checked;
            bool   OptLimitatif = optLimitatif.Checked;
            var    TypeMontant  = (TypeMontant)lstTypeMontant.SelectedIndex;
            var    TypeFlux     = (TypeFlux)lstTypeFlux.SelectedIndex;
            int    ORG          = listeORG[lstORG.SelectedIndex].ID;
            int    GEO          = listeGEO[lstGEO.SelectedIndex].ID;

            if (LibBudget.Length == 0)
            {
                MessageBox.Show("Libellé du budget obligatoire", "Erreur", MessageBoxButtons.OK);
                return;
            }

            if (Codebudget.Length == 0)
            {
                MessageBox.Show("Code du budget obligatoire", "Erreur", MessageBoxButtons.OK);
                return;
            }

            budget_ligne.Console     = Console;
            budget_ligne.Acces       = Acces;
            budget_ligne.Budget_ID   = listeBudget[lstBudget.SelectedIndex].ID;
            budget_ligne.Libelle     = LibBudget;
            budget_ligne.Code        = Codebudget;
            budget_ligne.Enveloppe   = Enveloppe;
            budget_ligne.Periode     = Periode;
            budget_ligne.DateDeb     = string.Format("{0:yyyyMMdd}", lblDateDebut.Value);
            budget_ligne.DateFin     = string.Format("{0:yyyyMMdd}", lblDateFin.Value);
            budget_ligne.Actif       = OptActive;
            budget_ligne.Budget_ORG  = ORG;
            budget_ligne.Budget_GEO  = GEO;
            budget_ligne.TypeMontant = TypeMontant;
            budget_ligne.TypeFlux    = TypeFlux;

            List <int> ListeChoix = new List <int>();

            foreach (int i in ChoixCompte.ListeSelectionId)
            {
                ListeChoix.Add(i);
            }
            budget_ligne.ListeCompte = ListeChoix;

            TypeElement typeElement = Acces.type_BUDGET_LIGNE;

            if (Creation)
            {
                if (!(Acces.Existe_Element(typeElement, "CODE", Codebudget)))
                {
                    budget_ligne.ID = Acces.Ajouter_Element(typeElement, budget_ligne);
                }
                else
                {
                    MessageBox.Show("Code existant"); return;
                }
            }
            else
            {
                Acces.Enregistrer(typeElement, budget_ligne);

                //Test du changement de code --> Impact sur les liens
                if (lblCodeGenere.Text != lblCodeGenere.Tag.ToString())
                {
                    Lien l = new Lien()
                    {
                        Acces = Acces,
                    };
                    l.MettreAJourCode(typeElement, budget_ligne.ID, budget_ligne.Code);
                }
            }

            this.DialogResult = DialogResult.OK;
        }
 public void Delete(Budget Budget)
 {
     _context.Budget.Remove(Budget);
 }
 public ActionResult Edit(Budget Proizvodstvo)
 {
     db.Entry(Proizvodstvo).State = EntityState.Modified;
     db.SaveChanges();
     return(RedirectToAction("Index"));
 }
 public void AddBudget(Budget budget)
 {
     _budgets.Add(budget);
 }
 /// <summary>
 /// The operation to create or update a budget. Update operation requires
 /// latest eTag to be set in the request mandatorily. You may obtain the latest
 /// eTag by performing a get operation. Create operation does not require eTag.
 /// <see href="https://docs.microsoft.com/en-us/rest/api/consumption/" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Azure Resource Group Name.
 /// </param>
 /// <param name='budgetName'>
 /// Budget Name.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the Create Budget operation.
 /// </param>
 public static Budget CreateOrUpdateByResourceGroupName(this IBudgetsOperations operations, string resourceGroupName, string budgetName, Budget parameters)
 {
     return(operations.CreateOrUpdateByResourceGroupNameAsync(resourceGroupName, budgetName, parameters).GetAwaiter().GetResult());
 }