public ActionResult AddTopPortfolio(TopPortfolioItem topPortfolio, FormCollection formCollection)
        {
            if (topPortfolio.CreateNewAccount)
            {
                try
                {
                    topPortfolio.AddAccountModel = new AddAccountModel
                        {
                            AccountBalance = Convert.ToSingle(formCollection["AccountBalance"]),
                            AccountGroup = formCollection["AccountGroup"],
                            AccountCurrency = formCollection["AccountCurrency"],
                            AccountMaxLeverage = Convert.ToSingle(formCollection["AccountMaxLeverage"]),
                            UserLogin = formCollection["UserLogin"],
                            UserPassword = formCollection["UserPassword"],
                            UserName = formCollection["UserName"],
                            UserSurname = formCollection["UserSurname"],
                            UserPatronym = formCollection["UserPatronym"],
                            UserDescription = formCollection["UserDescription"],
                            UserEmail = formCollection["UserEmail"],
                            UserPhone1 = formCollection["UserPhone1"],
                            UserPhone2 = formCollection["UserPhone2"],
                            UserRightsMask =(UserAccountRights)Enum.Parse(typeof (UserAccountRights), formCollection["UserRightsMask"]),
                            UserRoleMask = (UserRole) Enum.Parse(typeof (UserRole), formCollection["UserRoleMask"]),
                            UserRegistrationDate = DateTime.Now,
                            WalletBalance = Convert.ToSingle(formCollection["WalletBalance"])
                        };
                }
                catch (Exception ex)
                {
                    Logger.Error("AddTopPortfolio() - Не валидно введённые данные.", ex);
                }
            }

            if (!ModelState.IsValid)
            {
                var errors = new List<string>();
                for (int i = 0; i < ModelState.Values.Count(); i++)
                {
                    var name = ModelState.Keys.ToList()[i];
                    errors.AddRange(ModelState.Values.ToList()[i].Errors.Select(x => name + ": " + x.ErrorMessage));
                }

                return RedirectToAction("AddTopPortfolio", new { message = string.Join(Environment.NewLine, errors) });
            }

            var errorMessage = topPortfolio.CreateNewAccount ?
                                      topPortfolioRepository.SubscribeOnPortfolioOnNewAccount(topPortfolio) :
                                      topPortfolioRepository.SubscribeOnPortfolioOnExistAccount(topPortfolio);

            return RedirectToAction("TopPortfolios", new { message = errorMessage });
        }
        public ActionResult AddTopPortfolio(string message, bool? createNewAccount)
        {
            FillDropDownListForAccountView();
            if (!string.IsNullOrEmpty(message))
                ResultMessage = message;

            var listHostAccount = accountRepository.GetAllAccounts();

            if (listHostAccount != null)
            {
                ViewBag.listHostAccount = listHostAccount;
                var topPortfolioItem = new TopPortfolioItem();
                if (createNewAccount.HasValue)
                    topPortfolioItem.CreateNewAccount = createNewAccount.Value;
                return View("TopPortfoliosAdd", topPortfolioItem);
            }
            return RedirectToAction("TopPortfolios", new { message = Resource.ErrorMessageUnableRetrieveServerListPortfolios });
        }
        public ActionResult TopPortfolioDetails(TopPortfolioItem topPortfolio)
        {
            if (!ModelState.IsValid)
                return RedirectToAction("TopPortfolioDetails", new { message = String.Format("{0}:{1}", Resource.ErrorMessage, Resource.ErrorMessageInvalid) });

            var result = string.Format(topPortfolioRepository.SaveTopPortfolioChanges(topPortfolio) ?
                                      Resource.MessageEditingMade + " (" + Resource.TitleElement + "  {0})" :
                                      Resource.ErrorMessageUnableUpdateRecordDB + " (" + Resource.TitleElement + " {0})",
                                      topPortfolio.Name + " / " + topPortfolio.ParticipantCount);

            return RedirectToAction("TopPortfolios", new { message = result });
        }
 public bool SaveTopPortfolioChanges(TopPortfolioItem topPortfolioItem)
 {
     try
     {
         using (var ctx = DatabaseContext.Instance.Make())
         {
             var undecoratePortfolio = ctx.TOP_PORTFOLIO.Single(a => a.Id == topPortfolioItem.Id);
             LinqToEntity.UndecoratePortfolio(undecoratePortfolio, topPortfolioItem);
             ctx.SaveChanges();
             return true;
         }
     }
     catch (Exception ex)
     {
         Logger.Error(
             String.Format("Не удалось сохранить изменения в портфеле роботов {0}", topPortfolioItem.Id), ex);
     }
     return false;
 }
        /// <summary>
        /// Добавляем в базу новую сущность
        /// </summary>
        /// <param name="newTopPortfolio">Объект содержит значения полей для новой сущность</param>
        /// <returns></returns>
        private static TopPortfolio AddTopPortfolio(TopPortfolioItem newTopPortfolio)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var topPortfolio = new TOP_PORTFOLIO
                    {
                        Name = newTopPortfolio.Name,
                        Criteria = newTopPortfolio.Criteria,
                        ParticipantCount = newTopPortfolio.ParticipantCount,
                        DescendingOrder = newTopPortfolio.DescendingOrder,
                        MarginValue = newTopPortfolio.MarginValue,
                        ManagedAccount = newTopPortfolio.ManagedAccount
                    };

                    ctx.TOP_PORTFOLIO.Add(topPortfolio);
                    ctx.SaveChanges();

                    return LinqToEntity.DecoratePortfolio(topPortfolio);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("AddTopPortfolio", ex);
                return null;
            }
        }
        public string SubscribeOnPortfolioOnNewAccount(TopPortfolioItem newTopPortfolio)
        {
            var accountRepository = DependencyResolver.Current.GetService<IAccountRepository>();

            string errorMessage;
            if (!accountRepository.AddAccount(newTopPortfolio.AddAccountModel))
            {
                errorMessage = Resource.ErrorMessageNotCreateAccountForTopPortfolio + " " + newTopPortfolio.AddAccountModel.UserName;
                Logger.Error("SubscribeOnPortfolioOnNewAccount() - " + errorMessage);
                return errorMessage;
            }

            newTopPortfolio.ManagedAccount = accountRepository.GetAccountId(newTopPortfolio.AddAccountModel.UserLogin);

            var topPortfolio = AddTopPortfolio(newTopPortfolio);
            if (topPortfolio == null)
            {
                errorMessage = Resource.ErrorMessageTopPortfolioUnableAdd;
                Logger.Error(errorMessage);
                return errorMessage;
            }

            Logger.Info("Новый портфель роботов создан");
            try
            {
                var proxy = new TradeSharpServerTrade(EmptyTradeSharpCallbackReceiver.Instance).proxy;
                var status = proxy.SubscribeOnPortfolio(ProtectedOperationContext.MakeServerSideContext(),
                    newTopPortfolio.AddAccountModel.UserLogin, topPortfolio, null, Utils.GetDefaultPortfolioTradeSettings());
                if (status != RequestStatus.OK)
                {
                    errorMessage = Resource.ErrorMessageUnableSignAccount;
                    Logger.Error(errorMessage);
                    return errorMessage;
                }
                return string.Empty;
            }
            catch (Exception ex)
            {
                errorMessage = Resource.ErrorMessageUnableSignAccount + ": " + ex.Message;
                Logger.Error("AddTopPortfolio", ex);
            }
            return errorMessage;
        }
        public string SubscribeOnPortfolioOnExistAccount(TopPortfolioItem newTopPortfolio)
        {
            string errorMessage;
            if (!newTopPortfolio.ManagedAccount.HasValue)
            {
                errorMessage = Resource.ErrorMessageCampaignAccount;
                Logger.Error(errorMessage);
                return errorMessage;
            }

            var ownerUser = userRepository.GetAccountOwner(newTopPortfolio.ManagedAccount.Value);
            if (ownerUser == null)
            {
                errorMessage = Resource.ErrorMessageNotFindUserAccountOwner;
                Logger.Error(errorMessage);
                return errorMessage;
            }

            var topPortfolio = AddTopPortfolio(newTopPortfolio);
            if (topPortfolio == null)
            {
                errorMessage = Resource.ErrorMessageTopPortfolioUnableAdd;
                Logger.Error(errorMessage);
                return errorMessage;
            }

            Logger.Info("Новый портфель роботов создан");
            try
            {
                var proxy = new TradeSharpServerTrade(EmptyTradeSharpCallbackReceiver.Instance).proxy;

                var status = proxy.SubscribeOnPortfolio(ProtectedOperationContext.MakeServerSideContext(),
                                                        ownerUser.Login, topPortfolio, null, Utils.GetDefaultPortfolioTradeSettings());
                if (status != RequestStatus.OK)
                {
                    errorMessage = Resource.ErrorMessageCampaignAccount;
                    Logger.Error(errorMessage);
                    return errorMessage;
                }
                return string.Empty;
            }
            catch (Exception ex)
            {
                errorMessage = Resource.ErrorMessageUnableSignAccount + ": " + ex.Message;
                Logger.Error("AddTopPortfolio", ex);
            }
            return errorMessage;
        }