public ActionResult Login(string userId, string password)
        {
            AccountInfo info = new AccountInfo();

            if (ModelState.IsValid)
            {
                info.userid = userId;
                info.password = password;
                try {
                    using (svcClient = new AccountServiceClient())
                    {
                        if (svcClient.Authenticate(info))
                        {
                            Session["IsAuthenticated"] = true;
                            Session["User"] = userId;
                            return View("LoggedIn");
                        }
                    }
                }
                catch (FaultException<AccountServiceFault> ex)
                {
                    HandleErrorInfo errorInfo = new HandleErrorInfo(ex, "Home", "Login");
                    return View("Error", errorInfo);
                }

            }
            ViewBag.LoginFailed = "Oops... user credential is not matched, please try again!";
            return View();
        }
Beispiel #2
0
    private void ShowAccountInfo(AccountInfo accountInfo)
    {
        LiteralResult.Text = string.Format("[{0}]{1} {2}", accountInfo.ZoneName, accountInfo.AccountName,StringDef.AccountInfo);
        TextAccount.Text = accountInfo.AccountName;
        TextZoneName.Text = accountInfo.ZoneName;
        TextEndDate.Text = accountInfo.EndDate.ToString();
        TextLeftSecond.Text = accountInfo.LeftSecond.ToString();
        TextLastLoginTime.Text = accountInfo.LastLoginTime.ToString();
        TextLastLoginIP.Text = accountInfo.LastLoginIP.ToString();
        TextLastLogoutTime.Text = accountInfo.LastLogoutTime.ToString();
        TextLeftCoin.Text = accountInfo.LeftCoin.ToString();
        TextLeftSecond.Text = accountInfo.LeftSecond.ToString();
        TextActiveIP.Text = accountInfo.ActiveIP.ToString();
        TextActiveTime.Text = accountInfo.ActiveTime.ToString();
        TextActiveType.Text = accountInfo.ActiveType.ToString();
        TextExtPoint0.Text = accountInfo.ExtPoint0.ToString();
        TextExtPoint1.Text = accountInfo.ExtPoint1.ToString();
        TextExtPoint2.Text = accountInfo.ExtPoint2.ToString();
        TextExtPoint3.Text = accountInfo.ExtPoint3.ToString();
        TextExtPoint4.Text = accountInfo.ExtPoint4.ToString();
        TextExtPoint5.Text = accountInfo.ExtPoint5.ToString();
        TextExtPoint6.Text = accountInfo.ExtPoint6.ToString();
        TextExtPoint7.Text = accountInfo.ExtPoint7.ToString();
        TextState.Text = TheAdminServer.PaySysAgent.GetAccountState(accountInfo.AccountName).ToString();
        TextGatewayInfo.Text = TheAdminServer.PaySysAgent.GetGatewayByAccount(accountInfo.AccountName);

        HyperLinkSetPassword.NavigateUrl = string.Format("~/PaySys/AccountPassword.aspx?{0}={1}",
            WebConfig.ParamAccount, accountInfo.AccountName);
    }
 /// <summary>
 /// 
 /// </summary>
 public ModifyOrderResponceMessage(AccountInfo sessionInfo, string orderId,
     string orderModifiedId, bool operationResult)
     : base(sessionInfo, operationResult)
 {
     _orderId = orderId;
     _orderModifiedId = orderModifiedId;
 }
 /// <summary>
 /// 
 /// </summary>
 public OrdersInformationUpdateResponseMessage(AccountInfo accountInfo, 
     OrderInfo[] orderInformations, ActiveOrder.UpdateTypeEnum[] ordersUpdates, bool operationResult)
     : base(accountInfo, operationResult)
 {
     _ordersUpdates = ordersUpdates;
     _orderInformations = orderInformations;
 }
        public static AccountRoles GetUserRole(string strUserName)
        {
            AccountInfo user = new AccountInfo();
            try
            {
                 user = CurrentUser.Details(strUserName);
            }
            catch (Exception)
            {
                FormsAuthentication.SignOut();
                HttpContext.Current.Items["loggedOut"] = true;
                HttpContext.Current.Response.RedirectToRoute("SignOut", null);

            }
            if (user != null)
            {
                return user.Role;
            }
            else
            {
                string result = OBSDataSource.GetUserProfile(long.Parse(strUserName), out user);

                if (string.IsNullOrEmpty(result))
                {
                    CurrentUser.CacheUser(user);
                    return CurrentUser.Details(strUserName).Role;
                }
                else
                {
                    //TODO
                    return AccountRoles.User;
                }
            }
        }
        protected override void Orders_OrderUpdatedEvent(ITradeEntityManagement provider, AccountInfo account, Order[] orders, ActiveOrder.UpdateTypeEnum[] updatesType)
        {
            base.Orders_OrderUpdatedEvent(provider, account, orders, updatesType);

            // Run in a separate thread since it takes time to request from server.
            //GeneralHelper.FireAndForget(new GeneralHelper.GenericReturnDelegate<bool>(Update));
        }
Beispiel #7
0
        // If account exists, check password correct.
        // Otherwise create new account with id and password.
        public static async Task<AccountInfo> AuthenticateAsync(string id, string password)
        {
            if (string.IsNullOrWhiteSpace(id))
                return null;

            var accountCollection = MongoDbStorage.Instance.Database.GetCollection<AccountInfo>("Account");
            await EnsureIndex(accountCollection);

            var account = await accountCollection.Find(a => a.Id == id).FirstOrDefaultAsync();
            if (account != null)
            {
                if (PasswordUtility.Verify(password, account.PassSalt, account.PassHash) == false)
                    return null;

                account.LastLoginTime = DateTime.UtcNow;
                await accountCollection.ReplaceOneAsync(a => a.Id == id, account);
            }
            else
            {
                var saltHash = PasswordUtility.CreateSaltHash(password);
                account = new AccountInfo
                {
                    Id = id,
                    PassSalt = saltHash.Item1,
                    PassHash = saltHash.Item2,
                    UserId = UniqueInt64Id.GenerateNewId(),
                    RegisterTime = DateTime.UtcNow,
                    LastLoginTime = DateTime.UtcNow
                };
                await accountCollection.InsertOneAsync(account);
            }

            return account;
        }
        public bool IsFiscalOfficer(AccountInfo account, string userId)
        {
            var client = InitializeClient();

            var result = client.isUserFiscalOfficerForAccount(userId, account.Chart, account.Number);

            return result;
        }
        public AccountInfo GetAccountInfo(AccountInfo account)
        {
            var client = InitializeClient();

            var result = client.getSimpleAccountInfo(account.Chart, account.Number);

            return new AccountInfo(result);
        }
 public bool DecreaseOrderVolume(AccountInfo accountInfo, string orderId, decimal volumeDecreasal, decimal? allowedSlippage,
     decimal? desiredPrice, out decimal decreasalPrice, out string modifiedId, out string operationResultMessage)
 {
     decreasalPrice = 0;
     modifiedId = string.Empty;
     operationResultMessage = "The operation is not supported by this provider.";
     return false;
 }
 /// <summary>
 /// Close order.
 /// </summary>
 public CloseOrderVolumeMessage(AccountInfo accountInfo, Symbol symbol, string orderId, string orderTag, decimal? price, decimal? slippage)
     : base(accountInfo)
 {
     _symbol = symbol;
     _orderId = orderId;
     _price = price;
     _slippage = slippage;
     _orderTag = orderTag;
 }
 /// <summary>
 /// 
 /// </summary>
 public CloseOrderVolumeResponceMessage(AccountInfo sessionInfo, string orderId,
     string orderModifiedId, decimal closingPrice, DateTime closingDateTime, bool operationResult)
     : base(sessionInfo, operationResult)
 {
     _orderId = orderId;
     _orderModifiedId = orderModifiedId;
     _closingPrice = closingPrice;
     _closingDateTime = closingDateTime;
 }
 public bool CloseOrCancelOrder(AccountInfo accountInfo, string orderId, string orderTag,
     decimal? allowedSlippage, decimal? desiredPrice, out decimal closingPrice,
     out DateTime closingTime, out string modifiedId, out string operationResultMessage)
 {
     closingPrice = 0;
     closingTime = DateTime.MinValue;
     modifiedId = string.Empty;
     operationResultMessage = "The operation is not supported by this provider.";
     return false;
 }
Beispiel #14
0
        public void InsertTest()
        {
            AccountDao target = new AccountDao(); // TODO: 初始化为适当的值
            AccountInfo account = new AccountInfo(); // TODO: 初始化为适当的值
            account.UserName = "******";
            account.Password = "******";

            object expected = null; // TODO: 初始化为适当的值
            object actual;
            actual = target.Register(account);
        }
Beispiel #15
0
        /// <summary>
        /// ����һ�����˺�
        /// </summary>
        /// <returns></returns>
        public static Account CreateNewAccount()
        {
            string name = "NewAccount" + _accountList.Count + 1;
            AccountInfo accountInfo = new AccountInfo() {Username = name};
            Config.BuyTicketConfig.Instance.AccountInfos.Add(accountInfo);
            Config.BuyTicketConfig.Save();
            Account account = new Account(accountInfo);
            _accountList.Add(account);

            return account;
        }
        /// <summary>
        /// 
        /// </summary>
        public OrdersInformationUpdateResponseMessage(AccountInfo accountInfo, 
            OrderInfo[] orderInformations, bool operationResult)
            : base(accountInfo, operationResult)
        {
            _orderInformations = orderInformations;

            _ordersUpdates = new Order.UpdateTypeEnum[_orderInformations.Length];
            for (int i = 0; i < _orderInformations.Length; i++)
            {
                _ordersUpdates[i] = Order.UpdateTypeEnum.Update;
            }
        }
Beispiel #17
0
        public void SampleMenu()
        {
            account = new AccountInfo ();

            context = new BindingContext (this, account, "Settings");

            if (dynamic != null)
                dynamic.Dispose ();

            dynamic = new DialogViewController (context.Root, true);
            navigation.PushViewController (dynamic, true);
        }
    /// <summary>
    /// OnAfterDataLoad event handler.
    /// </summary>
    protected void EditForm_OnAfterDataLoad(object sender, EventArgs e)
    {
        ai = (AccountInfo)EditForm.EditedObject;

        if ((EditForm.EditedObject != null) && (ai.AccountID != 0))
        {
            SiteID = ValidationHelper.GetInteger(EditForm.Data["AccountSiteID"], 0);
        }

        // AccountStatusSelector
        SetControl("accountstatusid", ctrl => ctrl.SetValue("siteid", SiteID));
    }
 /// <summary>
 /// 
 /// </summary>
 public OrderMessage(AccountInfo accountInfo, Symbol symbol, OrderTypeEnum orderType, int volume, decimal? price, decimal? slippage, 
     decimal? takeProfit, decimal? stopLoss, string comment)
     : base(accountInfo)
 {
     _symbol = symbol;
     _orderType = orderType;
     _volume = volume;
     _desiredPrice = price;
     _slippage = slippage;
     _takeProfit = takeProfit;
     _stopLoss = stopLoss;
     _comment = comment;
 }
        /// <summary>
        /// Pass double.Nan for any parameter to assign it to "not assigned", pass null to leave unchanged.
        /// </summary>
        public ModifyOrderMessage(AccountInfo account, Symbol symbol, string orderId, decimal? stopLoss, decimal? takeProfit, decimal? targetOpenPrice, DateTime? expiration)
            : base(account)
        {
            _symbol = symbol;
            _orderId = orderId;
            _takeProfit = takeProfit;
            _stopLoss = stopLoss;
            _targetOpenPrice = targetOpenPrice;

            if (_expiration.HasValue)
            {
                _expiration = GeneralHelper.GenerateSecondsDateTimeFrom1970(expiration.Value);
            }
        }
Beispiel #21
0
        public EditAccount(IAccountContainer container, TwitterAccount account, bool pushing)
        {
            var info = new AccountInfo ();
            bool newAccount = account == null;

            if (newAccount)
                account = new TwitterAccount ();
            else {
                info.Login = account.Username;
                //info.Password = account.Password;
            }

            var bc = new BindingContext (this, info, Locale.GetText ("Edit Account"));
            var dvc = new DialogViewController (bc.Root, true);
            PushViewController (dvc, false);
            UIBarButtonItem done = null;
            done = new UIBarButtonItem (UIBarButtonSystemItem.Done, delegate {
                bc.Fetch ();

                done.Enabled = false;
                CheckCredentials (info, delegate (string errorMessage) {
                    Util.PopNetworkActive ();
                    done.Enabled = true;

                    if (errorMessage == null){
                        account.Username = info.Login;
                        //account.Password = info.Password;

                        lock (Database.Main){
                            if (newAccount)
                                Database.Main.Insert (account);
                            else
                                Database.Main.Update (account);
                        }

                        account.SetDefaultAccount ();
                        DismissModalViewControllerAnimated (true);
                        container.Account = account;
                    } else {
                        dlg = new UIAlertView (Locale.GetText ("Login error"), errorMessage, null, Locale.GetText ("Close"));
                        dlg.Show ();
                    }
                });
            });

            dvc.NavigationItem.SetRightBarButtonItem (done, false);
        }
 static void Main()
 {
     AccountInfo client = new AccountInfo();
     string line = new string('-', 40);
     Console.WriteLine(line);
     Console.WriteLine(client.firstName);
     Console.WriteLine(client.middleName);
     Console.WriteLine(client.lastName);
     Console.WriteLine(client.balance);
     Console.WriteLine(client.bankName);
     Console.WriteLine(client.iban);
     Console.WriteLine(client.bic);
     Console.WriteLine(client.creditCard1);
     Console.WriteLine(client.creditCard2);
     Console.WriteLine(client.creditCard3);
     Console.WriteLine(line);
 }
        public System.Web.Mvc.ActionResult SendMessage(string msgContent, long senderId, long receiverId)
        {
            AccountInfo senderInfo = new AccountInfo();
            AccountInfo receiverInfo = new AccountInfo();
            OBSDataSource.GetUserProfile(senderId, out senderInfo);
            OBSDataSource.GetUserProfile(receiverId, out receiverInfo);

            ChatMessage message = new ChatMessage();
            message.Message = msgContent;
            message.SenderId = senderId;
            message.SenderName = senderInfo.FirstName;
            message.ReceiverId = receiverId;
            message.ReceiverName = receiverInfo.FirstName;
            message.SentTime = DateTime.Now;

            ChatHistory.SaveNewMessage(message);

            return Json(JsonConvert.SerializeObject(new { Success = true }),JsonRequestBehavior.AllowGet);
        }
        public bool ExecuteMarketOrder(AccountInfo accountInfo, Symbol symbol, OrderTypeEnum orderType, int volume, decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss, string comment, out OrderInfo? orderPlaced, out string operationResultMessage)
        {
            operationResultMessage = string.Empty;
            string operationResultMessageCopy = string.Empty;
            object orderId, psd;

            bool isBuy = OrderInfo.TypeIsBuy(orderType);

            OrderInfo? order = null;
            GeneralHelper.GenericReturnDelegate<bool> operationDelegate = delegate()
            {
                _manager.Desk.OpenTrade(accountInfo.Id, symbol.Name, isBuy, _adapter.DefaultLotSize, (double)desiredPrice.Value, (string)_adapter.GetInstrumentData(symbol.Name, "QuoteID"), 0, (double)stopLoss.Value, (double)takeProfit.Value, 0, out orderId, out psd);

                order = new OrderInfo();
                OrderInfo tempOrder = order.Value;
                tempOrder.Id = orderId.ToString();

                TableAut accountsTable = (FXCore.TableAut)_manager.Desk.FindMainTable("trades");

                RowAut item = (RowAut)accountsTable.FindRow("OrderID", orderId, 0);

                return true;
            };

            orderPlaced = order;

            object result;
            if (_messageLoopOperator.Invoke(operationDelegate, TimeSpan.FromSeconds(8), out result) == false)
            {// Timed out.
                operationResultMessage = "Timeout submiting order.";
                return false;
            }

            if (string.IsNullOrEmpty((string)result))
            {// Operation error.
                operationResultMessage = operationResultMessageCopy;
                return false;
            }

            return true;
        }
Beispiel #25
0
        public static Guid AddUser(string accountName, string password, string email, bool locked, string[] roles, ref string msg)
        {
            if (Accounts.ContainsKey(accountName))
            {
                msg = "Account name already exists.";
                return Guid.Empty;
            }

            AccountInfo ai = new AccountInfo();
            ai.AccountName = accountName;
            ai.AccountID = Guid.NewGuid();
            ai.Email = email;
            ai.Locked = locked;
            ai.Password = CryptoManager.GetSHA256Hash(password);
            ai.Roles = new List<string>(roles);

            Accounts.Add(accountName, ai);

            if (CurrentPath.Length != 0)
            {
                SaveFile(CurrentPath);
            }
            return ai.AccountID;
        }
        // Called forth when new user has to be created.
        public EditAccountModel()
        {
            User = new AccountInfo();
            User.Preferences = new UserPreferences();
            User.Preferences.DocumentFontSize = Constants.DefaultDocumentFontSize;
            User.Preferences.DocumentFontName = Constants.DefaultDocumentFontName;
            User.Role = AccountRoles.User;
            User.CarerId = CurrentUser.Details(HttpContext.Current.User.Identity.Name).AccountId;
            User.Preferences.SelectedDocumentSimplificationTools = Constants.DefaultSimplificationTools;
            User.Preferences.CurrentTheme = new Theme();

            IEnumerable<LanguagePreference> prefs = null;

            string result = OBSDataSource.GetDefaultLanguageSettings(out prefs);
            if (string.IsNullOrEmpty(result))
            {
                User.Preferences.LanguagePreferences = prefs.ToArray();
            }
            else
            {
                User.Preferences.LanguagePreferences = new List<LanguagePreference>().ToArray();
            }
            IsUpdate = false;
        }
Beispiel #27
0
        public static DataSet GetAccountInfo(int contactID)
        {
            IDalSession session = null;
            DataSet ds = null;
            session = NHSessionFactory.CreateSession();
            ArrayList listAccounts = new ArrayList();

            IContact contact = ContactMapper.GetContact(session, contactID);
            if (contact != null && contact.AccountHolders != null)
            {
                foreach (IAccountHolder contactAH in contact.AccountHolders)
                {
                    ICustomerAccount acc = contactAH.GiroAccount;

                    AccountInfo accountInfo = new AccountInfo();
                    accountInfo.AccountKey = acc.Key;
                    accountInfo.Number = contactAH.GiroAccount.Number;
                    accountInfo.ShortName = acc.ShortName;
                    foreach (IAccountHolder accAH in acc.AccountHolders)
                    {
                        if (accAH.IsPrimaryAccountHolder)
                        {
                            IContact primaryContact = accAH.Contact;
                            accountInfo.PrimaryAhName = primaryContact.FullName;
                        }

                    }
                    accountInfo.ContactKey = contact.Key;
                    listAccounts.Add(accountInfo);
                }
                ds = DataSetBuilder.CreateDataSetFromBusinessObjectList(
                     listAccounts, "AccountKey, ContactKey, Number, PrimaryAhName, ShortName");
            }
            session.Close();
            return ds;
        }
Beispiel #28
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="accountInfo">The account information.</param>
        public AccountInfoCacheEventArgs(AccountInfo accountInfo)
        {
            Throw.IfNull(accountInfo, nameof(accountInfo));

            AccountInfo = accountInfo;
        }
 public AuthenticateResponse(AccountInfo user, string jwtToken, string refreshToken)
 {
     AccountInfo  = user;
     AccessToken  = jwtToken;
     RefreshToken = refreshToken;
 }
Beispiel #30
0
        public static Tuple <DateTime, int> GetUnderControlChunk(AccountInfo info)
        {
            // based on http://ltzz.info/alpha/twitter_kisei.html
            // セクション(Under control chunk)を導出する

            // とりあえずこのユーザーの全ツイートを持ってくる
            // 投稿時間配列にする
            var times = TweetStorage.GetAll(t => t.Status.User.ScreenName == info.ScreenName)
                        .Select(t => t.Status.CreatedAt)
                        .OrderByDescending(t => t) // 新着順に並べる
                        .ToArray();

            // 全ツイートのうち、3時間以上の投稿の空きがある部分を調べる
            int initPoint = -1;

            for (int i = 0; i < times.Length; i++)
            {
                // 前のツイートまで、3時間以上の空きがあるとそこがチャンクの切れ目
                if (i + 1 < times.Length &&
                    times[i] - times[i + 1] > TwitterDefine.UnderControlTimespan)
                {
                    // ここがチャンクの切れ目
                    initPoint = i;
                    break;
                }
                else if (i + TwitterDefine.UnderControlCount < times.Length &&
                         times[i + 1] - times[i + TwitterDefine.UnderControlCount] <
                         TwitterDefine.UnderControlTimespan)
                {
                    // UnderControlTimespanの期間中、UnderControlCountを超える投稿がある
                    // →チャンクの切れ目
                    initPoint = i;
                    break;
                }
            }

            while (initPoint >= 0 &&
                   DateTime.Now.Subtract(times[initPoint]) > TwitterDefine.UnderControlTimespan)
            {
                // 導出したチャンクから現在消費中のチャンクを推測する
                // チャンクのスタートポイントがチャンク時間内でない場合、チャンク時間後のツイートを順番に辿る
                var  chunkEnd = times[initPoint] + TwitterDefine.UnderControlTimespan;
                bool found    = false;
                for (int i = initPoint; i >= 0; i--)
                {
                    if (times[initPoint] >= chunkEnd)
                    {
                        initPoint = i;
                        found     = true;
                        break;
                    }
                }
                // チャンクの導出ができないとは何事だ
                if (!found)
                {
                    initPoint = -1;
                }
            }

            if (initPoint >= 0)
            {
                // 結局チャンクの導出がしっかりできた
                return(new Tuple <DateTime, int>(times[initPoint].Add(TwitterDefine.UnderControlTimespan), initPoint));
            }
            else
            {
                // なんかだめだった
                // 規制開始ポイントが分からないので、とりあえずウィンドウタイムだけ遡る
                var window = times.Where(d => d > DateTime.Now.Subtract(TwitterDefine.UnderControlTimespan))
                             .OrderBy(d => d);
                var initt = window.FirstOrDefault();
                if (initt != null)
                {
                    return(new Tuple <DateTime, int>(initt.Add(TwitterDefine.UnderControlTimespan),
                                                     window.Count()));
                }
                else
                {
                    return(new Tuple <DateTime, int>(DateTime.MinValue, 0));
                }
            }
        }
Beispiel #31
0
        public static int UpdateTweet(AccountInfo info, string text, long?inReplyToId = null)
        {
            int retryCount = 0;

            do
            {
                try
                {
                    updateInjection.Execute(new Tuple <AccountInfo, string, long?>(info, text, inReplyToId));
                    break; // break roop on succeeded
                }
                catch (WebException wex)
                {
                    if (wex.Status == WebExceptionStatus.ProtocolError)
                    {
                        var hrw = wex.Response as HttpWebResponse;
                        if (hrw != null && hrw.StatusCode == HttpStatusCode.Forbidden)
                        {
                            // 規制?
                            using (var strm = hrw.GetResponseStream())
                                using (var json = JsonReaderWriterFactory.CreateJsonReader(strm,
                                                                                           System.Xml.XmlDictionaryReaderQuotas.Max))
                                {
                                    var xdoc = XDocument.Load(json);
                                    System.Diagnostics.Debug.WriteLine(xdoc);
                                    var eel = xdoc.Root.Element("errors");
                                    if (eel != null)
                                    {
                                        if (eel.Value.IndexOf("update limit", StringComparison.CurrentCultureIgnoreCase) >= 0)
                                        {
                                            // User is over daily status update limit.
                                            // POST規制
                                            AddUnderControlled(info);
                                            throw new TweetFailedException(TweetFailedException.TweetErrorKind.Controlled);
                                        }
                                        else if (eel.Value.IndexOf("duplicate", StringComparison.CurrentCultureIgnoreCase) >= 0)
                                        {
                                            // 同じツイートをしようとした
                                            if (retryCount == 0) // 複数回投稿している場合はサスペンドする
                                            {
                                                throw new TweetFailedException(TweetFailedException.TweetErrorKind.Duplicated);
                                            }
                                            else
                                            {
                                                break; // 成功
                                            }
                                        }
                                        else
                                        {
                                            // 何かよくわからない
                                            throw new TweetFailedException(TweetFailedException.TweetErrorKind.CommonFailed, eel.Value);
                                        }
                                    }
                                }
                        }
                        // 何かよくわからない
                        throw new TweetFailedException(TweetFailedException.TweetErrorKind.CommonFailed, wex.Message);
                    }
                    else
                    {
                        if (!Setting.Instance.InputExperienceProperty.AutoRetryOnError)
                        {
                            if (wex.Status == WebExceptionStatus.Timeout)
                            {
                                // タイムアウト
                                throw new TweetFailedException(TweetFailedException.TweetErrorKind.Timeout, "ツイートに失敗しました(タイムアウトしました。Twitterが不調かも)", wex);
                            }
                            else
                            {
                                // 何かがおかしい
                                throw new TweetFailedException(TweetFailedException.TweetErrorKind.CommonFailed, "ツイートに失敗しました(" + (int)wex.Status + ")", wex);
                            }
                        }
                    }
                }
                catch (TweetAnnotationException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw new TweetFailedException(TweetFailedException.TweetErrorKind.CommonFailed, "ツイートに失敗しました(" + ex.Message + ")", ex);
                }
            } while (Setting.Instance.InputExperienceProperty.AutoRetryOnError && retryCount++ < Setting.Instance.InputExperienceProperty.AutoRetryMaxCount);

            var chunk = GetUnderControlChunk(info);

            if (chunk.Item2 > TwitterDefine.UnderControlWarningThreshold)
            {
                throw new TweetAnnotationException(TweetAnnotationException.AnnotationKind.NearUnderControl);
            }

            return(chunk.Item2);
        }
 public PoloniexAccountBalanceInfo(AccountInfo info) : base(info)
 {
 }
Beispiel #33
0
        private void CalculationMoney(DateTime startDate, DateTime endDate)
        {
            DateTime?finishDate;

            string[] str;
            Entities entity = new Entities();
            var      list   = (
                from p in entity.OrderInfo
                join o in entity.OrderRefundInfo on p.Id equals o.OrderId
                join x in entity.OrderItemInfo on o.OrderId equals x.OrderId
                where (int)p.OrderStatus == 5 && (o.ManagerConfirmDate >= startDate) && (o.ManagerConfirmDate < endDate) && (int)o.ManagerConfirmStatus == 7
                select new { Order = p, OrderRefund = o, OrderItem = x }).Distinct().ToList();
            var collection = (
                from p in entity.OrderInfo
                join o in entity.OrderItemInfo on p.Id equals o.OrderId
                where (int)p.OrderStatus == 5 && (p.FinishDate >= startDate) && (p.FinishDate < endDate)
                select new { Order = p, OrderItem = o }).ToList();
            List <long> nums = new List <long>();

            nums.AddRange(
                from c in list
                select c.Order.ShopId);
            nums.AddRange(
                from c in collection
                select c.Order.ShopId);
            nums = nums.Distinct <long>().ToList();
            using (TransactionScope transactionScope = new TransactionScope())
            {
                try
                {
                    foreach (long num in nums)
                    {
                        List <OrderInfo> orderInfos = (
                            from c in collection
                            where c.Order.ShopId == num
                            select c.Order).Distinct <OrderInfo>().ToList();
                        decimal num1 = orderInfos.Sum <OrderInfo>((OrderInfo c) => c.ProductTotalAmount) - orderInfos.Sum <OrderInfo>((OrderInfo c) => c.DiscountAmount);
                        decimal num2 = orderInfos.Sum <OrderInfo>((OrderInfo c) => c.Freight);
                        decimal num3 = CalculationTotalCommission((
                                                                      from c in collection
                                                                      where c.Order.ShopId == num
                                                                      select c.OrderItem).Distinct <OrderItemInfo>().ToList());
                        decimal num4 = CalculationTotalRefundCommission((
                                                                            from c in list
                                                                            where c.OrderRefund.ShopId == num
                                                                            select c.OrderItem).Distinct <OrderItemInfo>().ToList());
                        decimal num5 = (
                            from c in list
                            where c.OrderRefund.ShopId == num
                            select c.OrderRefund).Distinct <OrderRefundInfo>().Sum <OrderRefundInfo>((OrderRefundInfo c) => c.Amount);
                        decimal     num6        = (((num1 + num2) - num3) - num5) + num4;
                        AccountInfo accountInfo = new AccountInfo()
                        {
                            ShopId   = num,
                            ShopName = (
                                from c in entity.ShopInfo
                                where c.Id == num
                                select c).FirstOrDefault().ShopName,
                            AccountDate             = DateTime.Now,
                            StartDate               = startDate,
                            EndDate                 = endDate.AddSeconds(-1),
                            Status                  = AccountInfo.AccountStatus.UnAccount,
                            ProductActualPaidAmount = num1,
                            FreightAmount           = num2,
                            CommissionAmount        = num3,
                            RefundCommissionAmount  = num4,
                            RefundAmount            = num5,
                            PeriodSettlement        = num6,
                            Remark                  = string.Empty
                        };
                        entity.AccountInfo.Add(accountInfo);
                        foreach (OrderInfo orderInfo in (
                                     from c in list
                                     where c.Order.ShopId == num
                                     select c.Order).Distinct <OrderInfo>().ToList())
                        {
                            AccountDetailInfo accountDetailInfo = new AccountDetailInfo()
                            {
                                Himall_Accounts = accountInfo,
                                ShopId          = orderInfo.ShopId
                            };
                            finishDate                  = orderInfo.FinishDate;
                            accountDetailInfo.Date      = finishDate.Value;
                            accountDetailInfo.OrderType = AccountDetailInfo.EnumOrderType.ReturnOrder;
                            accountDetailInfo.OrderId   = orderInfo.Id;
                            accountDetailInfo.ProductActualPaidAmount = orderInfo.ProductTotalAmount - orderInfo.DiscountAmount;
                            accountDetailInfo.FreightAmount           = orderInfo.Freight;
                            accountDetailInfo.CommissionAmount        = CalculationTotalCommission((
                                                                                                       from c in list
                                                                                                       where c.OrderRefund.OrderId == orderInfo.Id
                                                                                                       select c.OrderItem).Distinct <OrderItemInfo>().ToList());
                            accountDetailInfo.RefundCommisAmount = CalculationTotalRefundCommission((
                                                                                                        from c in list
                                                                                                        where c.OrderRefund.OrderId == orderInfo.Id
                                                                                                        select c.OrderItem).Distinct <OrderItemInfo>().ToList());
                            accountDetailInfo.RefundTotalAmount = (
                                from c in list
                                where c.OrderRefund.OrderId == orderInfo.Id
                                select c.OrderRefund).Distinct <OrderRefundInfo>().Sum <OrderRefundInfo>((OrderRefundInfo c) => c.Amount);
                            accountDetailInfo.OrderDate         = orderInfo.OrderDate;
                            accountDetailInfo.OrderRefundsDates = string.Join <DateTime>(";", (
                                                                                             from c in list
                                                                                             where c.OrderRefund.OrderId == orderInfo.Id
                                                                                             select c.OrderRefund.ManagerConfirmDate).Distinct <DateTime>());
                            entity.AccountDetailInfo.Add(accountDetailInfo);
                        }
                        foreach (OrderInfo orderInfo1 in orderInfos)
                        {
                            AccountDetailInfo value = new AccountDetailInfo()
                            {
                                Himall_Accounts = accountInfo,
                                ShopId          = orderInfo1.ShopId
                            };
                            finishDate      = orderInfo1.FinishDate;
                            value.Date      = finishDate.Value;
                            value.OrderType = AccountDetailInfo.EnumOrderType.FinishedOrder;
                            value.OrderId   = orderInfo1.Id;
                            value.ProductActualPaidAmount = orderInfo1.ProductTotalAmount - orderInfo1.DiscountAmount;
                            value.FreightAmount           = orderInfo1.Freight;
                            value.CommissionAmount        = CalculationTotalCommission((
                                                                                           from c in collection
                                                                                           where c.Order.Id == orderInfo1.Id
                                                                                           select c.OrderItem).Distinct <OrderItemInfo>().ToList());
                            value.RefundCommisAmount = new decimal(0);
                            value.RefundTotalAmount  = new decimal(0);
                            value.OrderDate          = orderInfo1.OrderDate;
                            value.OrderRefundsDates  = string.Empty;
                            entity.AccountDetailInfo.Add(value);
                        }
                    }
                    entity.SaveChanges();
                    transactionScope.Complete();
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    str = new string[] { "CalculationMoney :startDate=", startDate.ToString(), " endDate=", endDate.ToString(), "/r/n", exception.Message };
                    Log.Error(string.Concat(str));
                }
            }
            try
            {
                var list1 = (
                    from b in entity.ActiveMarketServiceInfo
                    join c in entity.MarketServiceRecordInfo on b.Id equals c.MarketServiceId
                    join d in nums on b.ShopId equals d
                    join aa in entity.MarketSettingInfo on b.TypeId equals aa.TypeId
                    where c.SettlementFlag == 0
                    select new { ShopId = b.ShopId, TypeId = b.TypeId, Price = ((c.EndTime.Year * 12 + c.EndTime.Month - (c.StartTime.Year * 12 + c.StartTime.Month)) * aa.Price), MSRecordId = c.Id, StartTime = c.StartTime, EndTime = c.EndTime }).ToList();
                List <AccountInfo> accountInfos = (
                    from e in entity.AccountInfo
                    where e.StartDate == startDate
                    select e).ToList();
                IEnumerable <long> nums1 = (
                    from e in list1
                    select e.ShopId).Distinct <long>();
                foreach (AccountInfo periodSettlement in accountInfos)
                {
                    var shopId =
                        from e in list1
                        where e.ShopId == periodSettlement.ShopId
                        select e;
                    foreach (var variable in shopId)
                    {
                        periodSettlement.PeriodSettlement     = periodSettlement.PeriodSettlement - variable.Price;
                        periodSettlement.AdvancePaymentAmount = periodSettlement.AdvancePaymentAmount + variable.Price;
                        DbSet <AccountMetaInfo> accountMetaInfo  = entity.AccountMetaInfo;
                        AccountMetaInfo         accountMetaInfo1 = new AccountMetaInfo()
                        {
                            AccountId        = periodSettlement.Id,
                            MetaKey          = variable.TypeId.ToDescription(),
                            MetaValue        = variable.Price.ToString("f2"),
                            ServiceStartTime = variable.StartTime,
                            ServiceEndTime   = variable.EndTime
                        };
                        accountMetaInfo.Add(accountMetaInfo1);
                    }
                }
                var collection1 = (
                    from a in entity.MarketServiceRecordInfo
                    join b in entity.ActiveMarketServiceInfo on a.MarketServiceId equals b.Id
                    join c in nums1 on b.ShopId equals c
                    where a.SettlementFlag == 0
                    select new { Shopid = b.ShopId, TypeId = b.TypeId, Msrecordid = a.Id }).ToList();
                foreach (var variable1 in collection1)
                {
                    MarketServiceRecordInfo marketServiceRecordInfo = entity.MarketServiceRecordInfo.FirstOrDefault((MarketServiceRecordInfo e) => e.Id == variable1.Msrecordid);
                    marketServiceRecordInfo.SettlementFlag = 1;
                }
                entity.SaveChanges();
            }
            catch (Exception exception3)
            {
                Exception exception2 = exception3;
                str = new string[] { "CalculationMoney 服务费:startDate=", startDate.ToString(), " endDate=", endDate.ToString(), "/r/n", exception2.Message };
                Log.Error(string.Concat(str));
            }
        }
Beispiel #34
0
        public ActionResult LogOn(AccountInfo m)
        {
            Session.Remove("IsNonFinanceImpersonator");
            TryLoadAlternateShell();
            if (m.ReturnUrl.HasValue())
            {
                var lc = m.ReturnUrl.ToLower();
                if (lc.StartsWith("/default.aspx") || lc.StartsWith("/login.aspx"))
                {
                    m.ReturnUrl = "/";
                }
            }

            if (!m.UsernameOrEmail.HasValue())
            {
                return(View(m));
            }

            var ret = AccountModel.AuthenticateLogon(m.UsernameOrEmail, m.Password, Session, Request);

            if (ret is string)
            {
                ViewBag.error = ret.ToString();
                return(View(m));
            }
            var user = ret as User;

            if (user.MustChangePassword)
            {
                return(Redirect("/Account/ChangePassword"));
            }

            var access = DbUtil.Db.Setting("LimitAccess", "");

            if (access.HasValue())
            {
                if (!user.InRole("Developer"))
                {
                    return(Message($"Site is {access}, contact {DbUtil.AdminMail} for help"));
                }
            }

            var newleadertag = DbUtil.Db.FetchTag("NewOrgLeadersOnly", user.PeopleId, DbUtil.TagTypeId_System);

            if (newleadertag != null)
            {
                if (!user.InRole("Access")) // if they already have Access role, then don't limit them with OrgLeadersOnly
                {
                    user.AddRoles(DbUtil.Db, "Access,OrgLeadersOnly".Split(','));
                }
                DbUtil.Db.Tags.DeleteOnSubmit(newleadertag);
                DbUtil.Db.SubmitChanges();
            }

            if (!m.ReturnUrl.HasValue())
            {
                if (!CMSRoleProvider.provider.IsUserInRole(user.Username, "Access"))
                {
                    return(Redirect("/Person2/" + Util.UserPeopleId));
                }
            }
            if (m.ReturnUrl.HasValue() && Url.IsLocalUrl(m.ReturnUrl))
            {
                return(Redirect(m.ReturnUrl));
            }
            return(Redirect("/"));
        }
 public WeaponStatsRequest(AccountInfo account)
     : base(account)
 {
 }
Beispiel #36
0
 public BalanceBase(AccountInfo info)
 {
     Account = info;
 }
        /// <summary>
        /// Make sure to call on Invoke'd thread.
        /// </summary>
        /// <param name="account"></param>
        void PerformUpdate(MbtAccount account, bool updateAccount, bool updateOrders, bool updatePositions)
        {
            //SystemMonitor.CheckError(_messageLoopOperator.InvokeRequred == false, "Invoke must not be required in baseMethod call.");

            MbtOrderClient orderClient = _orderClient;
            MBTradingConnectionManager manager = _manager;
            MBTradingQuote quotes = null;

            if (orderClient == null || manager == null)
            {
                return;
            }

            quotes = manager.Quotes;
            if (quotes == null)
            {
                return;
            }

            AccountInfo info;
            Dictionary<string, OrderInfo> pendingOrderInfos = new Dictionary<string, OrderInfo>();
            List<PositionInfo> positionsInfos = new List<PositionInfo>();
            lock (this)
            {
                if (updateOrders)
                {
                    // We need to send up only the latest of each orders histories, since prev ones are for previous states.
                    foreach (MbtOrderHistory history in _orderClient.OrderHistories)
                    {
                        Order.UpdateTypeEnum updateType;
                        OrderInfo? orderInfo = ConvertToOrderInfo(history, out updateType);
                        if (orderInfo.HasValue)
                        {
                            pendingOrderInfos[orderInfo.Value.Id] = orderInfo.Value;
                        }
                    }

                    // Make sure open orders orderInfo is always on top.
                    foreach (MbtOpenOrder pOrd in _orderClient.OpenOrders)
                    {
                        OrderInfo? orderInfo = ConvertToOrderInfo(pOrd);
                        if (orderInfo.HasValue)
                        {
                            pendingOrderInfos[orderInfo.Value.Id] = orderInfo.Value;
                        }
                    }
                }

                if (updatePositions)
                {
                    foreach (MbtPosition position in _orderClient.Positions)
                    {
                        PositionInfo? positionInfo = ConvertToPositionInfo(position);
                        if (positionInfo.HasValue)
                        {
                            positionsInfos.Add(positionInfo.Value);
                        }
                    }
                }

                if (_accountInfo.HasValue)
                {
                    info = _accountInfo.Value;
                }
                else
                {
                    info = new AccountInfo();
                    info.Guid = Guid.NewGuid();
                }

                 ConvertAccount(account, ref info);

                _accountInfo = info;
            }

            MBTradingAdapter adapter = _adapter;
            if (adapter != null)
            {
                OrderExecutionSourceStub stub = adapter.OrderExecutionSourceStub;
                if (stub != null)
                {
                    if (updateAccount)
                    {
                        stub.UpdateAccountInfo(_accountInfo.Value);
                    }

                    if (updateOrders)
                    {
                        stub.UpdateOrdersInfo(_accountInfo.Value,
                            GeneralHelper.GenerateSingleValueArray<Order.UpdateTypeEnum>(pendingOrderInfos.Count, Order.UpdateTypeEnum.Update),
                             GeneralHelper.EnumerableToArray<OrderInfo>(pendingOrderInfos.Values));
                    }

                    if (updatePositions)
                    {
                        stub.UpdatePositionsInfo(_accountInfo.Value, positionsInfos.ToArray());
                    }
                }
            }
        }
        public void OnAuthLoginRequestPacketReceive(GamePacketReceiveEvent e)
        {
            if (e.Packet is AuthLoginRequestPacket)
            {
                AuthLoginRequestPacket request = (AuthLoginRequestPacket)e.Packet;

                string username        = request.Username;
                string password        = request.Password;
                string maintenanceText = null;

                if (File.Exists("./maintenance.txt"))
                {
                    string[] lines = File.ReadAllLines("./maintenance.txt");

                    maintenanceText = String.Empty;

                    for (int i = 0; i < lines.Length; i++)
                    {
                        if (i > 0)
                        {
                            maintenanceText += "\n";
                        }

                        maintenanceText += lines[i];
                    }
                }

                Server.Instance.Scheduler.RunTaskAsync(

                    () =>
                {
                    ClientLoginResponsePacket response = new ClientLoginResponsePacket();
                    AccountInfo accountInfo            = null;

                    MySqlHandle mySqlHandle = Server.Instance.DatabaseManager.GetMySqlHandle();

                    try
                    {
                        mySqlHandle.Open();

                        accountInfo = mySqlHandle.AccountsGetAccountInfo(username);

                        if (accountInfo != null)
                        {
                            Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, accountInfo.PasswordSalt, accountInfo.PasswordIterations, HashAlgorithmName.SHA256);

                            byte[] passwordHash = pbkdf2.GetBytes(32);

                            if (passwordHash.SequenceEqual(accountInfo.PasswordHash))
                            {
                                response.LoginResult = LoginResult.Allow;
                            }
                            else
                            {
                                response.LoginResult = LoginResult.DenyInvalidCredentials;
                            }
                        }
                        else
                        {
                            response.LoginResult = LoginResult.DenyInvalidCredentials;
                        }

                        mySqlHandle.Close();
                    }
                    catch (Exception exc)
                    {
                        Server.Instance.LogDatabaseError(exc);
                    }

                    mySqlHandle.Free();

                    if (maintenanceText != null)
                    {
                        response.LoginResult = LoginResult.DenyCustomError;

                        response.CustomErrorMessage = maintenanceText;
                    }

                    if (response.LoginResult == LoginResult.Allow)
                    {
                        Session session = Server.Instance.SessionManager.CreateSession(e.SourceAddress, e.SourcePort, accountInfo);

                        response.SessionSecret = session.Secret;
                    }
                    else
                    {
                        response.SessionSecret = "AUTHENTICATION FAILED";
                    }

                    response.CharacterInstanceIp   = e.DestinationAddress;
                    response.ChatInstanceIp        = e.DestinationAddress;
                    response.CharacterInstancePort = Server.Instance.WorldPort;
                    response.ChatInstancePort      = Server.Instance.WorldPort;

                    Server.Instance.SendGamePacket(response, ClientPacketId.MSG_CLIENT_LOGIN_RESPONSE, e.SourceAddress, e.SourcePort);

                    Server.Instance.Logger.Log("A client requested to authenticate. address=" + e.SourceAddress + " port=" + e.SourcePort + " username="******" result=" + response.LoginResult);
                }

                    );
            }
        }
Beispiel #39
0
        public void AddHistoricalOrder(Order order, AccountInfo info, Status status, bool canRetry = false)
        {
            using (var aConnection = new SqlConnection(_connectionString))
            {
                ////simple insert
                var cmd = new SqlCommand("INSERT INTO [dbo].[Orders] ([OrderId],[BrokerID],[SignalID],[BrokerName],[DataFeed],[UserName],[AccountId],[Symbol],[Price],[Quantity],[ExecutedQuantity],[Status],"
                                         + "[Type],[TIF],[Date],[PlacedDate],[FilledDate],[OpeningQuantity],[ClosingQuantity],[Origin]) "
                                         + "VALUES (@orderId, @brokerId, @signalId, @brokerName, @dataFeed, @userName, @accountId, @symbol, @price, @qty, @execQty, @status, "
                                         + "@type, @tif, @openDate, @placedDate, @filledDate, @openingQty, @closingQty, @origin);", aConnection);

                //upsert via MERGE
                //var cmd1 = new SqlCommand("MERGE [dbo].[Orders] AS Target "
                //                         + "USING (VALUES(@orderId, @brokerId, @signalId, @brokerName, @accountId, @symbol, @datafeed, @price, @qty, @execQty, @status, "
                //                         + "@type, @tif, @openDate, @placedDate, @filledDate, @openingQty, @closingQty, @origin)) "
                //                         + "AS item([OrderId],[BrokerID],[SignalID],[BrokerName],[AccountId],[Symbol],[DataFeed],[Price],[Quantity],[ExecutedQuantity],"
                //                         + "[Status],[Type],[TIF],[Date],[PlacedDate],[FilledDate],[OpeningQuantity],[ClosingQuantity],[Origin]) "
                //                         + "ON (Target.OrderId = item.OrderId AND Target.BrokerID = item.BrokerID AND Target.SignalID = item.SignalID AND Target.AccountId = item.AccountId) "
                //                         + "WHEN MATCHED THEN "
                //                         + "UPDATE SET Target.Price = item.Price, Target.Quantity = item.Quantity, Target.ExecutedQuantity = item.ExecutedQuantity, "
                //                         + "Target.Status = item.Status, Target.[Type] = item.[Type], Target.TIF = item.TIF, Target.[Date] = item.[Date], "
                //                         + "Target.[PlacedDate] = item.[PlacedDate], Target.[FilledDate] = item.[FilledDate], "
                //                         + "Target.OpeningQuantity = item.OpeningQuantity, Target.ClosingQuantity = item.ClosingQuantity,Target.Origin = item.Origin "
                //                         + "WHEN NOT MATCHED BY TARGET THEN "
                //                         + "INSERT ([OrderId],[BrokerID],[SignalID],[BrokerName],[AccountId],[Symbol],[DataFeed],[Price],[Quantity],[ExecutedQuantity],[Status],"
                //                         + "[Type],[TIF],[Date],[PlacedDate],[FilledDate],[OpeningQuantity],[ClosingQuantity],[Origin]) "
                //                         + "VALUES (item.OrderId,item.BrokerID,item.SignalID,item.BrokerName,item.AccountId,item.Symbol,item.DataFeed,item.Price,"
                //                         + "item.Quantity,item.ExecutedQuantity,item.Status,item.[Type],item.TIF,item.[Date],item.[PlacedDate],item.[FilledDate],"
                //                         + "item.OpeningQuantity,item.ClosingQuantity,item.Origin);", aConnection);

                cmd.Parameters.AddWithValue("orderId", order.UserID);
                cmd.Parameters.AddWithValue("brokerId", order.BrokerID);
                cmd.Parameters.AddWithValue("brokerName", info.BrokerName);
                cmd.Parameters.AddWithValue("datafeed", order.DataFeedName);
                cmd.Parameters.AddWithValue("userName", info.UserName);
                cmd.Parameters.AddWithValue("accountId", info.ID);
                cmd.Parameters.AddWithValue("symbol", order.Symbol);
                cmd.Parameters.AddWithValue("qty", order.OrderSide == Side.Buy ? order.Quantity : -order.Quantity);
                cmd.Parameters.AddWithValue("openingQty", order.OpeningQty);
                cmd.Parameters.AddWithValue("closingQty", order.ClosingQty);
                cmd.Parameters.AddWithValue("status", DBConverters.OrderStatusToString(status));
                cmd.Parameters.AddWithValue("type", DBConverters.OrderTypeToString(order.OrderType));
                cmd.Parameters.AddWithValue("tif", DBConverters.TifToString(order.TimeInForce));
                cmd.Parameters.AddWithValue("openDate", order.OpenDate);
                cmd.Parameters.AddWithValue("placedDate", order.PlacedDate);
                cmd.Parameters.AddWithValue("filledDate", order.FilledDate);

                if (order.SignalID == null)
                {
                    cmd.Parameters.AddWithValue("signalId", DBNull.Value);
                }
                else
                {
                    cmd.Parameters.AddWithValue("signalId", order.SignalID);
                }

                if (string.IsNullOrWhiteSpace(order.Origin))
                {
                    cmd.Parameters.AddWithValue("origin", DBNull.Value);
                }
                else
                {
                    cmd.Parameters.AddWithValue("origin", order.Origin);
                }

                if (status == Status.Filled)
                {
                    cmd.Parameters.AddWithValue("execQty",
                                                order.OrderSide == Side.Buy ? order.FilledQuantity : -order.FilledQuantity);
                    cmd.Parameters.AddWithValue("price", order.AvgFillPrice);
                }
                else if (status == Status.Cancelled)
                {
                    cmd.Parameters.AddWithValue("execQty",
                                                order.OrderSide == Side.Buy ? order.CancelledQuantity : -order.CancelledQuantity);
                    cmd.Parameters.AddWithValue("price", order.Price);
                }

                SqlTransaction transaction = null;

                try
                {
                    aConnection.Open();
                    transaction     = aConnection.BeginTransaction();
                    cmd.Transaction = transaction;
                    cmd.ExecuteNonQuery();
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    if (canRetry && e is SqlException)
                    {
                        var code = ((SqlException)e).Number;
                        if (code == 1205 || code == -2)  //deadlock or timeout
                        {
                            Logger.Error($"Failed to add {order.Symbol} order to DB (will retry): {e.Message}");
                            AddHistoricalOrder(order, info, status);
                            return;
                        }
                    }

                    Logger.Error($"Failed to add {order.Symbol} order to DB", e);

                    transaction?.Rollback();
                }
            }
        }
Beispiel #40
0
 /// <summary>
 /// Process inbound data
 /// </summary>
 /// <param name="data">Data to process</param>
 protected void processInboundData(byte[] data)
 {
     try
     {
         List <byte> foo = new List <byte>();
         if (this._incompleteBytes.Count > 0)
         {
             foreach (IncompleteMessageException e in this._incompleteBytes)
             {
                 foo.AddRange(e.getInput());
             }
             this._incompleteBytes.Clear();
         }
         if (data != null)
         {
             foo.AddRange(data);
         }
         ProtocolTreeNode node = this.reader.nextTree(foo.ToArray());
         while (node != null)
         {
             //this.WhatsParser.ParseProtocolNode(node);
             if (node.tag == "iq" &&
                 node.GetAttribute("type") == "error")
             {
                 this.AddMessage(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "challenge"))
             {
                 this.processChallenge(node);
             }
             else if (ProtocolTreeNode.TagEquals(node, "success"))
             {
                 this.loginStatus = CONNECTION_STATUS.LOGGEDIN;
                 this.accountinfo = new AccountInfo(node.GetAttribute("status"),
                                                    node.GetAttribute("kind"),
                                                    node.GetAttribute("creation"),
                                                    node.GetAttribute("expiration"));
             }
             else if (ProtocolTreeNode.TagEquals(node, "failure"))
             {
                 this.loginStatus = CONNECTION_STATUS.UNAUTHORIZED;
             }
             if (ProtocolTreeNode.TagEquals(node, "message"))
             {
                 this.AddMessage(node);
                 if (node.GetChild("request") != null)
                 {
                     this.sendMessageReceived(node);
                 }
                 else if (node.GetChild("received") != null)
                 {
                     this.sendMessageReceived(node, "ack");
                 }
             }
             if (ProtocolTreeNode.TagEquals(node, "stream:error"))
             {
                 Console.Write(node.NodeString());
             }
             if (ProtocolTreeNode.TagEquals(node, "iq") &&
                 node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase) &&
                 ProtocolTreeNode.TagEquals(node.children.First(), "query")
                 )
             {
                 //last seen
                 this.AddMessage(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "iq") &&
                 node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase) &&
                 (ProtocolTreeNode.TagEquals(node.children.First(), "media") || ProtocolTreeNode.TagEquals(node.children.First(), "duplicate"))
                 )
             {
                 //media upload
                 this.uploadResponse = node;
             }
             if (ProtocolTreeNode.TagEquals(node, "iq") &&
                 node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase) &&
                 ProtocolTreeNode.TagEquals(node.children.First(), "picture")
                 )
             {
                 //profile picture
                 this.AddMessage(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "iq") &&
                 node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase) &&
                 ProtocolTreeNode.TagEquals(node.children.First(), "ping"))
             {
                 this.Pong(node.GetAttribute("id"));
             }
             if (ProtocolTreeNode.TagEquals(node, "stream:error"))
             {
                 var textNode = node.GetChild("text");
                 if (textNode != null)
                 {
                     string content = WhatsApp.SYSEncoding.GetString(textNode.GetData());
                     Console.WriteLine("Error : " + content);
                     if (content.Equals("Replaced by new connection", StringComparison.OrdinalIgnoreCase))
                     {
                         this.Disconnect();
                         this.Connect();
                         this.Login();
                     }
                 }
             }
             if (ProtocolTreeNode.TagEquals(node, "presence"))
             {
                 //presence node
                 this.AddMessage(node);
             }
             node = this.reader.nextTree();
         }
     }
     catch (IncompleteMessageException ex)
     {
         this._incompleteBytes.Add(ex);
     }
 }
Beispiel #41
0
        public ActionResult Edit(int accountId)
        {
            AccountInfo info = this.accountService.GetAccount(accountId);

            return(this.View(info));
        }
Beispiel #42
0
 /// <summary>
 /// Get the <see cref="AccountActivity"/> for a specific <see cref="AccountInfo"/>
 /// </summary>
 public static AccountActivity GetLoginInfo <T>(this T client, AccountInfo account) where T : Dragon6Client
 => GetLoginInfo(client, new[] { account }).First();
Beispiel #43
0
 public UnderControlEventArgs(AccountInfo info, bool added)
 {
     this.AccountInfo = info;
     this.Added       = added;
 }
Beispiel #44
0
 // Start is called before the first frame update
 void Start()
 {
     account = GameManager.Instance.GetComponent <YourAccount>().account;
 }
Beispiel #45
0
        public static void FavTweetSink(IEnumerable <AccountInfo> infos, TweetViewModel status)
        {
            var ts = status.Status as TwitterStatus;

            if (ts == null)
            {
                NotifyStorage.Notify("DirectMessageはFavできません。");
                return;
            }
            if (ts.RetweetedOriginal != null)
            {
                status = TweetStorage.Get(ts.RetweetedOriginal.Id, true);
            }
            if (status == null)
            {
                NotifyStorage.Notify("Fav 対象ステータスが見つかりません。");
                return;
            }
            bool success = true;

            Parallel.ForEach(infos,
                             (d) =>
            {
                var ud = d.UserViewModel;
                // ふぁぼり状態更新
                if (ud != null)
                {
                    status.RegisterFavored(ud);
                }
                try
                {
                    favoriteInjection.Execute(new Tuple <AccountInfo, TweetViewModel>(d, status));
                }
                catch (Exception ex)
                {
                    success = false;
                    if (ud != null)
                    {
                        status.RemoveFavored(ud);
                    }
                    if (ex is FavoriteSuspendedException && Setting.Instance.InputExperienceProperty.EnableFavoriteFallback)
                    {
                        // ふぁぼ規制 -> フォールバック
                        AccountInfo fallback = null;
                        if (!String.IsNullOrEmpty(d.AccountProperty.FallbackAccount) &&
                            (fallback = AccountStorage.Get(d.AccountProperty.FallbackAccount)) != null &&
                            !status.FavoredUsers.Contains(fallback.UserViewModel))
                        {
                            NotifyStorage.Notify("Fav fallbackします: @" + d.ScreenName + " >> @");
                            FavTweetSink(new[] { fallback }, status);
                        }
                    }
                    else
                    {
                        NotifyStorage.Notify("Favに失敗しました: @" + d.ScreenName);
                        if (!(ex is ApplicationException))
                        {
                            ExceptionStorage.Register(ex, ExceptionCategory.TwitterError,
                                                      "Fav操作時にエラーが発生しました");
                        }
                    }
                }
            });
            if (success)
            {
                NotifyStorage.Notify("Favしました: @" + status.Status.User.ScreenName + ": " + status.Status.Text);
            }
        }
Beispiel #46
0
    /// <summary>
    /// Save data.
    /// </summary>
    protected void Save()
    {
        if (IsValid())
        {
            bool redirect = false;

            // Create new account
            if (ai == null)
            {
                ai           = new AccountInfo();
                EditedObject = ai;
                redirect     = true;
            }

            // Set values
            ai.AccountName               = txtName.Text.Trim();
            ai.AccountSubsidiaryOfID     = parentAccount.AccountID;
            ai.AccountOwnerUserID        = ValidationHelper.GetInteger(accountOwner.Value, 0);
            ai.AccountStatusID           = accountStatus.AccountStatusID;
            ai.AccountAddress1           = txtAddress1.Text.Trim();
            ai.AccountAddress2           = txtAddress2.Text.Trim();
            ai.AccountCity               = txtCity.Text.Trim();
            ai.AccountZIP                = txtZip.Text.Trim();
            ai.AccountCountryID          = countrySelector.CountryID;
            ai.AccountStateID            = countrySelector.StateID;
            ai.AccountPhone              = txtPhone.Text.Trim();
            ai.AccountFax                = txtFax.Text.Trim();
            ai.AccountEmail              = ValidationHelper.GetString(emailInput.Value, null);
            ai.AccountWebSite            = txtURL.Text.Trim();
            ai.AccountPrimaryContactID   = primaryContact.ContactID;
            ai.AccountSecondaryContactID = secondaryContact.ContactID;
            ai.AccountNotes              = htmlNotes.Value;
            ai.AccountSiteID             = SiteID;

            try
            {
                // Save account changes
                AccountInfoProvider.SetAccountInfo(ai);
                if (AssignContacts())
                {
                    ShowChangesSaved();
                }

                RaiseOnSaved();

                // Redirect page after newly created item is saved
                if (redirect)
                {
                    string url = "Frameset.aspx?accountId=" + ai.AccountID + "&saved=1";
                    url = URLHelper.AddParameterToUrl(url, "siteid", SiteID.ToString());
                    if (ContactHelper.IsSiteManager)
                    {
                        url = URLHelper.AddParameterToUrl(url, "issitemanager", "1");
                    }

                    URLHelper.Redirect(url);
                }
            }
            catch (Exception e)
            {
                ShowError(GetString("general.saveerror"), e.Message, null);
            }
        }
    }
Beispiel #47
0
 internal static void UpdateDirectMessage(AccountInfo accountInfo, string target, string body)
 {
     dmInjection.Execute(new Tuple <AccountInfo, string, string>(accountInfo, target, body));
 }
 public AccountInfoTests()
 {
     _fakeAccountService = A.Fake <IAccountService>();
     _accountId          = 2;
     _sut = new AccountInfo(_accountId, _fakeAccountService);
 }
Beispiel #49
0
 public LoginCommand(AccountInfo info)
 {
     Info = info;
 }
Beispiel #50
0
 public Account(LauncherConfig launcherConfig)
 {
     this.launcherConfig = launcherConfig;
     SelectedAccount     = null;
 }
Beispiel #51
0
        //LogBll logBll = new LogBll();
        //GlobalConfigBll configBll = new GlobalConfigBll();

        /// <summary>
        /// 用户id查实体
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public AccountInfo GetAccByUserId(int userId)
        {
            AccountInfo acc = _accDal.GetAccByUserId(userId);

            return(acc);
        }
 public RegisterForm(AccountInfo arg, WindowsModel vm)
 {
     InitializeComponent();
     _account = arg;
     WindowsInit(arg, vm);
 }
Beispiel #53
0
        ///// <summary>
        ///// 用户账户地址查实体
        ///// </summary>
        ///// <param name="userId"></param>
        ///// <returns></returns>
        //public AccountInfo GetAccByAccName(string accName)
        //{
        //    AccountInfo acc = _accDal.GetAccByAccName(accName);
        //    return acc;
        //}


        /// <summary>
        /// 修改账户信息
        /// </summary>
        /// <param name="accInfo"></param>
        /// <returns></returns>

        public bool UpdateAccInfo(AccountInfo accInfo)
        {
            bool isTrue = _accDal.UpdateAccInfo(accInfo);

            return(isTrue);
        }
 public AmazonOrderMatcher(AccountInfo accountInfo)
     : base(accountInfo, @"shipping charge", @"tax charged", @"total promotions")
 {
 }
Beispiel #55
0
        public IEnumerable <Order> GetOrderHistory(AccountInfo info, int count, int skip)
        {
            if (skip < 0 || count < 1)
            {
                return(new List <Order>(0));
            }

            var result = new List <Order>();

            using (var aConnection = new SqlConnection(_connectionString))
            {
                //select N latest records of each symbol
                var cmd = new SqlCommand("WITH TOPRECORDS AS ( "
                                         + "SELECT s.[Symbol], h.[Quantity], h.[ExecutedQuantity], h.[Status], h.[OrderId], h.[Price], "
                                         + "h.[Type], h.[TIF], h.[Date], h.[BrokerID], h.[OpeningQuantity], h.[ClosingQuantity], h.[Origin], ROW_NUMBER() "
                                         + "OVER(PARTITION BY h.[Symbol], h.[DataFeed] ORDER BY [Date] DESC) AS RowNumber FROM [Orders] AS h "
                                         + "INNER JOIN[dbo].[Securities] AS s ON s.Symbol = h.Symbol AND s.DataFeed = h.DataFeed "
                                         + "WHERE h.[UserName] = @userName AND h.[AccountId] = @account AND h.[BrokerName] = @broker) "
                                         + "SELECT * FROM TOPRECORDS WHERE RowNumber > @start AND RowNumber <= @end", aConnection);
                cmd.Parameters.AddWithValue("start", skip);
                cmd.Parameters.AddWithValue("end", skip + count);
                cmd.Parameters.AddWithValue("userName", info.UserName);
                cmd.Parameters.AddWithValue("account", info.ID);
                cmd.Parameters.AddWithValue("broker", info.BrokerName);

                SqlTransaction transaction = null;
                try
                {
                    aConnection.Open();
                    transaction     = aConnection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted, "Orders Select");
                    cmd.Transaction = transaction;

                    using (var reader = cmd.ExecuteReader())
                    {
                        if (!reader.HasRows)
                        {
                            return(result);
                        }

                        while (reader.Read())
                        {
                            try
                            {
                                var qty     = (decimal)reader["Quantity"];
                                var execQty = (decimal)reader["ExecutedQuantity"];
                                var status  = DBConverters.ParseOrderStatus((string)reader["Status"]);
                                var order   = new Order((string)reader["OrderId"], (string)reader["Symbol"])
                                {
                                    BrokerID          = (string)reader["BrokerID"],
                                    AvgFillPrice      = status == Status.Filled ? (decimal)reader["Price"] : 0,
                                    Price             = status == Status.Cancelled ? (decimal)reader["Price"] : 0,
                                    OrderSide         = qty > 0 ? Side.Buy : Side.Sell,
                                    OrderType         = DBConverters.ParseOrderType((string)reader["Type"]),
                                    BrokerName        = info.BrokerName,
                                    AccountId         = info.ID,
                                    TimeInForce       = DBConverters.ParseTif((string)reader["TIF"]),
                                    OpenDate          = (DateTime)reader["Date"],
                                    CancelledQuantity = status == Status.Cancelled ? Math.Abs(execQty) : 0,
                                    FilledQuantity    = status == Status.Filled ? Math.Abs(execQty) : 0,
                                    OpeningQty        = status == Status.Filled ? (decimal)reader["OpeningQuantity"] : 0,
                                    ClosingQty        = status == Status.Filled ? (decimal)reader["ClosingQuantity"] : 0,
                                    Origin            = reader["Origin"] as string
                                };

                                if (status == Status.Cancelled)
                                {
                                    order.CancelledQuantity = Math.Abs(qty);
                                }
                                else
                                {
                                    order.FilledQuantity = Math.Abs(qty);
                                }

                                result.Add(order);
                            }
                            catch (Exception ex)
                            {
                                Logger.Error("Failed to parse historical order", ex);
                            }
                        }
                    }

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    Logger.Error("Failed to load order history", e);
                    transaction?.Rollback();
                    return(result);
                }
            }
            return(result);
        }
Beispiel #56
0
 public void SetAccountInfo(AccountInfo accountInfo)
 {
     _memoryCache.Set(ACCOUNT_INFO_KEY, accountInfo, TimeSpan.FromMinutes(CACHE_TIME_IN_MINUTES));
 }
        /// <summary>
        /// Helper, get account based on name from orderInfo.
        /// </summary>
        MbtAccount GetAccountByInfo(AccountInfo info)
        {
            foreach (MbtAccount account in _orderClient.Accounts)
            {
                if (account.Account == info.Id && account.RoutingID == info.Name)
                {
                    return account;
                }
            }

            return null;
        }
Beispiel #58
0
 public void Init()
 {
     instance = new AccountInfo();
 }
 /// <summary>
 /// Sets the dialog parameters to the context.
 /// </summary>
 private void SetDialogParameters(DataSet mergedAccounts, AccountInfo parentAccount)
 {
     Hashtable parameters = new Hashtable();
     parameters["MergedAccounts"] = mergedAccounts;
     parameters["ParentAccount"] = parentAccount;
     WindowHelper.Add(Identifier.ToString(), parameters);
 }
Beispiel #60
0
        public FileResult ExportExcel(int status, string shopName)
        {
            AccountQuery accountQuery = new AccountQuery()
            {
                Status   = new AccountInfo.AccountStatus?((AccountInfo.AccountStatus)status),
                ShopName = shopName,
                PageSize = 2147483647,
                PageNo   = 1
            };
            PageModel <AccountInfo> accounts      = ServiceHelper.Create <IAccountService>().GetAccounts(accountQuery);
            IList <AccountModel>    accountModels = new List <AccountModel>();

            AccountInfo[] array = accounts.Models.ToArray();
            for (int i = 0; i < array.Length; i++)
            {
                AccountInfo  accountInfo  = array[i];
                AccountModel accountModel = new AccountModel()
                {
                    Id                      = accountInfo.Id,
                    ShopId                  = accountInfo.ShopId,
                    ShopName                = accountInfo.ShopName,
                    AccountDate             = accountInfo.AccountDate.ToString(),
                    StartDate               = accountInfo.StartDate,
                    EndDate                 = accountInfo.EndDate,
                    Status                  = (int)accountInfo.Status,
                    ProductActualPaidAmount = accountInfo.ProductActualPaidAmount,
                    FreightAmount           = accountInfo.FreightAmount,
                    CommissionAmount        = accountInfo.CommissionAmount,
                    RefundAmount            = accountInfo.RefundAmount,
                    RefundCommissionAmount  = accountInfo.RefundCommissionAmount,
                    AdvancePaymentAmount    = accountInfo.AdvancePaymentAmount,
                    PeriodSettlement        = accountInfo.PeriodSettlement,
                    Remark                  = accountInfo.Remark
                };
                string   str  = accountModel.StartDate.Date.ToString("yyyy-MM-dd");
                DateTime date = accountModel.EndDate.Date;
                accountModel.TimeSlot = string.Format("{0} 至 {1}", str, date.ToString("yyyy-MM-dd"));
                accountModels.Add(accountModel);
            }
            HSSFWorkbook hSSFWorkbook = new HSSFWorkbook();
            Sheet        sheet        = hSSFWorkbook.CreateSheet("Sheet1");
            Row          row          = sheet.CreateRow(0);

            row.CreateCell(0).SetCellValue("店铺名称");
            row.CreateCell(1).SetCellValue("时间段");
            row.CreateCell(2).SetCellValue("商品实付总额");
            row.CreateCell(3).SetCellValue("运费");
            row.CreateCell(4).SetCellValue("佣金");
            row.CreateCell(5).SetCellValue("退款金额");
            row.CreateCell(6).SetCellValue("退还佣金");
            row.CreateCell(7).SetCellValue("营销费用总额");
            row.CreateCell(8).SetCellValue("本期应结");
            row.CreateCell(9).SetCellValue("出账日期");
            for (int j = 0; j < accountModels.Count; j++)
            {
                Row row1 = sheet.CreateRow(j + 1);
                row1.CreateCell(0).SetCellValue(accountModels[j].ShopName);
                row1.CreateCell(1).SetCellValue(accountModels[j].TimeSlot);
                row1.CreateCell(2).SetCellValue(accountModels[j].ProductActualPaidAmount.ToString());
                row1.CreateCell(3).SetCellValue(accountModels[j].FreightAmount.ToString());
                row1.CreateCell(4).SetCellValue(accountModels[j].CommissionAmount.ToString());
                row1.CreateCell(5).SetCellValue(accountModels[j].RefundAmount.ToString());
                row1.CreateCell(6).SetCellValue(accountModels[j].RefundCommissionAmount.ToString());
                row1.CreateCell(7).SetCellValue(accountModels[j].AdvancePaymentAmount.ToString());
                row1.CreateCell(8).SetCellValue(accountModels[j].PeriodSettlement.ToString());
                row1.CreateCell(9).SetCellValue(accountModels[j].AccountDate.ToString());
            }
            MemoryStream memoryStream = new MemoryStream();

            hSSFWorkbook.Write(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return(File(memoryStream, "application/vnd.ms-excel", "结算管理.xls"));
        }