public void Login(AccountData account)
 {
     _pages.LoginPage.LoginButton.Click();
     _pages.LoginPage.EmailField.SendKeys(account.Username);
     _pages.LoginPage.PasswordField.SendKeys(account.Password);
     _pages.LoginPage.SubmitButton.Click();
 }
 internal AccountDataEntry(string account, AccountData values, AccountData[] positions, AccountData[] orders)
 {
     this.Account = account;
     this.Values = values;
     this.Positions = positions;
     this.Orders = orders;
 }
Exemple #3
0
        protected void LoadAccountInfo()
        {
            AccountData account = new AccountData("E3FB0351-32DC-4D4D-8902-181DD9666AB2");

            SqlDataReader rdr = account.GetAccountData();

            if (rdr.HasRows)
            {

                Response.Write("<div class='row'>");
                Response.Write("<div class='col-md-2 product-table-hdr'><p class='active'>Product Name</p></div>");
                Response.Write("<div class='col-md-2 product-table-hdr'><p>Start Date</p></div>");
                Response.Write("<div class='col-md-2 product-table-hdr'><p>End Date</p></div>");

                Response.Write("</div>");
                while (rdr.Read())
                {
                    Response.Write("<div class='row'>");
                    Response.Write("<div class='col-md-2 product-table-row'>" + rdr.GetValue(1) + "</div>");
                    Response.Write("<div class='col-md-2 product-table-row'>" + rdr.GetDateTime(2).ToString("d") + "</div>");
                    Response.Write("<div class='col-md-2 product-table-row'>" + rdr.GetDateTime(3).ToString("d") + "</div>");

                }
                Response.Write("</div>");
            }
            else
            {
                Console.WriteLine("No rows found.");
            }
            rdr.Close();
        }
Exemple #4
0
 public void PossitiveLoginTestWithFile(AccountData account)
 {
     //App.Auth.LoginPossitive(account);
     //тут вроде все легко и понятно
     //Assert.IsTrue(App.Auth.IsLogIn(), "Logged In");
     //принять ассерт, тоже не сложно
 }
 public PacketsSendModule(AccountData acc)
 {
     this.acc = acc;
     this.addPacketEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
     this.thread = new Thread((ThreadStart)ThreadFunc);
     this.thread.Start();
 }
 public void CreateNewPayment(AccountData account)
 {
     //pages.Office.Dopay.Click();
     //pages.Newpay.Recipient.Clear();
     //pages.Newpay.Recipient.SendKeys(account.recipient);
     //паджес.страница(обозванная).кнопка(обозванная).действие
 }
 string IAccountServices.Query()
 {
     AccountData data = new AccountData();
     List<Model.DataBase.AccountModel> list=data.DataList();
     list = list.Where(r => r.Zhlx != 1).ToList();
     return JsonConvert.SerializeObject(list);
 }
        public void CreateAccount(string user, AccountData data)
        {
            try
            {
                // VERIFY

                if (data == null || string.IsNullOrEmpty(data.email) || string.IsNullOrEmpty(data.password)) throw new BadRequestException();

                var invoker = _h.Authorize();

                // CREATE ACCOUNT

                data.user = user; // name must be username

                if (data.type == null) data.type = "Customer"; // Default to customer account
                if (data.type.Equals("Customer") && data.credits == null) data.credits = 0;

                var account = _c.Convert(data);
                ControlledAccount.persist(invoker, account);

                // SIGNAL SUCCESS

                _h.SetHeader("Location", "/accounts/"+user);
                _h.Success(201);
            }
            catch (BadRequestException) { _h.Failure(400); } // TODO: Should also be returned for too long usernames, instead of 413
            catch (AccountExceptions.BrokenInvariant) { _h.Failure(400); }
            catch (PermissionExceptions.PermissionDenied) { _h.Failure(403); }
            catch (PermissionExceptions.AccountBanned) { _h.Failure(403); }
            catch (AccountExceptions.UnknownAccType) { _h.Failure(400); }
            catch (AccountExceptions.UserAlreadyExists) { _h.Failure(409); }
            catch (AccountExceptions.TooLargeData) { _h.Failure(413); }
            catch (Exception) { _h.Failure(500); }
        }
        public AccountTypes.Account Convert(AccountData a)
        {
            if (a == null) return null;

            var dummy = Account.make("", "", "", "", ConvertToExtra(null));

            return Merge(dummy, a);
        }
		public void RestoreAccountData(AccountData accountData)
		{
			_accountData = accountData;
			if (LoginCompleted != null)
			{
				LoginCompleted(_accountData);
			}
		}
Exemple #11
0
 void PerformAccountClick(AccountData acc)
 {
     if (AccountClick != null)
     {
         clickEA.Account = acc;
         AccountClick(this, clickEA);
     }
 }
        public void SaveAccountData(AccountData accountData)
        {
            string jsonString = JsonConvert.SerializeObject(accountData, Newtonsoft.Json.Formatting.Indented);

            string myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string filePath = Path.Combine(myDocumentsPath, "accountData.json");
            File.WriteAllText(filePath, jsonString);
        }
        public static void Insert(AccountData data)
        {
            MysqlQuery query = new MysqlQuery(INSERT_QUERY);
            query.AddValue("GUID", data.Id, MySqlDbType.Int32);
            query.AddValue("USERNAME", data.Login.Length > 16 ? data.Login.Substring(0, 16) : data.Login, MySqlDbType.VarChar);
            query.AddValue("PASSWORD", data.Password.Length > 32 ? data.Password.Substring(0, 32) : data.Password, MySqlDbType.VarChar);

            MysqlDB.Query(query);
        }
        /// <summary>
        /// Create new instance connected to current reseller
        /// </summary>
        public PaymentMethodsProvider(IResellerDataProvider resellerDataProvider, PublicBillingApiProxy billingApi)
            : base(billingApi)
        {
            if (resellerDataProvider == null)
            {
                throw new ArgumentNullException("resellerDataProvider");
            }

            resellerData = resellerDataProvider.GetResellerAccountData();
        }
 public void Test(AccountData account)
 {
     ApplicationManager.LoginHelper.Login(account);
     Assert.IsTrue(ApplicationManager.LoginHelper.IsLoggedIn(), "The user is not logged in");
     ApplicationManager.UserProfileHelper.OpenUserProfile();
     Assert.IsTrue(ApplicationManager.UserProfileHelper.IsOnUserProfilePage(), "User profile page is not opened");
     ApplicationManager.UserProfileHelper.ChangeAddress();
     ApplicationManager.UserProfileHelper.ChangePhone();
     ApplicationManager.UserProfileHelper.GetListOfOperations();
 }
Exemple #16
0
		/// <summary>
		/// This is used to initialize *skeleton* data for accounts that do not already have data stored server side.
		/// We initialize with DateTime.MinValue to cause the client to update the server side data.
		/// </summary>
		/// <param name="accountId">GUID of the account that needs to be initialized</param>
		/// <returns>An AccountData reference</returns>
		public static AccountData InitializeNewAccount(long accountId)
		{
			var newData = new AccountData {AccountId = accountId};

			for (uint i = 7; i > 0; i--)
			{
				newData.TimeStamps[i] = 0;
			}
			
			return newData;
		}
        public void Lock()
        {
            Accounts = new AccountData();

            if (password != null)
            {
                password.Dispose();
                password = null;
            }

            pattern = null;
        }
    // Use this for initialization
    public ServerAccounts()
    {
        functionName = "Accounts";
        // Database tables name
        tableName = "account";
        functionTitle = "Account Management";
        loadButtonLabel = "Load Accounts";
        notLoadedText = "No Account loaded.";
        // Init
        dataRegister = new Dictionary<int, AccountData> ();

        editingDisplay = new AccountData ();
        originalDisplay = new AccountData ();
    }
 public void SetAccountData(AccountData[] accountData)
 {
     userNameMapping.Clear();
     IEnumerator e = accountData.GetEnumerator();
     while (e.MoveNext())
     {
         AccountData account = (AccountData)e.Current;
         userNameMapping.Add(account.id, account.name);
         if (account.name == cs.Username)
         {
             this.myAccountID = account.id;
         }
     }
     ListIssues();
 }
        /// <summary>
        /// Construct new instance with current reselller
        /// </summary>
        public LanguageProvider(IResourceProvider resourceProvider, IResellerDataProvider resellerDataProvider, PublicBillingApiProxy billingApi)
            : base(billingApi)
        {
            if (resourceProvider == null)
            {
                throw new ArgumentNullException("resourceProvider");
            }

            if (resellerDataProvider == null)
            {
                throw new ArgumentNullException("resellerDataProvider");
            }

            this.resourceProvider = resourceProvider;
            this.resellerData = resellerDataProvider.GetResellerAccountData();
        }
		public async Task<AccountData> LoginAsync(FacebookAccess facebookAccess)
		{
			Task<FacebookProfile> facebookProfileTask = _facebookFacade.GetUserProfile(facebookAccess.AccessToken);

			Task<BiketimerAccount> biketimerAccountTask = _biketimerIdentityFacade.GetBiketimerToken(facebookAccess.AccessToken)
															   .ContinueWith(DownloadBiketimerAccountAsync)
															   .Unwrap();

			FacebookProfile facebookProfile = await facebookProfileTask;
			BiketimerAccount biketimerAccount = await biketimerAccountTask;

			FacebookAccount facebookAccount = new FacebookAccount(facebookAccess, facebookProfile);
			AccountData _accountData = new AccountData(facebookAccount, biketimerAccount);

			return _accountData;
		}
 public static Dictionary<int, AccountData> LoadAll()
 {
     Dictionary<int, AccountData> accounts = new Dictionary<int, AccountData>();
     foreach (var a in MysqlDB.SelectAll(new MysqlQuery(SELECT_QUERY)))
     {
         AccountData data = new AccountData()
         {
             Id = Convert.ToInt32(a["guid"]),
             Login = Convert.ToString(a["username"]),
             Password = Convert.ToString(a["password"]),
             AccessLevel = Convert.ToInt32(a["access_level"])
         };
         GUIDGenerator.SetGUID(data.Id);
         accounts.Add(data.Id, data);
     }
     return accounts;
 }
		private async Task HandleLoginProcessAsync(FacebookAccess facebookAccess)
		{
			try
			{
				LoginProcessor loginProcessor = new LoginProcessor();
				_accountData = await loginProcessor.LoginAsync(facebookAccess);
				if (LoginCompleted != null)
				{
					LoginCompleted(_accountData);
				}
			}
			catch(Exception e)
			{
				if (LoginFailed != null)
				{
					LoginFailed();
				}
			}
		}
 public UserAccountEntity()
 {
     string accessToken;
     string refreshToken;
     try
     {
         accessToken = (string) AppSettings["accessToken"];
     }
     catch (KeyNotFoundException e)
     {
         accessToken = string.Empty;
     }
     try
     {
         refreshToken = (string) AppSettings["refreshToken"];
     }
     catch (KeyNotFoundException e)
     {
         refreshToken = string.Empty;
     }
     _data = new AccountData(accessToken, refreshToken, 3600);
     _entity = null;
     _isCalled = false;
 }
        private void CompleteAggregation(List <Index> indices, Index totalRow, AccountData accountData, double dividendsReceived)
        {
            try
            {
                accountData.CurrentEquity = accountData.StartOfDayEquity + accountData.TotalPandL;

                // CurrentLeverage has synthetic stock due to short puts - add OLAP then calculate leverage
                accountData.CurrentLeverage += accountData.CurrentOLAPMarketValue;
                accountData.CurrentLeverage /= accountData.CurrentEquity;

                // CurrentCash is currently set to the negative of the unavailable cash
                accountData.CurrentCash += (accountData.CurrentEquity - dividendsReceived) * (double)accountData.Leverage - accountData.CurrentMarketValue;

                // calculate PutsPctTarget - this used to be a fixed number. it is now calculated as below
                accountData.PutsPctTarget = (decimal)Math.Round(Math.Max(0, (accountData.CurrentMarketValue - accountData.CurrentEquity) / accountData.CurrentEquity), 3);

                totalRow.LastPrice = totalRow.PrevClose = 100;
                foreach (Index indexRow in indices)
                {
                    indexRow.TargetValue = (double)indexRow.Weight * DeltaDivisor(accountData);
                    if (indexRow.TargetValue > 0)
                    {
                        indexRow.CallDeltaPct     /= indexRow.TargetValue;
                        indexRow.PutDeltaPct      /= indexRow.TargetValue;
                        indexRow.TotalDeltaPct     = ((double)indexRow.Weight * accountData.CurrentOLAPMarketValue + indexRow.TotalDeltaPct) / indexRow.TargetValue;
                        indexRow.GammaPct          = indexRow.GammaPct / indexRow.TargetValue;
                        indexRow.FaceValuePutsPct /= indexRow.TargetValue;
                        indexRow.ShortPct         /= indexRow.TargetValue;
                        indexRow.TimePremium      /= indexRow.TargetValue;
                        indexRow.Caks             /= indexRow.TargetValue;

                        if (indexRow.LastPrice > 0)
                        {
                            indexRow.PutsToRebalance = (int)Math.Round(((double)accountData.PutsPctTarget - indexRow.FaceValuePutsPct) * indexRow.TargetValue / (100 * indexRow.LastPrice.Value), 0);
                        }
                    }
                    if (indexRow.PrevClose != 0)
                    {
                        totalRow.LastPrice += (double)indexRow.Weight * (indexRow.LastPrice / indexRow.PrevClose - 1) * totalRow.PrevClose;
                    }
                }

                double deltaDivisor = DeltaDivisor(accountData);
                if (deltaDivisor > 0)
                {
                    totalRow.CallDeltaPct     /= deltaDivisor;
                    totalRow.PutDeltaPct      /= deltaDivisor;
                    totalRow.TotalDeltaPct     = (accountData.CurrentOLAPMarketValue + totalRow.TotalDeltaPct) / deltaDivisor;
                    totalRow.GammaPct          = totalRow.GammaPct / deltaDivisor;
                    totalRow.FaceValuePutsPct /= deltaDivisor;
                    totalRow.ShortPct         /= deltaDivisor;
                    totalRow.TimePremium      /= deltaDivisor;
                    totalRow.Caks             /= deltaDivisor;
                    totalRow.ThetaAnnualized  /= deltaDivisor;
                    accountData.DeltaPctTraded = accountData.DollarDeltasTraded / deltaDivisor;
                }
            }
            catch (Exception ex)
            {
                ReportError("Error completing aggregation of account totals", ex);
            }
        }
Exemple #26
0
 public GameServerInformations GetServerInformations(AccountData account)
 {
     return(new GameServerInformations(Id, Type, (sbyte)Status, 0, true, ServerCharacterRecord.GetCharactersCount(Id, account.Id), account.CharacterSlots, 0));
 }
Exemple #27
0
    public override void    execute()
    {
        base.execute();

        this.resolve_collision();

        this.update_item_queries();

        // ---------------------------------------------------------------- //
        // ?ㅼ쓬 ?곹깭濡??꾪솚?좎? 泥댄겕?쒕떎.


        switch (this.step.do_transition())
        {
        // ?됱긽 ??
        case STEP.MOVE:
        {
            if (this.control.vital.getHitPoint() <= 0.0f)
            {
                this.step.set_next(STEP.BATAN_Q);
            }
        }
        break;

        // 洹쇱젒 怨듦꺽.
        case STEP.MELEE_ATTACK:
        {
            if (!this.melee_attack.isAttacking())
            {
                this.step.set_next(STEP.MOVE);
            }
        }
        break;

        // ?꾩씠???ъ슜.
        case STEP.USE_ITEM:
        {
            if (this.step_use_item.transition_check())
            {
                this.ice_timer = ICE_DIGEST_TIME;
            }
        }
        break;

        // ?€誘몄?瑜?諛쏆븘 ?좊씪媛€??以?
        case STEP.BLOW_OUT:
        {
            // ?쇱젙 嫄곕━瑜??섏븘媛€嫄곕굹 ?€?꾩븘?껋쑝濡?醫낅즺.

            float distance = MathUtility.calcDistanceXZ(this.control.getPosition(), this.step_blow_out.center);

            if (distance >= this.step_blow_out.radius || this.step.get_time() > BLOW_OUT_TIME)
            {
                this.control.cmdSetAcceptDamage(true);
                this.step.set_next(STEP.MOVE);
            }
        }
        break;

        // 泥대젰0.
        case STEP.BATAN_Q:
        {
            if (this.control.getMotion() == "")
            {
                this.control.cmdSetMotion("m007_out_lp", 1);
                this.step.set_next_delay(STEP.WAIT_RESTART, 1.0f);
            }
        }
        break;
        }

        // ---------------------------------------------------------------- //
        // ?곹깭 ?꾪솚 ??珥덇린??

        while (this.step.get_next() != STEP.NONE)
        {
            switch (this.step.do_initialize())
            {
            // ?됱긽 ??
            case STEP.MOVE:
            {
                this.GetComponent <Rigidbody>().WakeUp();
                this.move_target    = this.transform.position;
                this.heading_target = this.transform.TransformPoint(Vector3.forward);
            }
            break;

            // 洹쇱젒 怨듦꺽.
            case STEP.MELEE_ATTACK:
            {
                this.melee_attack.setTarget(this.melee_target);
                this.melee_attack.attack(true);
                this.melee_target = null;
            }
            break;

            // ?꾩씠???ъ슜.
            case STEP.USE_ITEM:
            {
                int slot_index = this.step_use_item.slot_index;

                if (this.ice_timer > 0.0f)
                {
                    // ?꾩씠?ㅻ? 吏㏃? 媛꾧꺽?쇰줈 ?곗냽 ?ъ슜????						// 癒몃━媛€ 吏€?덉??덊빐???뚮났?섏? ?딅뒗??

                    // ?꾩씠?쒖쓣 ??젣?쒕떎.
                    ItemWindow.get().clearItem(Item.SLOT_TYPE.MISC, slot_index);
                    this.item_slot.miscs[slot_index].initialize();

                    this.startJinJin();
                    this.step.set_next(STEP.MOVE);

                    SoundManager.getInstance().playSE(Sound.ID.DDG_SE_SYS06);
                }
                else
                {
                    this.item_slot.miscs[slot_index].is_using = true;

                    this.control.cmdSetAcceptDamage(false);

                    this.step_use_item.initialize();
                }
            }
            break;

            // ?€誘몄?瑜?諛쏆븘 ?좊씪媛€??以?
            case STEP.BLOW_OUT:
            {
                this.GetComponent <Rigidbody>().Sleep();
                this.control.cmdSetAcceptDamage(false);
            }
            break;

            // 泥대젰 0
            case STEP.BATAN_Q:
            {
                this.GetComponent <Rigidbody>().Sleep();
                this.control.cmdSetAcceptDamage(false);
                this.control.cmdSetMotion("m006_out", 1);
            }
            break;

            // 由ъ뒪?€???€湲?
            case STEP.WAIT_RESTART:
            {
                this.step_batan_q.tears_effect.destroy();
            }
            break;

            // ?몃? ?쒖뼱.
            case STEP.OUTER_CONTROL:
            {
                this.GetComponent <Rigidbody>().Sleep();
            }
            break;
            }
        }

        // ---------------------------------------------------------------- //
        // 媛??곹깭?먯꽌???ㅽ뻾 泥섎━.

        // 洹쇱젒 怨듦꺽.
        // ?쇰떒 false濡??대몢怨??대룞 ?낅젰???덉쓣 ?뚮쭔.
        // true濡??쒕떎.
        this.melee_attack.setHasInput(false);

        GameInput gi = GameInput.getInstance();

        switch (this.step.do_execution(Time.deltaTime))
        {
        // ?됱긽 ??
        case STEP.MOVE:
        {
            this.exec_step_move();

            // ?룔깾?껁깉.
            if (this.is_shot_enable)
            {
                this.bullet_shooter.execute(gi.shot.current);

                if (gi.shot.current)
                {
                    CharacterRoot.get().SendAttackData(PartyControl.get().getLocalPlayer().getAcountID(), 0);
                }
            }

            // 泥대젰 ?뚮났 吏곹썑(?덉씤蹂댁슦而щ윭 以???臾댁쟻.
            if (this.skin_color_control.isNowHealing())
            {
                this.control.cmdSetAcceptDamage(false);
            }
            else
            {
                this.control.cmdSetAcceptDamage(true);
            }
        }
        break;

        // ?꾩씠???ъ슜.
        case STEP.USE_ITEM:
        {
            this.step_use_item.execute();
        }
        break;

        // ?€誘몄?瑜?諛쏆븘 ?좊씪媛€??以?
        case STEP.BLOW_OUT:
        {
            this.exec_step_blow_out();
        }
        break;

        // 泥대젰0.
        case STEP.BATAN_Q:
        {
            if (this.step.is_acrossing_time(4.0f))
            {
                this.step_batan_q.tears_effect = EffectRoot.get().createTearsEffect(this.control.getPosition());

                this.step_batan_q.tears_effect.setParent(this.gameObject);
                this.step_batan_q.tears_effect.setLocalPosition(Vector3.up);
            }
        }
        break;
        }

        // ---------------------------------------------------------------- //

        if (gi.serif_text.trigger_on)
        {
            this.control.cmdQueryTalk(gi.serif_text.text, true);
        }

        // ---------------------------------------------------------------- //
        // 10 ?꾨젅?꾩뿉 ??踰?醫뚰몴瑜??ㅽ듃?뚰겕??蹂대궦??

        {
            do
            {
                if (this.step.get_current() == STEP.OUTER_CONTROL)
                {
                    break;
                }

                m_send_count = (m_send_count + 1) % SplineData.SEND_INTERVAL;

                if (m_send_count != 0 && m_culling.Count < PLOT_NUM)
                {
                    break;
                }

                // ?듭떊??醫뚰몴 ?≪떊.
                Vector3        target = this.control.getPosition();
                CharacterCoord coord  = new CharacterCoord(target.x, target.z);

                Vector3 diff = m_prev - target;
                if (diff.sqrMagnitude > 0.0001f)
                {
                    m_culling.Add(coord);

                    AccountData account_data = AccountManager.get().getAccountData(GlobalParam.getInstance().global_account_id);

                    CharacterRoot.get().SendCharacterCoord(account_data.avator_id, m_plotIndex, m_culling);
                    ++m_plotIndex;

                    if (m_culling.Count >= PLOT_NUM)
                    {
                        m_culling.RemoveAt(0);
                    }

                    m_prev = target;
                }
            } while(false);
        }
    }
        protected void PasswordSet_Click(object sender, EventArgs e)
        {
            AccountData.SetPassword(Session["UserId"].ToString(), password.Text);

            Response.Redirect("../BoardFinancialTransactions.aspx");
        }
Exemple #29
0
        public static void BusinessRunAccountForBuy(string accountId, string coin, AccountData account, decimal nowOpen, List <FlexPoint> flexPointList)
        {
            var usdtBalance = GetBlance(accountId, coin);

            var noSellCount = new CoinDao().GetNoSellRecordCount(account.id, coin);
            // 平均推荐购买金额
            var avgBuyAmount = GetAvgBuyAmount(usdtBalance.balance, noSellCount);

            Console.WriteLine($"杠杆------->{coin.PadLeft(7, ' ')}   推荐额度:{decimal.Round(avgBuyAmount, 6).ToString().PadLeft(10)}     未售出数量 {noSellCount}");
            if (!flexPointList[0].isHigh && avgBuyAmount >= 1)
            {
                AnaylyzeData anaylyzeData = new CoinAnalyze().GetAnaylyzeData(coin, "usdt");
                // 最后一次是高位,
                // 一定要小于5天内最高位的5%
                // 不追高????
                if (noSellCount <= 0 && CheckCanBuy(nowOpen, flexPointList[0].open) && anaylyzeData.NowPrice * (decimal)1.05 < anaylyzeData.FiveHighestPrice)
                {
                    // 可以考虑
                    decimal buyQuantity = avgBuyAmount / nowOpen;
                    buyQuantity = decimal.Round(buyQuantity, GetBuyQuantityPrecisionNumber(coin));
                    decimal       orderPrice = decimal.Round(nowOpen * (decimal)1.008, getPrecisionNumber(coin));
                    ResponseOrder order      = new AccountOrder().NewOrderBuy(accountId, buyQuantity, orderPrice, null, coin, "usdt");
                    if (order.status != "error")
                    {
                        new CoinDao().CreateTradeRecord(new TradeRecord()
                        {
                            Coin             = coin,
                            UserName         = AccountConfig.userName,
                            BuyTotalQuantity = buyQuantity,
                            BuyOrderPrice    = orderPrice,
                            BuyDate          = DateTime.Now,
                            HasSell          = false,
                            BuyOrderResult   = JsonConvert.SerializeObject(order),
                            BuyAnalyze       = JsonConvert.SerializeObject(flexPointList),
                            AccountId        = accountId,
                            BuySuccess       = false,
                            BuyTradePrice    = 0,
                            BuyOrderId       = order.data,
                            BuyOrderQuery    = "",
                            SellAnalyze      = "",
                            SellOrderId      = "",
                            SellOrderQuery   = "",
                            SellOrderResult  = ""
                        });
                        // 下单成功马上去查一次
                        QueryDetailAndUpdate(order.data);
                    }
                    logger.Error($"下单数据 coin:{coin} accountId:{accountId}  购买数量{buyQuantity} nowOpen{nowOpen},orderPrice:{orderPrice}");
                    logger.Error($"下单拐点 {JsonConvert.SerializeObject(flexPointList)}");
                    logger.Error($"下单结果 {JsonConvert.SerializeObject(order)}");
                }

                if (noSellCount > 0)
                {
                    // 获取最小的那个, 如果有,
                    decimal  minBuyPrice = 9999;
                    DateTime nearBuyDate = DateTime.MinValue;
                    var      noSellList  = new CoinDao().ListNoSellRecord(accountId, coin);
                    if (noSellList.Count == 0)
                    {
                        return;
                    }
                    foreach (var item in noSellList)
                    {
                        if (item.BuyOrderPrice < minBuyPrice)
                        {
                            minBuyPrice = item.BuyOrderPrice;
                        }
                        if (item.BuyDate > nearBuyDate)
                        {
                            nearBuyDate = item.BuyDate;
                        }
                    }

                    // 再少于1%, 并且最近购买时间要至少相差30分钟   控制下单的次数
                    decimal pecent = noSellCount >= 15 ? (decimal)1.05 : (decimal)1.05;
                    if (nearBuyDate < DateTime.Now.AddMinutes(-60 * 4) || nowOpen * pecent < minBuyPrice)
                    {
                        decimal buyQuantity = avgBuyAmount / nowOpen;
                        buyQuantity = decimal.Round(buyQuantity, GetBuyQuantityPrecisionNumber(coin));
                        decimal       buyPrice = decimal.Round(nowOpen * (decimal)1.005, getPrecisionNumber(coin));
                        ResponseOrder order    = new AccountOrder().NewOrderBuy(accountId, buyQuantity, buyPrice, null, coin, "usdt");
                        if (order.status != "error")
                        {
                            new CoinDao().CreateTradeRecord(new TradeRecord()
                            {
                                Coin             = coin,
                                UserName         = AccountConfig.userName,
                                BuyTotalQuantity = buyQuantity,
                                BuyOrderPrice    = buyPrice,
                                BuyDate          = DateTime.Now,
                                HasSell          = false,
                                BuyOrderResult   = JsonConvert.SerializeObject(order),
                                BuyAnalyze       = JsonConvert.SerializeObject(flexPointList),
                                AccountId        = accountId,
                                BuySuccess       = false,
                                BuyTradePrice    = 0,
                                BuyOrderId       = order.data,
                                BuyOrderQuery    = "",
                                SellAnalyze      = "",
                                SellOrderId      = "",
                                SellOrderQuery   = "",
                                SellOrderResult  = ""
                            });
                            // 下单成功马上去查一次
                            QueryDetailAndUpdate(order.data);
                        }
                        logger.Error($"下单数据 coin:{coin} accountId:{accountId}  购买数量:{buyQuantity} buyPrice:{buyPrice} nowOpen:{nowOpen},minBuyPrice:{minBuyPrice}");
                        logger.Error($"下单拐点{JsonConvert.SerializeObject(flexPointList)}");
                        logger.Error($"下单结果{JsonConvert.SerializeObject(order)}");
                    }
                }
            }
        }
        private Portfolio BuildPortfolio(AccountPortfolio positionMonitorPortfolio, bool bPositionsForAllAccounts)
        {
            try
            {
                List <Index> indices = new List <Index>();
                BuildIndexList(positionMonitorPortfolio.Indices, indices);

                Index totalRow = new Index();
                totalRow.Symbol = "Total";

                Index benchmark = BuildBenchmark(positionMonitorPortfolio.Benchmark);

                int unsubscribedSymbols = 0;

                AccountData accountData = BuildAccountData(positionMonitorPortfolio.Data);
                if (accountData != null)
                {
                    List <Position> positions = BuildPositions(positionMonitorPortfolio.AccountName, positionMonitorPortfolio.Portfolio, indices, totalRow, accountData, bPositionsForAllAccounts, ref unsubscribedSymbols);
                    CompleteAggregation(indices, totalRow, accountData, positionMonitorPortfolio.DividendsReceived);

                    if (!positionMonitorPortfolio.Data.TradingComplete)
                    {
                        CalculateTradingGoals(indices, totalRow, accountData);
                    }

                    indices.Add(totalRow);

                    // see if quotefeed has stopped
                    DateTime timeStamp = DateTime.Now;
                    TimeSpan?quoteServiceStoppedTime = positionMonitorPortfolio.QuoteServiceStoppedTime;
                    if (!quoteServiceStoppedTime.HasValue)
                    {
                        if (positionMonitorPortfolio.LastQuoteTime.HasValue)
                        {
                            if (timeStamp.TimeOfDay.Subtract(positionMonitorPortfolio.LastQuoteTime.Value) > s_quoteDelayThreshold)
                            {
                                quoteServiceStoppedTime = positionMonitorPortfolio.LastQuoteTime;
                            }
                        }
                    }

                    return(new Portfolio()
                    {
                        AccountName = positionMonitorPortfolio.AccountName,
                        SnapshotType = SentoniServiceLib.SnapshotType.Current,
                        TimeStamp = timeStamp,
                        QuoteServiceHost = m_positionMonitor.QuoteServerHost,
                        QuoteServiceStoppedTime = quoteServiceStoppedTime,
                        UnsubscribedSymbols = unsubscribedSymbols,
                        AccountData = accountData,
                        Positions = positions.ToArray(),
                        Indices = indices.ToArray(),
                        Benchmark = benchmark,
                        Snapshots = BuildSnapshots(positionMonitorPortfolio)
                    });
                }
            }
            catch (Exception ex)
            {
                ReportError("Error building portfolio", ex);
            }
            return(null);
        }
Exemple #31
0
 private long StoreAccount(AccountData account)
 {
     return(this.InsertObject("INSERT INTO `Accounts`(`guid`) VALUES (@guid);", () => FetchAccountId(account.Guid),
                              new KeyValuePair <string, object>("@guid", account.Guid.ToByteArray())));
 }
Exemple #32
0
    void HttpResp_UI(BaseHttpRequest request, BaseResponse response)
    {
        ConsoleEx.DebugLog(" --- Http Resp - running in the main thread, UI purpose --" + response.GetType().ToString());
        if (response != null && response.status != BaseResponse.ERROR)
        {
            HttpRequest myRequest = (HttpRequest)request;
            switch (myRequest.Type)
            {
            case RequestType.GET_PARTITION_SERVER:
                //UI ...
                GetPartitionServerResponse ServerResp = response as GetPartitionServerResponse;
                showServerList(ServerResp);
                LoginIsReady();
                if (ServerResp != null && ServerResp.data != null)
                {
                    SpeakerMgr.autoShow(ServerResp.data.noticeTitle, ServerResp.data.noticeContent);
                }
                break;

            case RequestType.THIRD_GET_SERVER:
                GetPartitionServerResponse resp = response as GetPartitionServerResponse;
                showServerList(resp);
                AccountData ad = Native.mInstace.m_thridParty.GetAccountData();
                if (!string.IsNullOrEmpty(resp.data.platId))
                {
                    ad.uniqueId = resp.data.platId;
                }
                ad.token = resp.data.platToken;

                this.UniqueId = resp.data.token;
                LoginIsReady();
                if (resp != null && resp.data != null)
                {
                    SpeakerMgr.autoShow(resp.data.noticeTitle, resp.data.noticeContent);
                }
                break;

            case RequestType.UPDATE_RESOURCES: {
                //更新资源包
                ConfigResponse r = response as ConfigResponse;
                if (r != null && r.result)
                {
                    step = LoginStep.DownloadConfig_Start;
                    Content.SetActive(false);
                    configLoading.gameObject.SetActive(true);
                    test_DownloadResource(r);
                }
                else
                {
                    Debug.Log("the Config.zip is The latest! Don't need Download.");
                    step = LoginStep.Download_OK;
                    readLocalConfig();
                }
            }
            break;

            case RequestType.LOGIN_GAME:
                ComLoading.Close();

                status = status.set(LoginStatus.Login_Ready);
                JumpToGameView();
                                #if Spade
                SpadeIOSLogin spadeSdk = Native.mInstace.m_thridParty as SpadeIOSLogin;
                                #if !UNITY_EDITOR
                spadeSdk.NotityLogin(ChosenServer);
                                #endif
                                #endif
                #if UNITY_IOS && !DEBUG
                // 添加 IOS 本地 push
                IOSLocalPush.getInstance().notifyLoggedin();
                                #endif
                MessageMgr.GetInstance().SendWorldChatLogin();

                ///
                /// --------------- 登陆完成之后,设定日期改变,设定获得活动运营信息 -------
                ///
                if (Core.Data != null && Core.Data.playerManager != null && Core.Data.playerManager.RTData != null)
                {
                    Core.SM.recordDayChanged(Core.Data.playerManager.RTData.systemTime);
                }

                if (Core.Data != null && Core.Data.HolidayActivityManager != null)
                {
                    Core.Data.HolidayActivityManager.setHourChanged();
                }

                Core.Data.rechargeDataMgr.SendHttpRequest();
                break;
            }
        }
        else
        {
            ComLoading.Close();

            //登陆超时了
            if (response.errorCode == 2000)
            {
                if (Core.Data != null && Core.Data.stringManager != null)
                {
                    SQYAlertViewMove.CreateAlertViewMove(Core.Data.stringManager.getString(48), gameObject);
                }

                ///
                ///  ---- 回滚用户中心
                ///
                HttpClient.RevertToUserCenter();
                SendGetThirdServerRQ();
            }
            else
            {
                GetPartitionServerResponse ServerResp = response as GetPartitionServerResponse;
                if (ServerResp != null && ServerResp.data != null)
                {
                    SpeakerMgr.autoShow(ServerResp.data.noticeTitle, ServerResp.data.noticeContent);
                }

                if (Core.Data != null && Core.Data.stringManager != null)
                {
                    string word = Core.Data.stringManager.getString(response.errorCode);
                    if (!string.IsNullOrEmpty(word))
                    {
                        SQYAlertViewMove.CreateAlertViewMove(word, gameObject);
                    }
                }
            }
        }
    }
Exemple #33
0
    public void onButtonClick()
    {
        AccountData ad = Native.mInstace.m_thridParty.GetAccountData();

        #if Spade
        SpadeIOSLogin spadeSdk = Native.mInstace.m_thridParty as SpadeIOSLogin;
        bool          retry    = spadeSdk == null ? false : spadeSdk.OnCheckGameEnter();
        //如果没有登录,或者取消登录,打开第三方登录界面
        if (ad.loginStatus == ThirdLoginState.CancelLogin || ad.loginStatus == ThirdLoginState.Invalid || retry == false)
        {
            spadeSdk.getUniqueId(
                (t) => { SendGetThirdServerRQ(); }, false
                );
        #else
        //如果没有登录,或者取消登录,打开第三方登录界面
        if (ad.loginStatus == ThirdLoginState.CancelLogin || ad.loginStatus == ThirdLoginState.Invalid)
        {
            Native.mInstace.m_thridParty.getUniqueId(
                (t) => { SendGetThirdServerRQ(); }
                );
        #endif
        }
        else if (ad.loginStatus == ThirdLoginState.LoginFinish)
        {
            ///
            /// ---- 到目前为止,都是第三方登陆成功,自己的还没有初始化成功 -----
            ///

                        #if UNITY_ANDROID && !UNITY_EDITOR && !CHECKCONFIG
            if (step != LoginStep.Prepare_Config)
            {
                User_Click_LoginBtn = true;
                return;
            }
                        #endif

            if (ChosenServer != null)
            {
                if (ChosenServer.status == Server.STATUS_STOP)
                {
                    string word = Core.Data.stringManager.getString(21);
                    if (string.IsNullOrEmpty(word))
                    {
                        word = "Beta test is Over.\nThe public test is coming soon!";
                    }
                    SQYAlertViewMove.CreateAlertViewMove(word, gameObject);
                    return;
                }
                else if (ChosenServer.status == Server.STATUS_FULL)
                {
                    //TODO :停服提示 yancg

                    string status_full = Core.Data.stringManager.getString(32002);
                    if (string.IsNullOrEmpty(status_full))
                    {
                        status_full = "Beta test is Over.\nThe public test is coming soon!";
                    }
                    SQYAlertViewMove.CreateAlertViewMove(status_full, gameObject);
                    return;
                }
            }
            if (bGetServerListOk)
            {
                Login();
            }
            else
            {
                SendGetThirdServerRQ();
            }
        }
    }
Exemple #34
0
        public void Execute(IJobExecutionContext context)
        {
            AccountData ar   = new AccountData();
            var         data = ar.GetArchiveData();

            if (data != null && data.Any())
            {
                foreach (var r in data)
                {
                    String msg = "";
                    if (!String.IsNullOrEmpty(r.ActivationCode.ToString()) && !String.IsNullOrEmpty(r.Email))
                    {
                        try
                        {
                            string host = ConfigurationManager.AppSettings["Hostaddr"];;
                            string serverurl, fburl, twurl, gurl, insatUrl = "";
                            serverurl = host + "/Content/images/logo.png";
                            fburl     = host + "/Content/images/facebook.png";
                            twurl     = host + "/Content/images/twitter.png";
                            gurl      = host + "/Content/images/googleplus.png";
                            insatUrl  = host + "/Content/images/instagram.png";
                            var           confirUrl = host + "/UserAccount/UserActivation?ActivationCode=" + r.ActivationCode;
                            StringBuilder mailBody  = new StringBuilder();
                            mailBody.Append("<html><body>");
                            mailBody.Append("<div id='no'><u></u>");
                            mailBody.Append("<div style='margin:0 auto;line-height:18px;padding:0;font-size:16px;font-family:Palanquin,Arial,Helvetica,sans-serif;width:98%; border:1px solid darkgray;background-color:#fff;'>");
                            mailBody.Append("<div style='background-color:#fff;padding:10px;text-align:left'>");
                            mailBody.Append("<img src='http://" + serverurl + "' alt='My PPC Pal'></div>");
                            mailBody.Append("<div style='background-color:#0074b7;height:20px;'></div>");
                            mailBody.Append("<div style='margin-top:20px;text-align:left; padding-left:12.5px;color:#020215;'>");
                            mailBody.Append("<p>Dear " + r.FirstName + " " + r.LastName + ",</p>");
                            mailBody.Append("<h4 style='color:#0074b7; margin: 5px 0;'>Welcome to \"My PPC Pal\" - The most advanced tool for optimizing your Amazon PPC campaigns.</h4>");
                            mailBody.Append("<ul style='line-height:28px;'>");
                            mailBody.Append("<li>Please give user permissions to [email protected] in your Amazon Seller Central account and enter your Amazon Seller Name into the software as specified in the instructions provided.</li>");
                            mailBody.Append("<li>Once we have accepted the invitation, Amazon will confirm the invitation has been accepted. Please return to Seller Central to grant us the required user permissions. (See \"Help\" section for additional details).</li>");
                            mailBody.Append("<li>We will begin to import your PPC data and will notify you once it's completed. If you do not receive a confirmation email within a few hours please contact us at [email protected]</li>");
                            mailBody.Append("<li>Please see our instructional videos under the 'Help' section, this will teach you how to set up My PPC Pal to run your campaigns and how to get the most from the software.</li>");
                            mailBody.Append("<li>Start improving your PPC!</li>");
                            mailBody.Append("</ul>");
                            mailBody.Append("<h4 style='color:#0074b7;margin: 5px 0;'>Login details:</h4>");
                            mailBody.Append("<p>");
                            mailBody.Append("<b style='font-size:#e76969;'>User ID:</b> <span>" + r.Email + "<br />");
                            mailBody.Append("</p>");
                            mailBody.Append("<p> Please click the following link to activate your account</p>");
                            mailBody.Append("<a style='color:#e76969;' href=" + confirUrl + " >Click here to activate your account.</a>");
                            mailBody.Append("<p style='line-height:25px;'>");
                            mailBody.Append("As always, thank you for your business! <br>");
                            mailBody.Append("My PPC Pal");
                            mailBody.Append("</p></div>");
                            mailBody.Append("<div style='background:#0074b7;color:#fff;text-align:center;height:38px;padding-top:15px;'>");
                            mailBody.Append("<a href='https://www.facebook.com/myppcpal/'><img src='http://" + fburl + "' alt='Facebook' style='height:25px;'></a>");
                            mailBody.Append("<a href='https://www.instagram.com/myppcpal/'><img src='http://" + insatUrl + "' alt='Instagram+' style='height:25px;padding:0 10px;border-radius:55%;'></a>");
                            mailBody.Append("<a href='https://twitter.com/MyPPCPal'><img src='http://" + twurl + "' alt='Twitter' style='height:25px;'></a>");
                            mailBody.Append("</div></div></div>");
                            mailBody.Append("</body></html>");

                            string fromEmail = ConfigurationManager.AppSettings["Email"].ToString();
                            string password  = ConfigurationManager.AppSettings["Password"].ToString();
                            string smtphost  = ConfigurationManager.AppSettings["Smtphost"].ToString();
                            Int32  smtpport  = Convert.ToInt32(ConfigurationManager.AppSettings["Smtpport"].ToString());
                            string toEmail   = r.Email;
                            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(new MailAddress(fromEmail, "My PPC Pal"), new MailAddress(toEmail));
                            message.IsBodyHtml = true;
                            message.Priority   = MailPriority.High;

                            message.Subject = "||My PPC Pal Login Details||";
                            message.Body    = mailBody.ToString();
                            SmtpClient smtp = new SmtpClient();
                            smtp.Host      = smtphost;
                            smtp.EnableSsl = true;
                            NetworkCredential NetworkCred = new NetworkCredential(fromEmail, password);
                            smtp.UseDefaultCredentials = true;
                            smtp.Credentials           = NetworkCred;
                            smtp.Port = smtpport;
                            smtp.Send(message);
                            message.Dispose();
                            AccountData dt = new AccountData();
                            dt.Update48HourAlert(r.ActivationCode);
                        }
                        catch (Exception e)
                        {
                            msg = e.Message.ToString();
                            LogFile.WriteLog("SendActivationEmail_1 - " + "System" + ": " + msg);
                        }
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string aSqlStr = "select * from accountdata";

            List <AccountData> aListData = new List <AccountData>();

            aListData.Clear();

            int aKind = 0;

            try
            {
                aKind = int.Parse(Request.QueryString["Kind"].ToString());
            }
            catch
            {
                Response.Write("99");
            }

            //取得所有人員資料
            if (aKind == 0)
            {
                aSqlStr = "select * from accountdata where loginkind != " + Common._ManagerID;

                try
                {
                    using (MySqlConnection aCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQL_Admin"].ConnectionString))
                    {
                        aCon.Open();

                        using (MySqlCommand aCommand = new MySqlCommand(aSqlStr, aCon))
                        {
                            MySqlDataReader aDR = aCommand.ExecuteReader();

                            AccountData aData = new AccountData();

                            while (aDR.Read())
                            {
                                aData           = new AccountData();
                                aData.ID        = int.Parse(aDR["ID"].ToString());
                                aData.account   = aDR["account"].ToString();
                                aData.password  = aDR["password"].ToString();
                                aData.nickname  = aDR["nickname"].ToString();
                                aData.loginkind = int.Parse(aDR["loginkind"].ToString());

                                aListData.Add(aData);
                            }
                            aCon.Close();
                            aDR.Dispose();

                            AccountData[] aResult = aListData.ToArray();

                            string json_data = JsonConvert.SerializeObject(aResult, Formatting.Indented);
                            Response.Write(json_data);
                        }
                    }
                }
                catch
                {
                    Response.Write("99");
                }
            }
            else if (aKind == 1)//新增玩家資料
            {
                try
                {
                    aSqlStr = "INSERT INTO dokkansuper.accountdata (account, password, nickname, loginkind) VALUES ('{0}', '{1}', '{2}', '{3}');";

                    AccountData aData = new AccountData();

                    aData.account   = Request.Form["account"];
                    aData.password  = Request.Form["password"];
                    aData.nickname  = Request.Form["nickname"];
                    aData.loginkind = 0;

                    //如果是管理人員 權限設定為"1"
                    if (Request.Form["loginkind"] != null && Request.Form["loginkind"] == "on")
                    {
                        aData.loginkind = 1;
                    }

                    //判斷重複帳號
                    if (CheckCanCreate(aData.account, out byte ioutkind) != 0)
                    {
                        Response.Write(ioutkind.ToString());
                        return;
                    }

                    aSqlStr = string.Format(aSqlStr, aData.account, aData.password, aData.nickname, aData.loginkind);

                    using (MySqlConnection aCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQL_Admin"].ConnectionString))
                    {
                        aCon.Open();

                        using (MySqlCommand aCommand = new MySqlCommand(aSqlStr, aCon))
                        {
                            aCommand.ExecuteNonQuery();
                        }
                        aCon.Close();
                    }

                    Response.Write("0");
                }
                catch
                {
                    Response.Write("99");
                }
            }
            else if (aKind == 2)//修改玩家資料
            {
                aSqlStr = "UPDATE dokkansuper.accountdata SET account = '{0}', password = '******' ,nickname = '{2}' , loginkind = {3} WHERE (ID = {4});";
                try
                {
                    AccountData aData = new AccountData();

                    aData.ID        = int.Parse(Request.Form["ID"]);
                    aData.account   = Request.Form["account"];
                    aData.password  = Request.Form["password"];
                    aData.nickname  = Request.Form["nickname"];
                    aData.loginkind = 0;

                    //如果是管理人員 權限設定為"1"
                    if (Request.Form["loginkind"] != null && Request.Form["loginkind"] == "on")
                    {
                        aData.loginkind = 1;
                    }

                    if (Request.Form["loginkind"] == null)
                    {
                        aData.loginkind = 0;
                    }

                    //判斷重複帳號
                    if (CheckCanCreate(aData.account, out byte ioutkind, aData.ID) != 0)
                    {
                        Response.Write(ioutkind.ToString());
                        return;
                    }

                    aSqlStr = string.Format(aSqlStr, aData.account, aData.password, aData.nickname, aData.loginkind, aData.ID);

                    using (MySqlConnection aCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQL_Admin"].ConnectionString))
                    {
                        aCon.Open();

                        using (MySqlCommand aCommand = new MySqlCommand(aSqlStr, aCon))
                        {
                            aCommand.ExecuteNonQuery();
                        }
                        aCon.Close();
                    }
                    Response.Write("0");
                }
                catch
                {
                    Response.Write("99");
                }
            }
            else if (aKind == 3)//移除玩家資料
            {
                aSqlStr = "DELETE FROM dokkansuper.accountdata WHERE (ID = {0});";

                try
                {
                    AccountData aData = new AccountData();
                    aData.ID = int.Parse(Request.QueryString["ID"]);
                    aSqlStr  = string.Format(aSqlStr, aData.ID);

                    using (MySqlConnection aCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQL_Admin"].ConnectionString))
                    {
                        aCon.Open();

                        using (MySqlCommand aCommand = new MySqlCommand(aSqlStr, aCon))
                        {
                            aCommand.ExecuteNonQuery();
                        }
                        aCon.Close();
                    }
                    Response.Write("0");
                }
                catch
                {
                    Response.Write("99");
                }
            }
        }
Exemple #36
0
 public static GameServerInformations[] GetGameServerInformations(AccountData account)
 {
     return(WorldServers.ConvertAll <GameServerInformations>(x => x.GetServerInformations(account)).ToArray());
 }
        private static unsafe void ThreadFunc()
        {
            try
            {
                int size = 65536;
                bool createdMain = false;
                var hFile = WinAPI.OpenFileMapping(
                    WinAPI.FileMapAccess.FileMapAllAccess,
                    false,
                    "ulHelper_fm");
                if (hFile == IntPtr.Zero)
                {
                    hFile = WinAPI.CreateFileMapping(
                        new IntPtr(-1),
                        IntPtr.Zero,
                        WinAPI.FileMapProtection.PageReadWrite,
                        (uint)0, (uint)size,
                        "ulHelper_fm");
                    createdMain = true;
                }
                var lpBaseAddress = WinAPI.MapViewOfFile(
                    hFile,
                    WinAPI.FileMapAccess.FileMapAllAccess,
                    0, 0, 0);

                Mutex = new Mutex(false, "ulHelper_mutex");
                Stream = new UnmanagedMemoryStream((byte*)lpBaseAddress.ToPointer(), size, size, FileAccess.ReadWrite);

                eventWH = new EventWaitHandle(false, EventResetMode.AutoReset, "ulHelper_event");

                int accCount;
                byte[] buf = new byte[size];

                if (createdMain)
                {
                    Mutex.WaitOne();
                    try
                    {
                        buf[0] = buf[1] = buf[2] = buf[3] = 0;
                        Stream.Position = 0;
                        Stream.Write(buf, 0, 4);
                    }
                    finally
                    {
                        Mutex.ReleaseMutex();
                    }
                }

                eventWH.Set();
                while (true)
                {
                    eventWH.WaitOne();
                    if (MainForm.NeedTerminate)
                        break;
                    Mutex.WaitOne();
                    try
                    {
                        Stream.Position = 0;
                        accCount = Stream.ReadByte();
                        lock (Accounts.List)
                            if (Accounts.List.Count != accCount)
                            {
                                foreach (var acc in Accounts.List)
                                    acc.Active = false;
                                for (int i = 0; i < accCount; i++)
                                {
                                    string accountName = "";
                                    int index = 0;
                                    Stream.Position = 8 + i * 128;
                                    Stream.Read(buf, 0, 128);
                                    while (buf[index] != 0)
                                        accountName += (char)buf[index++];
                                    if (!Accounts.List.Any(acc => acc.Name == accountName))
                                    {
                                        var accData = new AccountData(accountName);
                                        Accounts.List.Add(accData);
                                    }
                                    Accounts.List.First(acc => acc.Name == accountName).Active = true;
                                }
                                PerformNewAccount();
                            }
                    }
                    finally
                    {
                        Mutex.ReleaseMutex();
                    }
                }

                WinAPI.UnmapViewOfFile(lpBaseAddress);
                WinAPI.CloseHandle(hFile);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                var f = new ExceptionForm(ex);
                f.ShowDialog();
            }
        }
Exemple #38
0
        public static void Main(string[] args)
        {
            WriteLine("------------------------------------------------------", ConsoleColor.Blue);
            WriteLine("[    France Ragnarok Account Creator - by GodLesZ    ]", ConsoleColor.Blue);
            WriteLine("------------------------------------------------------", ConsoleColor.Blue);
            WriteLine();

            Write("\t#1 fetch email..");
            string email = MailGenerator.createMail();

            if (email == "")
            {
                WriteLine(" failed! PLease report this to GodLesZ.", ConsoleColor.Red);
                CleanUp();
                Console.ReadKey();
                return;
            }
            WriteLine(" done", ConsoleColor.Green);

            Write("\t#2 build credentials..");
            AccountData userData = new AccountData(email);

            WriteLine(" done", ConsoleColor.Green);

            WriteLine("\t#3 create account..");
            try {
                EAccountResult res;
                if ((res = AccountHelper.CreateAccount(ref userData)) != EAccountResult.Success)
                {
                    WriteLine("\tfailed to create account: " + res, ConsoleColor.Red);
                    CleanUp();
                    Console.ReadKey();
                    return;
                }
            } catch (Exception ex) {
                WriteLine("\tfailed to create account: internal exception", ConsoleColor.Red);
                CleanUp();
                Console.WriteLine(ex);

                Console.ReadKey();
                return;
            }

            try {
                Write("\t#4 create file..");
                using (StreamWriter Writer = new StreamWriter("Account.txt", true)) {
                    Writer.WriteLine("#----------- Account Daten ---------");
                    Writer.WriteLine("# E-Mail  :  " + userData.Email);
                    Writer.WriteLine("# Login   :  "******"# Password:  "******" done", ConsoleColor.Green);
            } catch (Exception WriterEX) {
                WriteLine("\failed to create file: internal exception", ConsoleColor.Red);
                CleanUp();
                Console.WriteLine(WriterEX);
                Console.ReadKey();
                return;
            }

            CleanUp();
            WriteLine();
            WriteLine("----------------------------------------", ConsoleColor.Green);

            WriteLine("Email    : " + userData.Email);
            WriteLine("Login    : "******"Password : "******"----------------------------------------", ConsoleColor.Green);
            Write("Wait for FRO email.. ");

            int i = 0;

            do
            {
                Console.Write("{0}{1}", (i > 0 ? "\b" : ""), mCursorData[i % mCursorData.Length]);

                if (MailGenerator.CheckResponseEmail(userData.Email) == true)
                {
                    Write("\b received & validated!", ConsoleColor.Green);
                    break;
                }

                System.Threading.Thread.Sleep(200);
                i++;
            } while (true);

            WriteLine();
            WriteLine();
            WriteLine("------------------------------------------------------", ConsoleColor.Blue);
            WriteLine("[                GodLesZ <3 Blaubeere                ]", ConsoleColor.Blue);
            WriteLine("------------------------------------------------------", ConsoleColor.Blue);
            Console.ReadKey();
        }
        private int BuildPositionsForAccount(HugoDataSet.PortfolioDataTable portfolio, List <Index> indices, Index totalRow, AccountData accountData, List <Position> positions)
        {
            int unsubscribedSymbols = 0;

            try
            {
                foreach (HugoDataSet.PortfolioRow portfolioRow in portfolio)
                {
                    Position newRow          = new Position();
                    Index    indexRow        = null;
                    double   underlyingPrice = 0;

                    if (!portfolioRow.IsUnderlyingSymbolNull())
                    {
                        if (indices != null)
                        {
                            indexRow = GetIndexData(indices, portfolioRow.UnderlyingSymbol);
                        }
                        if (indexRow != null)
                        {
                            underlyingPrice = indexRow.LastPrice.HasValue ? indexRow.LastPrice.Value : 0;
                        }
                        else
                        {
                            HugoDataSet.PortfolioRow underlyingRow = portfolio.FindByAcctNameSymbol(portfolioRow.AcctName, portfolioRow.UnderlyingSymbol);
                            if (underlyingRow != null)
                            {
                                underlyingPrice = underlyingRow.CurrentPrice;
                            }
                        }
                    }

                    BuildPositionRow(portfolioRow, accountData, newRow, underlyingPrice);

                    // accountData is null only if we are not interested in calculating totals for this account
                    if (accountData != null)
                    {
                        AggregateAccountTotals(accountData, newRow, underlyingPrice);

                        if (newRow.IsOption)
                        {
                            AggregateIndexTotals(newRow, indexRow, totalRow);
                        }
                    }

                    if ((newRow.SubscriptionStatus != "Subscribed") && ((newRow.CurrentPosition != 0) || (newRow.SODPosition != 0) || newRow.IsStock))
                    {
                        unsubscribedSymbols++;
                    }
                    newRow.UpdateTime = portfolioRow.IsUpdateTimeNull() ? new System.Nullable <TimeSpan>() : portfolioRow.UpdateTime;

                    positions.Add(newRow);
                }
            }
            catch (Exception ex)
            {
                ReportError("Error building positions for account", ex);
            }

            return(unsubscribedSymbols);
        }
Exemple #40
0
 public AccountDataEventArgs(AccountData accountData)
 {
     AccountData = accountData;
 }
Exemple #41
0
 public void SaveAccountData(AccountData accountData)
 {
 }
 public static void UpdateAccount(AccountData account)
 {
     DatabaseManager.GetInstance().Query(string.Format("INSERT INTO dofus_accounts(`Id`, `Role`, `CharacterSlots`, `LastSelectedServerId`) VALUES('{0}', '{1}', '{2}', '{3}') ON DUPLICATE KEY UPDATE `Role`='{4}', `CharacterSlots`='{5}', `LastSelectedServerId`='{6}'", account.Id, (sbyte)account.Role, account.CharacterSlots, account.LastSelectedServerId, (sbyte)account.Role, account.CharacterSlots, account.LastSelectedServerId), DatabaseManager.GetInstance().UseProvider());
     ToAccountRecord(account).UpdateInstantElement <AccountRecord>();
 }
        private void BuildPositionRow(HugoDataSet.PortfolioRow portfolioRow, AccountData accountData, Position newRow, double underlyingPrice)
        {
            int lineNumber = 0;

            try
            {
                lineNumber++; newRow.Account            = portfolioRow.AcctName;
                lineNumber++; newRow.Symbol             = portfolioRow.Symbol;
                lineNumber++; newRow.SubscriptionStatus = portfolioRow.SubscriptionStatus;
                lineNumber++; newRow.SODPosition        = portfolioRow.SOD_Position;
                lineNumber++; newRow.SODPrice           = portfolioRow.SOD_Price; // 5
                lineNumber++; newRow.SODMarketValue     = portfolioRow.SOD_Market_Value;
                lineNumber++; newRow.ChangeInPosition   = portfolioRow.Change_in_Position;
                lineNumber++; newRow.ChangeInCost       = portfolioRow.Change_in_Cost;
                lineNumber++; newRow.CurrentPosition    = portfolioRow.Current_Position;
                lineNumber++; newRow.NettingAdjustment  = portfolioRow.Netting_Adjustment; // 10
                lineNumber++; newRow.CurrentPrice       = portfolioRow.CurrentPrice;
                lineNumber++; newRow.CurrentCost        = portfolioRow.Current_Cost;
                lineNumber++; newRow.Closed             = portfolioRow.Closed;
                lineNumber++; newRow.OptionType         = portfolioRow.IsOptionTypeNull() ? null : portfolioRow.OptionType;
                lineNumber++; newRow.UnderlyingSymbol   = portfolioRow.IsUnderlyingSymbolNull() ? null : portfolioRow.UnderlyingSymbol; // 15
                lineNumber++; newRow.Multiplier         = portfolioRow.Multiplier;
                lineNumber++; newRow.IsStock            = portfolioRow.IsStock == 1;
                lineNumber++; newRow.IsOption           = portfolioRow.IsOption == 1;
                lineNumber++; newRow.IsFuture           = portfolioRow.IsFuture == 1;
                lineNumber++; newRow.Open         = portfolioRow.IsOpenNull() ? new System.Nullable <double>() : portfolioRow.Open; // 20
                lineNumber++; newRow.PrevClose    = portfolioRow.IsPrevCloseNull() ? new System.Nullable <double>() : portfolioRow.PrevClose;
                lineNumber++; newRow.LastPrice    = portfolioRow.IsLastPriceNull() ? new System.Nullable <double>() : portfolioRow.LastPrice;
                lineNumber++; newRow.Bid          = portfolioRow.IsBidNull() ? new System.Nullable <double>() : portfolioRow.Bid;
                lineNumber++; newRow.Ask          = portfolioRow.IsAskNull() ? new System.Nullable <double>() : portfolioRow.Ask;
                lineNumber++; newRow.ClosingPrice = portfolioRow.IsClosingPriceNull() ? new System.Nullable <double>() : portfolioRow.ClosingPrice;  // 25
                // must use portfolioRow.PriceMultiplier for P&L purposes
                // newRow.Multiplier has been adjusted to reflect deltas on the associated index
                lineNumber++; newRow.CurrentMarketValue = portfolioRow.CurrentPrice * newRow.CurrentPosition * portfolioRow.PriceMultiplier;
                lineNumber++; newRow.PandL          = newRow.CurrentMarketValue - newRow.CurrentCost;
                lineNumber++; newRow.ExpirationDate = portfolioRow.IsExpirationDateNull() ? new System.Nullable <DateTime>() : portfolioRow.ExpirationDate;

                lineNumber++;
                if (newRow.Bid.HasValue && newRow.Ask.HasValue)
                {
                    lineNumber++; newRow.Mid = (newRow.Bid + newRow.Ask) / 2.0;  // 30
                }
                else
                {
                    lineNumber++; newRow.Mid = 0;
                }

                lineNumber++;
                if (newRow.IsOption)
                {
                    lineNumber++; newRow._100DeltaUSD    = (newRow.CurrentPosition + newRow.NettingAdjustment) * newRow.Multiplier * underlyingPrice;
                    lineNumber++; newRow.Delta           = portfolioRow.IsDeltaNull() ? new System.Nullable <double>() : portfolioRow.Delta;
                    lineNumber++; newRow.DeltaUSD        = portfolioRow.IsDeltaNull() ? new System.Nullable <double>() : portfolioRow.Delta * (newRow.CurrentPosition + newRow.NettingAdjustment) * newRow.Multiplier * underlyingPrice;
                    lineNumber++; newRow.Gamma           = portfolioRow.IsGammaNull() ? new System.Nullable <double>() : portfolioRow.Gamma; // 35
                    lineNumber++; newRow.GammaUSD        = portfolioRow.IsGammaNull() ? new System.Nullable <double>() : newRow.Gamma * (newRow.CurrentPosition + newRow.NettingAdjustment) * newRow.Multiplier * underlyingPrice;
                    lineNumber++; newRow.Theta           = portfolioRow.IsThetaNull() ? new System.Nullable <double>() : portfolioRow.Theta;
                    lineNumber++; newRow.ThetaAnnualized = portfolioRow.IsThetaNull() ? new System.Nullable <double>() : newRow.Theta * (newRow.CurrentPosition + newRow.NettingAdjustment) * portfolioRow.PriceMultiplier * 360;

                    lineNumber++; newRow.Vega        = portfolioRow.IsVegaNull() ? new System.Nullable <double>() : portfolioRow.Vega;
                    lineNumber++; newRow.ImpliedVol  = portfolioRow.IsImpliedVolNull() ? new System.Nullable <double>() : portfolioRow.ImpliedVol; // 40
                    lineNumber++; newRow.StrikePrice = portfolioRow.IsStrikePriceNull() ? new System.Nullable <decimal>() : portfolioRow.StrikePrice;

                    lineNumber++;
                    if (newRow.OptionType == "Call")
                    {
                        lineNumber++; newRow.TimePremium = Math.Max(0, newRow.Mid.Value - Math.Max(0, underlyingPrice * newRow.Multiplier / 100 - (double)newRow.StrikePrice.Value)) * (newRow.CurrentPosition + newRow.NettingAdjustment) * portfolioRow.PriceMultiplier;
                    }
                    else
                    {
                        lineNumber++; newRow.TimePremium = Math.Max(0, newRow.Mid.Value - Math.Max(0, (double)newRow.StrikePrice.Value - underlyingPrice * newRow.Multiplier / 100)) * (newRow.CurrentPosition + newRow.NettingAdjustment) * portfolioRow.PriceMultiplier;
                        lineNumber++;
                        if (accountData != null)
                        {
                            if (((newRow.CurrentPosition + newRow.NettingAdjustment) > 0) && (newRow.Multiplier > 0) && newRow.StrikePrice.HasValue && (accountData.PutsOutOfMoneyThreshold < 1))
                            {
                                lineNumber++; // 45
                                if ((double)newRow.StrikePrice.Value * 100 / newRow.Multiplier < (1 - accountData.PutsOutOfMoneyThreshold) * underlyingPrice)
                                {
                                    lineNumber++; newRow.IsOutOfBounds = true;
                                }
                                else if ((double)newRow.StrikePrice.Value * 100 / newRow.Multiplier > (1 + accountData.PutsOutOfMoneyThreshold) * underlyingPrice)
                                {
                                    lineNumber++; newRow.IsOutOfBounds = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    ReportError(String.Format("Error building position row, Account={0}, Symbol={1}. line number={2}", portfolioRow.AcctName, portfolioRow.Symbol, lineNumber), ex);
                }
                catch
                {
                    ReportError("Error building position row", ex);
                }
            }
        }
        private async Task OnSelectWorld(IPacket packet)
        {
            packet.Decode <byte>();

            var worldID   = packet.Decode <byte>();
            var channelID = packet.Decode <byte>();

            try
            {
                using (var p = new Packet(SendPacketOperations.SelectWorldResult))
                    using (var store = Service.DataStore.OpenSession())
                    {
                        var service = Service.Peers
                                      .OfType <GameServiceInfo>()
                                      .FirstOrDefault(g => g.ID == channelID &&
                                                      g.WorldID == worldID);
                        var result = LoginResultCode.Success;

                        if (service == null)
                        {
                            result = LoginResultCode.NotConnectableWorld;
                        }

                        p.Encode <byte>((byte)result);

                        if (result == LoginResultCode.Success)
                        {
                            var data = store
                                       .Query <AccountData>()
                                       .Where(d => d.AccountID == Account.ID)
                                       .FirstOrDefault(d => d.WorldID == worldID);

                            if (data == null)
                            {
                                data = new AccountData
                                {
                                    AccountID = Account.ID,
                                    WorldID   = worldID,
                                    SlotCount = 3
                                };

                                await store.InsertAsync(data);
                            }

                            AccountData     = data;
                            SelectedService = service;

                            if (Account.LatestConnectedWorld != worldID)
                            {
                                Account.LatestConnectedWorld = worldID;
                                await store.UpdateAsync(Account);
                            }

                            var characters = store
                                             .Query <Character>()
                                             .Where(c => c.AccountDataID == data.ID)
                                             .ToList();

                            p.Encode <byte>((byte)characters.Count);
                            characters.ForEach(c =>
                            {
                                c.EncodeStats(p);
                                c.EncodeLook(p);

                                p.Encode <bool>(false);
                                p.Encode <bool>(false);
                            });

                            p.Encode <bool>(
                                !string.IsNullOrEmpty(Account.SecondPassword)
                                );                          // bLoginOpt TODO: proper bLoginOpt stuff
                            p.Encode <int>(data.SlotCount); // nSlotCount
                            p.Encode <int>(0);              // nBuyCharCount
                        }

                        await SendPacket(p);
                    }
            }
            catch
            {
                using (var p = new Packet(SendPacketOperations.SelectWorldResult))
                {
                    p.Encode <byte>((byte)LoginResultCode.Unknown);
                    await SendPacket(p);
                }
            }
        }
Exemple #45
0
        public async Task <IActionResult> Register([FromBody] RegisterModel model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                return(RequestHandler.BadRequest("User with that email already exists"));
            }

            var newAccount = await CreateIngameAccount(model.Username, model.Password, model.Email);

            if (newAccount == null)
            {
                return(RequestHandler.BadRequest("Username is already taken"));
            }

            var newUser = new ApplicationUser
            {
                Id        = Guid.NewGuid(),
                AccountId = newAccount.Id,
                UserName  = model.Username,
                Firstname = model.Firstname,
                Lastname  = model.Lastname,
                Email     = model.Email,
                JoinDate  = DateTime.UtcNow
            };

            var result = await _userManager.CreateAsync(newUser, model.Password);

            if (!result.Succeeded)
            {
                return(RequestHandler.BadRequest(result.Errors));
            }

            var token = TokenHelper.GenerateToken(newUser, _jwtSecurityKey).SerializeToken();

            // All good - now we add and save the new entities
            var accountData = new AccountData
            {
                Id        = newAccount.Id,
                Dp        = 0,
                Vp        = 0,
                ExtraMask = 0
            };

            await _authContext.Account.AddAsync(newAccount);

            await _authContext.AccountData.AddAsync(accountData);

            await _authContext.SaveChangesAsync();

            var userDto = new WebAccDTO
            {
                Id         = newUser.Id,
                AccountId  = newUser.AccountId,
                Username   = newUser.UserName,
                Firstname  = newUser.Firstname,
                Lastname   = newUser.Lastname,
                Email      = newUser.Email,
                JoinDate   = DateTime.UtcNow,
                Roles      = new string[] { },
                Location   = "Unknown",
                VP         = 0,
                DP         = 0,
                TotalVotes = 0,
                Account    = newAccount
            };

            // Update Client
            var count = await _userManager.Users.CountAsync();

            var userInformation = new UserInformationResponse
            {
                Id       = newUser.Id,
                Email    = newUser.Email,
                Username = newUser.UserName
            };

            await _signalRHub.Clients.All.UpdateUserInformations(userInformation, count);

            return(Ok(new
            {
                token,
                userDto
            }));
        }
    // Load Database Data
    public override void Load()
    {
        if (!dataLoaded) {
            // Clean old data
            dataRegister.Clear ();
            displayKeys.Clear ();

            // Read all entries from the table
            string query = "SELECT * FROM " + tableName;

            // If there is a row, clear it.
            if (rows != null)
                rows.Clear ();

            // Load data
            rows = DatabasePack.LoadData (DatabasePack.adminDatabasePrefix, query);

            // Read all the data
            if ((rows != null) && (rows.Count > 0)) {
                foreach (Dictionary<string,string> data in rows) {
                    AccountData display = new AccountData ();
                    display.id = int.Parse (data ["id"]);
                    display.name = data ["username"];
                    display.status = int.Parse (data ["status"]);
                    display.isLoaded = false;
                    //Debug.Log("Name:" + display.name  + "=[" +  display.id  + "]");
                    dataRegister.Add (display.id, display);
                    displayKeys.Add (display.id);
                }
                LoadSelectList ();
            }
            dataLoaded = true;
        }
    }
        private void OnLogin(MobaMessage msg)
        {
            OperationResponse operationResponse = msg.Param as OperationResponse;

            if (operationResponse == null)
            {
                Singleton <TipView> .Instance.ShowViewSetText("登陆失败...系统错误", 1f);

                LoginStateManager.Instance.ChangeState(LoginStateCode.LoginState_waitLogin);
            }
            else
            {
                int           num           = (int)operationResponse.Parameters[1];
                string        debugMessage  = operationResponse.DebugMessage;
                MobaErrorCode mobaErrorCode = (MobaErrorCode)num;
                if (mobaErrorCode != MobaErrorCode.InvalidOperation)
                {
                    if (mobaErrorCode != MobaErrorCode.InvalidParameter)
                    {
                        if (mobaErrorCode != MobaErrorCode.UserExist)
                        {
                            if (mobaErrorCode != MobaErrorCode.UserNotExist)
                            {
                                if (mobaErrorCode != MobaErrorCode.Ok)
                                {
                                    if (mobaErrorCode != MobaErrorCode.SystemError)
                                    {
                                        Singleton <TipView> .Instance.ShowViewSetText("登陆失败..不明原因,请重试", 1f);

                                        LoginStateManager.Instance.ChangeState(LoginStateCode.LoginState_waitLogin);
                                    }
                                    else
                                    {
                                        Singleton <TipView> .Instance.ShowViewSetText("传送门被调皮的小精灵搞坏了,正在抢修中", 1f);

                                        LoginStateManager.Instance.ChangeState(LoginStateCode.LoginState_waitLogin);
                                    }
                                }
                                else
                                {
                                    AccountData accountData = ModelManager.Instance.Get_accountData_X();
                                    if (accountData != null)
                                    {
                                        AnalyticsToolManager.SetAccountId(accountData.AccountId);
                                    }
                                    Singleton <TipView> .Instance.ShowViewSetText((!(LanguageManager.Instance.GetStringById("ChooseServerUI_LoginSuccess") != string.Empty))? "登录成功" : LanguageManager.Instance.GetStringById("ChooseServerUI_LoginSuccess"), 1f);

                                    this.bFinish = true;
                                    LoginStateManager.Instance.ChangeState(LoginStateCode.LoginState_selectServer);
                                }
                            }
                            else
                            {
                                CtrlManager.ShowMsgBox((!(LanguageManager.Instance.GetStringById("LoginUI_Title_LoginError") != string.Empty)) ? "登录错误" : LanguageManager.Instance.GetStringById("LoginUI_Title_LoginError"), "该账号不存在,请确认后重新输入", null, PopViewType.PopOneButton, "确定", "取消", null);
                                LoginStateManager.Instance.ChangeState(LoginStateCode.LoginState_waitLogin);
                            }
                        }
                        else
                        {
                            Singleton <TipView> .Instance.ShowViewSetText("登陆失败...玩家已经存在,重复登录", 1f);

                            LoginStateManager.Instance.ChangeState(LoginStateCode.LoginState_waitLogin);
                        }
                    }
                    else
                    {
                        Singleton <TipView> .Instance.ShowViewSetText("登陆失败...参数错误", 1f);

                        LoginStateManager.Instance.ChangeState(LoginStateCode.LoginState_waitLogin);
                    }
                }
                else
                {
                    CtrlManager.ShowMsgBox("登录错误", "账号或密码错误,请确认后重新输入", null, PopViewType.PopOneButton, "确定", "取消", null);
                    LoginStateManager.Instance.ChangeState(LoginStateCode.LoginState_waitLogin);
                }
            }
        }
 public override void CreateNewData()
 {
     editingDisplay = new AccountData ();
     originalDisplay = new AccountData ();
     selectedDisplay = -1;
 }
Exemple #49
0
        public IAccountData CreateAccountObject()
        {
            var account = new AccountData();

            return(account);
        }
Exemple #50
0
 public void Login(AccountData user)
 {
     Forms("mailbox:login-input", user.Username);
     Thread.Sleep(5000);
     Forms("mailbox:password-input", user.Password);
 }
    // Draw the Instance list
    public override void DrawLoaded(Rect box)
    {
        // Setup the layout
        Rect pos = box;
        pos.x += ImagePack.innerMargin;
        pos.y += ImagePack.innerMargin;
        pos.width -= ImagePack.innerMargin;
        pos.height = ImagePack.fieldHeight;

        if (dataRegister.Count <= 0) {
            pos.y += ImagePack.fieldHeight;
            ImagePack.DrawLabel (pos.x, pos.y, "An account must exist before editing it.");
            return;
        }

        // Draw the content database info
        ImagePack.DrawLabel (pos.x, pos.y, "Account Management");

        if (newItemCreated) {
            newItemCreated = false;
            LoadSelectList ();
            newSelectedDisplay = displayKeys.Count - 1;
        }

        // Draw data Editor
        if (newSelectedDisplay != selectedDisplay) {
            selectedDisplay = newSelectedDisplay;
            int displayKey = displayKeys [selectedDisplay];
            GetCharacters (dataRegister [displayKey].id);
            editingDisplay = dataRegister [displayKey];
            originalDisplay = editingDisplay.Clone ();
        }

        //if (!displayList.showList) {
        pos.y += ImagePack.fieldHeight;
        pos.x -= ImagePack.innerMargin;
        pos.y -= ImagePack.innerMargin;
        pos.width += ImagePack.innerMargin;
        DrawEditor (pos, false);
        pos.y -= ImagePack.fieldHeight;
        //pos.x += ImagePack.innerMargin;
        pos.y += ImagePack.innerMargin;
        pos.width -= ImagePack.innerMargin;
        //}

        if (state != State.Loaded) {
            // Draw combobox
            pos.width /= 2;
            pos.x += pos.width;
            newSelectedDisplay = ImagePack.DrawCombobox (pos, "", selectedDisplay, displayList);
            pos.x -= pos.width;
            pos.width *= 2;
        }
    }
Exemple #52
0
 public CmdGetAccountCharsStrategy(ILogger logger, AccountData accountData, ICharacterInfo characterInfo)
 {
     _logger        = logger ?? throw new Exception("CmdGetAccountCharsStrategy - logger cannot be NULL!");
     _accountData   = accountData ?? throw new Exception("CmdGetAccountCharsStrategy - account data cannot be NULL!");
     _characterInfo = characterInfo ?? throw new Exception("CmdGetAccountCharsStrategy - character info cannot be NULL!");
 }
Exemple #53
0
        async Task StartProcess()
        {
            try
            {
                documentComplete = new WebBrowserDocumentCompletedEventHandler((s, e) =>
                {
                    if (webLayout.DocumentText.Contains("res://ieframe.dll"))
                    {
                        tcs.SetException(new Exception("Lỗi không có kết nối internet"));
                        return;
                    }
                    if (!tcs.Task.IsCompleted)
                    {
                        webLayout.DocumentCompleted -= documentComplete;
                        tcs.SetResult(v);
                    }
                });
                isFinishProcess = false;
                AccountData userAccount  = new AccountData();
                var         adminAccount = new AdminAccount();
                decimal     moneyLeft    = 0;

                var process = checkAccountAdmin(ref adminAccount);
                do
                {
                    switch (process)
                    {
                    case "OpenWeb":
                        CreateSyncTask();
                        webLayout.Navigate(url);
                        await tcs.Task;
                        await Task.Delay(5000);

                        process = "Login";
                        if (webLayout.Url.ToString() == user_URL)
                        {
                            process = "CheckAmountAccount";
                            if (data.Count() == 0 && data.Exists(x => x.IsKeepSession))
                            {
                                process = "Finish";
                            }
                            break;
                        }

                        if (webLayout.Url.ToString() != index_URL)
                        {
                            SendNotificationForError(
                                "Trang Web Không Truy Cập Được",
                                $"{web_name} không thể truy cập");

                            process = "Finish";
                            break;
                        }

                        break;

                    case "Login":
                        CreateSyncTask();
                        Login(adminAccount);
                        await tcs.Task;
                        await Task.Delay(5000);

                        if (webLayout.Url.ToString() == index_URL)
                        {
                            if (!Globals.isSentNotification_BK)
                            {
                                Globals.isSentNotification_BK = true;
                                SendNotificationForError("Account Admin Đăng Nhập Lỗi",
                                                         $"{web_name} : Account admin đăng nhập web bị lỗi");
                            }
                            process = "Finish";
                            break;
                        }
                        Globals.isSentNotification_BK = false;
                        process = "CheckAmountAccount";
                        if (data.Exists(x => x.IsKeepSession))
                        {
                            process = "Finish";
                        }
                        break;

                    case "CheckAmountAccount":
                        var currentMoney   = GetAmountAccount();
                        var isAmountEnough = false;
                        if (currentMoney > 0)
                        {
                            isAmountEnough = CheckAmoutAccount(currentMoney);
                        }
                        await Task.Delay(5000);

                        if (!isAmountEnough)
                        {
                            if (!Globals.isSentNotification_BK)
                            {
                                Globals.isSentNotification_BK = true;
                                SendNotificationForError("Account không đủ số tiền tối thiểu",
                                                         $"{web_name} : Account admin không đủ số tiền tối thiểu");
                            }
                        }
                        else
                        {
                            Globals.isSentNotification_BK = false;
                        }

                        moneyLeft = currentMoney;
                        process   = "AccessToDaily";
                        break;

                    case "AccessToDaily":
                        CreateSyncTask();
                        AccessToDaily();
                        await tcs.Task;
                        await Task.Delay(5000);

                        if (webLayout.Url.ToString() != agencies_URL)
                        {
                            SendNotificationForError(
                                "Truy cập vào đại lý bị lỗi",
                                $"{web_name} : Trang đại lý bị lỗi");
                            process = "Finish";
                            break;
                        }

                        process = "SearchUser";
                        break;

                    case "SearchUser":
                        currentMessage = data.FirstOrDefault();
                        userAccount    = SearchUser();
                        if (userAccount == null)
                        {
                            // save record
                            SaveRecord($"Không tìm thấy user {web_name} : user id {currentMessage.Account}");

                            data.Remove(currentMessage);
                            if (data.Count == 0)
                            {
                                process = "Finish";
                                break;
                            }
                            process = "OpenWeb";
                            break;
                        }

                        CreateSyncTask();
                        SearchUserClick(userAccount);
                        await tcs.Task;
                        await Task.Delay(2000);

                        process = "AccessToPayIn";
                        break;

                    case "AccessToPayIn":
                        var userRow = FindAccountOnResult(userAccount);
                        if (userRow == null)
                        {
                            var errorMessage = $"" +
                                               $"Truy cập trang cộng tiền web {web_name} bị lỗi hoặc" +
                                               $" {web_name} : không tìm thấy account của User id {userAccount.IDAccount}";

                            SaveRecord(errorMessage);
                            SendNotificationForError(
                                "Truy cập vào trang cộng tiền bị lỗi", errorMessage);

                            data.Remove(currentMessage);
                            if (data.Count == 0)
                            {
                                process = "Finish";
                                break;
                            }
                            process = "OpenWeb";
                            break;
                        }

                        CreateSyncTask();
                        AccessToPayIn(userRow);
                        await tcs.Task;
                        await Task.Delay(5000);

                        process = "PayIn";
                        break;

                    case "PayIn":
                        PayIn();
                        await Task.Delay(5000);

                        var userName = GetUserName();
                        await Task.Delay(2000);

                        CreateSyncTask();
                        PayInSubmit();
                        await tcs.Task;
                        await Task.Delay(5000);

                        if (!webLayout.Url.ToString().Contains(agencies_URL))
                        {
                            var errorMessage = $"Cộng tiền account { currentMessage.Account } bị lỗi";
                            SaveRecord(errorMessage);

                            SendNotificationForError(
                                "Cộng tiền không thành công",
                                $"{Constant.BANHKEO.ToUpper()} : Lỗi + { helper.GetMoneyFormat(currentMessage.Money) } { currentMessage.Web }{ currentMessage.Account } ({ userName })");
                        }
                        else
                        {
                            var moneyAfterPay = moneyLeft - decimal.Parse(currentMessage.Money);
                            SaveRecord();
                            SendNotificationForError(
                                "Cộng tiền thành công",
                                $"{Constant.BANHKEO.ToUpper()} : Đã + { helper.GetMoneyFormat(currentMessage.Money) } { currentMessage.Web }{ currentMessage.Account } ({ userName }), SD: { helper.GetMoneyFormat(moneyAfterPay.ToString()) } ");
                        }

                        data.Remove(currentMessage);
                        if (data.Count == 0)
                        {
                            process = "Finish";
                            break;
                        }
                        process = "OpenWeb";
                        break;

                    case "Finish":
                        isFinishProcess = true;
                        break;
                    }
                } while (!isFinishProcess);
            }
            catch (Exception ex)
            {
                isFinishProcess = true;
                if (ex.Message.Contains("Lỗi không có kết nối internet"))
                {
                    DialogResult dialog = MessageBox.Show("Hãy kiểm tra internet và thử lại."
                                                          , "Mất kết nối internet", MessageBoxButtons.OK);
                    if (dialog == DialogResult.OK)
                    {
                        Application.ExitThread();
                    }
                }

                SendNotificationForError(
                    "Lỗi không xác định",
                    $"{web_name} : {ex.Message}");
            }

            return;
        }
Exemple #54
0
 public static void ToProjectListPage(this IStackNavigationService navigationService, AccountData account) => navigationService.NavigateTo(nameof(ProjectListPage), account);
    // Edit or Create a new instance
    public override void DrawEditor(Rect box, bool newInstance)
    {
        // Setup the layout
        Rect pos = box;
        pos.x += ImagePack.innerMargin;
        pos.y += ImagePack.innerMargin;
        pos.width -= ImagePack.innerMargin;
        pos.height = ImagePack.fieldHeight;

        // Draw the content database info
        if (newInstance) {
            ImagePack.DrawLabel (pos.x, pos.y, "Create a new account");
            pos.y += ImagePack.fieldHeight;
        }
        ImagePack.DrawText(pos, "Username: "******"Status:", status, AccountData.statusOptions);
        editingDisplay.status = AccountData.statusValues[status];

        // Save Instance data
        pos.x -= ImagePack.innerMargin;
        pos.y += 1.4f * ImagePack.fieldHeight;
        pos.width /= 3;
        if (!newInstance) {
            if (ImagePack.DrawButton (pos.x, pos.y, "Save Data")) {
            if (newInstance)
                InsertEntry ();
            else
                UpdateEntry ();

            state = State.Loaded;
            }
            // Cancel editing
            pos.x += pos.width;
            if (ImagePack.DrawButton (pos.x, pos.y, "Cancel")) {
                editingDisplay = originalDisplay.Clone ();
                if (newInstance)
                    state = State.New;
                else
                    state = State.Loaded;
            }
        }

        if (resultTimeout != -1 && resultTimeout > Time.realtimeSinceStartup) {
            pos.y += ImagePack.fieldHeight;
            ImagePack.DrawText(pos, result);
        }
    }
 static AccountRecord ToAccountRecord(AccountData accountData)
 {
     return(new AccountRecord(accountData.Id, accountData.Username, accountData.Password,
                              accountData.Nickname, (sbyte)accountData.Role, accountData.Banned,
                              accountData.CharacterSlots, accountData.LastSelectedServerId));
 }
Exemple #57
0
 public AccountAnswerMessage(AccountData account)
 {
     Account = account;
 }
        async Task StartProcess()
        {
            try
            {
                documentComplete = new WebBrowserDocumentCompletedEventHandler((s, e) =>
                {
                    if (webLayout.DocumentText.Contains("res://ieframe.dll"))
                    {
                        tcs.SetException(new Exception("Lỗi không có kết nối internet"));
                        return;
                    }
                    if (!tcs.Task.IsCompleted)
                    {
                        webLayout.DocumentCompleted -= documentComplete;
                        tcs.SetResult(v);
                    }
                });
                isFinishProcess = false;
                AccountData userAccount  = new AccountData();
                var         adminAccount = new AdminAccount();

                var process = checkAccountAdmin(ref adminAccount);
                do
                {
                    switch (process)
                    {
                    case "OpenWeb":
                        CreateSyncTask();
                        webLayout.Navigate(url);
                        await tcs.Task;
                        await Task.Delay(5000);

                        process = "Login";
                        if (webLayout.Url.ToString() == user_URL)
                        {
                            process = "AccessToDaily";
                            break;
                        }

                        if (webLayout.Url.ToString() != index_URL)
                        {
                            SendNotificationForError(
                                "Trang Web Không Truy Cập Được",
                                $"{web_name} không thể truy cập");

                            process = "Finish";
                            break;
                        }

                        break;

                    case "Login":
                        CreateSyncTask();
                        Login(adminAccount);
                        await tcs.Task;
                        await Task.Delay(5000);

                        if (webLayout.Url.ToString() == index_URL)
                        {
                            if (!Globals.isSentNotification_HL)
                            {
                                Globals.isSentNotification_HL = true;
                                SendNotificationForError("Account Admin Đăng Nhập Lỗi",
                                                         $"{web_name} : Account admin đăng nhập web bị lỗi");
                            }
                            process = "Finish";
                            break;
                        }
                        Globals.isSentNotification_HL = false;
                        process = "AccessToDaily";
                        break;

                    case "AccessToDaily":
                        CreateSyncTask();
                        AccessToDaily();
                        await tcs.Task;
                        await Task.Delay(5000);

                        if (webLayout.Url.ToString() != agencies_URL)
                        {
                            SendNotificationForError(
                                "Truy cập vào đại lý bị lỗi",
                                $"{web_name} : Trang đại lý bị lỗi");
                            process = "Finish";
                            break;
                        }

                        process = "AccessAddUser";
                        break;

                    case "AccessAddUser":
                        CreateSyncTask();
                        AccessToAddUser();
                        await tcs.Task;
                        await Task.Delay(5000);

                        if (webLayout.Url.ToString() != addUser_URL)
                        {
                            SendNotificationForError(
                                "Truy cập vào thêm user bị lỗi",
                                $"{web_name} : Trang thêm user bị lỗi");
                            process = "Finish";
                            break;
                        }

                        process = "AddUser";
                        break;

                    case "AddUser":
                        FillInUserInfor();
                        await Task.Delay(5000);

                        AddUser();
                        await tcs.Task;
                        await Task.Delay(5000);

                        var errorFromServerPhp = UpdateUserStatus();
                        if (!webLayout.Url.ToString().Contains(agencies_URL))
                        {
                            var errorFromCreation = GetErrorFromCreation();
                            var errorMessage      = $"Tạo user { data.WebId + data.IdNumber } bị lỗi";
                            SendNotificationForError(
                                "Tạo user không thành công",
                                (!string.IsNullOrEmpty(errorFromServerPhp) ? $"Có lỗi update từ server php {errorFromServerPhp}" + Environment.NewLine : string.Empty) +
                                $"{Constant.HANHLANG.ToUpper()} : user { data.WebId + data.IdNumber } lỗi {errorFromCreation}");
                        }
                        else
                        {
                            SendNotificationForError(
                                $"Tạo user thành công cho web {Constant.HANHLANG.ToUpper()}",
                                (!string.IsNullOrEmpty(errorFromServerPhp) ? $"Tạo thành công nhưng có lỗi update từ server php {errorFromServerPhp}" + Environment.NewLine : string.Empty) +
                                $"Thông tin:" + Environment.NewLine +
                                $"Họ tên: {data.Name}" + Environment.NewLine +
                                $"Sdt: {data.Phone}" + Environment.NewLine +
                                $"Tên web: {Constant.HANHLANG.ToUpper()} ({data.WebId})" + Environment.NewLine +
                                $"Link web: {url}" + Environment.NewLine +
                                $"Tk({data.GetLevel()}): {data.WebId + data.IdNumber}" + Environment.NewLine +
                                $"Mk: {data.Password}" + Environment.NewLine +
                                $"Nội dung chuyển khoản nạp số dư: {data.WebId + data.IdNumber}" + Environment.NewLine +
                                $"STK VPBank: 97229748 - PHAN MINH CHÂU" + Environment.NewLine +
                                $"(ACE lưu ý chọn chuyển nhanh 24 / 7 & chuyển khoản đúng nội dung quy định sẽ được tự động cộng vào tài khoản trong 3p.Trường hợp chuyển khoản sai xử lý vào cuối ngày)" + Environment.NewLine +
                                $"Cần liên hệ ACE liên hệ Zalo 0981 694 994");
                        }
                        process = "Finish";
                        break;

                    case "Finish":
                        isFinishProcess = true;
                        registerAccountForm.Dispose();
                        break;
                    }
                } while (!isFinishProcess);
            }
            catch (Exception ex)
            {
                isFinishProcess = true;
                if (ex.Message.Contains("Lỗi không có kết nối internet"))
                {
                    DialogResult dialog = MessageBox.Show("Hãy kiểm tra internet và thử lại."
                                                          , "Mất kết nối internet", MessageBoxButtons.OK);
                    if (dialog == DialogResult.OK)
                    {
                        Application.ExitThread();
                    }
                }

                SendNotificationForError(
                    "Lỗi không xác định",
                    $"{web_name} : {ex.Message}");
            }

            return;
        }
Exemple #59
0
        public static void PacketReceived(Server sender, Packet packet)
        {
            //Program.frm1.AddLog("(C - S)  " + packet.ToString());

            Player player = Players.Find(sender);
            for (int i = 0; i < 3; i++)
            {
                if (player != null)
                    break;
                Thread.Sleep(100);
                player = Players.Find(sender);
            }

            if (player == null)
                sender.Kick();

            if (player.CharName != "")
                Program.frm1.AddLog(player.CharName + " : (C - S)  " + packet.ToString());
            else
                Program.frm1.AddLog(player.AccountName + " : (C - S)  " + packet.ToString());

            switch (packet.Opcode)
            {
                case 0x7FD4: // Login Request
                    {
                        player.AccountName = packet.ReadString(31);

                        AccountData AccData = new AccountData(player.AccountName);

                        Packet LoginResponse = new Packet(0x7FD2);
                        LoginResponse.WriteString(player.AccountName, 31);
                        LoginResponse.WriteString("test", 31);
                        sender.Send(LoginResponse);

                        LoginResponse = new Packet(0x0001);
                        LoginResponse.WriteUInt(2);

                        int z = AccData.Characters.Count;

                        while (z < 2)
                        {
                            //3rd Char
                            LoginResponse.WriteUInt(10);
                            for (int i = 0; i < 128; i++)
                                LoginResponse.WriteByte(0);
                            z++;
                        }

                        foreach (CharData x in AccData.Characters)
                        {
                            LoginResponse.WriteUInt(1);
                            LoginResponse.WriteString(x.Name, 17);
                            LoginResponse.WriteInt(Data.GetStyle(x.Gender, x.Nation, x.Face, x.Hair));

                            LoginResponse.WriteByte((byte)x.Job);//Job
                            LoginResponse.WriteByte(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteByte(x.Level); // level
                            LoginResponse.WriteUShort(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(0).Model); // top
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(1).Model); // bottom
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(2).Model);// right hand weapon
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(3).Model);// left hand weapon
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(4).Model); // hat
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(5).Model); // wing & suit
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(6).Model); // Gauntlet
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(7).Model); // boot
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(8).Model); // 1st Necklace
                            LoginResponse.WriteUInt(x.ClothesItems.FindSlot(9).Model); // 2nd Necklace
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUInt(0);
                            LoginResponse.WriteUShort(0);
                        }

                        sender.Send(LoginResponse);
                    }
                    break;

                case 0x0002:
                    {
                        packet.ReadInt();
                        string  CharName = packet.ReadString(17);
                        int nStyle = packet.ReadInt();

                        CharData class_CharData = new CharData(player, player.AccountName, CharName);
                        class_CharData.Name = CharName;
                        class_CharData.Nation = Data.GetCharNation(nStyle);
                        class_CharData.Gender = Data.GetCharGender(nStyle);
                        class_CharData.Hair = Data.GetCharHair(nStyle, class_CharData.Nation, class_CharData.Gender);
                        class_CharData.Face = Data.GetCharFace(nStyle, class_CharData.Nation, class_CharData.Gender);

                        class_CharData.CreateCharData();//save character data to file.

                        Packet LoginResponse = new Packet(0x0003);
                        sender.Send(LoginResponse);

                    }
                    break;

                case 0x0004:
                    {
                        string CharName = packet.ReadString(17);
                        string FileName = "Accounts\\" + player.AccountName + "\\" + CharName;
                        if (File.Exists(FileName))
                            File.Delete(FileName);

                        Packet LoginResponse = new Packet(0x0005);
                        LoginResponse.WriteUInt(1);
                        LoginResponse.WriteUInt(1);
                        LoginResponse.WriteUInt(1);
                        LoginResponse.WriteUInt(1);
                        LoginResponse.WriteUInt(1);
                        LoginResponse.WriteUInt(1);
                        LoginResponse.WriteUInt(1);
                        LoginResponse.WriteUInt(1);
                        sender.Send(LoginResponse);

                    }
                    break;

                case 0x0010:
                    {
                        player.CharName = packet.ReadString(17);
                        Packet LoginResponse = new Packet(0x0013);
                        LoginResponse.WriteUInt(1);
                        sender.Send(LoginResponse);
                    }
                    break;

                case 0x0014:
                    player.SendCharData();
                    break;

                case 0x0124:
                    Packets.Movement.UpdatePosition(packet, player);
                    break;

                case 0x0121:
                    Packets.Movement.BeginMove(packet, player);
                    break;

                case 0x0453:
                    Packets.ItemControl.ChangeSlot(packet, player);
                    break;

                case 0x0411:
                    Packets.ItemControl.Equip(packet, player);
                    break;

                case 0x0415:
                    Packets.ItemControl.TakeOff(packet, player);
                    break;

                case 0x0229:
                    Packets.Communication.Expressing(packet, player);
                    break;

                case 0x7E02:
                    Packets.Msngr.MemberInsert(packet, player);
                    break;

                case 0x0710:
                    Packets.Party.PartyRequest(packet, player);
                    break;

                case 0x0801:
                    Packets.PVP.Open(packet, player);
                    break;

                case 0x0807:
                    Packets.PVP.Close(packet, player);
                    break;

                case 0x0808:
                    Packets.PVP.CreateRoom(packet, player);
                    break;

                case 0x0816:
                    Packets.PVP.ExitRoom(packet, player);
                    break;

                case 0x0471:
                    Packets.Movement.RideHorse(packet, player);
                    break;

                case 0x0133:
                    {
                        int MapIndex = Maps.MapsData.Find(player.CharData.Map);
                        if (MapIndex != -1)
                            Maps.AddPlayer(player, Maps.MapsData[MapIndex]);
                    }
                    break;

                case 0x0222:
                    Packets.Chatting.Whisper(packet, player);
                    break;

                case 0x0220:
                    {
                        byte Length = packet.ReadByte();
                        string Text = packet.ReadString(Length);

                        if (!player.CharData.isInPVP)
                        {
                            int MapIndex = Maps.MapsData.Find(player.CharData.Map);
                            foreach (Player x in Maps.MapsData[MapIndex].Players)
                            {
                                Packet newPacket = new Packet(0x0221);
                                newPacket.WriteUInt(player.ID);
                                newPacket.WriteString(player.CharData.Name, 17);
                                newPacket.WriteByte(0);
                                newPacket.WriteByte(Length);
                                newPacket.WriteString(Text, Length);
                                x.Sock.Send(newPacket);
                            }
                        }
                        else
                        {
                            foreach (Player x in Packets.PVP.Players)
                            {
                                Packet newPacket = new Packet(0x0221);
                                newPacket.WriteUInt(player.ID);
                                newPacket.WriteString(player.CharData.Name, 17);
                                newPacket.WriteByte(63);
                                newPacket.WriteByte(Length);
                                newPacket.WriteString(Text, Length);
                                x.Sock.Send(newPacket);
                            }
                        }
                    }
                    break;

                #region DropEld
                case 0x0406:
                    {
                        byte Result = 0;

                        uint Dropped = packet.ReadUInt();
                        if (player.CharData.Gold >= Dropped)
                        {
                            player.CharData.Gold -= Dropped;
                            Result = 1;
                        }

                        Packet Response = new Packet(0x0407);
                        Response.WriteByte(Result);
                        Response.WriteUInt(player.CharData.Gold);
                        player.Sock.Send(Response);
                    }
                    break;
                #endregion
            }
        }
        private List <Position> BuildPositions(string acctName, HugoDataSet.PortfolioDataTable portfolio, List <Index> indices, Index totalRow, AccountData accountData, bool bPositionsForAllAccounts, ref int unsubscribedSymbols)
        {
            List <Position> positions = new List <Position>();

            try
            {
                unsubscribedSymbols += BuildPositionsForAccount(portfolio, indices, totalRow, accountData, positions);

                if (bPositionsForAllAccounts)
                {
                    foreach (AccountPortfolio account in m_positionMonitor.GetAllAccountPortfolios())
                    {
                        if (account.AccountName != acctName)
                        {
                            unsubscribedSymbols += BuildPositionsForAccount(account.Portfolio, null, null, null, positions);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportError("Error building positions", ex);
            }
            return(positions);
        }