Beispiel #1
0
        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
            string username = UserName.Text;
            string password = Password.Text;

            System.Diagnostics.Trace.WriteLine(username + " start to register");

            var accountManager = new AccountManager();

            var ftpAccount = accountManager.AddAccount(username, password);

            if (ftpAccount == null)
            {
                ErrorMessage.Text = "该用户名已被使用";
                return;
            }

            System.Diagnostics.Trace.WriteLine(username + " registered");

            FormsAuthentication.SetAuthCookie(username, false /* createPersistentCookie */);

            string continueUrl = Request.QueryString["ReturnUrl"];
            if (String.IsNullOrEmpty(continueUrl))
            {
                continueUrl = "~/";
            }
            Response.Redirect(continueUrl);
        }
Beispiel #2
0
 public LoginServer(string ipAddress, int port)
     : base(ipAddress, port)
 {
     worldManager = new WorldManager(ConfigurationManager.ConnectionStrings["XiahDb"].ConnectionString, ConfigurationManager.ConnectionStrings["XiahDb"].ProviderName);
     accountManager = new AccountManager(ConfigurationManager.ConnectionStrings["XiahDb"].ConnectionString, ConfigurationManager.ConnectionStrings["XiahDb"].ProviderName);
     InitiateWorlds();
 }
    protected void btnAddAccountingPlan_Click(object sender, EventArgs e)
    {
        accountManager = new AccountManager(this);
        accountingPlan = new AccountingPlan();

        if (String.IsNullOrEmpty(cboTreeAccountingPlan.SelectedValue))
        {
            ShowError("Selecione um plano de contas pai!");
            return;
        }

        if (treAccountingPlan.SelectedNode != null)
        {
            AccountingPlan original_accountingPlan = accountManager.GetAccountingPlan(Company.CompanyId,Convert.ToInt32(treAccountingPlan.SelectedValue));
            
            accountingPlan.CopyPropertiesFrom(original_accountingPlan);

            accountingPlan.Name = txtName.Text.ToUpper();

            accountingPlan.ParentId = Convert.ToInt32(cboTreeAccountingPlan.SelectedValue);

            accountManager.UpdateAccountingPlan(original_accountingPlan, accountingPlan);
        }
        else
        {
            accountingPlan.CompanyId = Company.CompanyId;
            accountingPlan.Name = txtName.Text.ToUpper();

            accountingPlan.ParentId = Convert.ToInt32(cboTreeAccountingPlan.SelectedValue);

            accountManager.InsertAccountingPlan(accountingPlan);
        }
        BindTree();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        accountManager = new AccountManager(this);
        account = new Account();

        if (!String.IsNullOrEmpty(Request["AccountId"]))
        {
            originalAccount = accountManager.GetAccount(Convert.ToInt32(Page.ViewState["AccountId"]), Company.CompanyId);
            account.CopyPropertiesFrom(originalAccount);
        }

        account.CompanyId = Company.CompanyId;
        account.BankId = Convert.ToInt32(cboBank.SelectedValue);
        account.AccountNumber = txtAccountNumber.Text;
        account.Agency = txtAgency.Text;
        account.AgencyMail = txtAgencyMail.Text;
        account.AgencyManager = txtAgencyManager.Text;
        account.AgencyPhone = txtAgencyPhone.Text;

        account.PostalCode = ucAddress.PostalCode;
        account.AddressComp = ucAddress.AddressComp;
        account.AddressNumber = ucAddress.AddressNumber;

        if (!String.IsNullOrEmpty(Request["AccountId"]))
            accountManager.Update(originalAccount, account);
        else
            accountManager.Insert(account);

        Response.Redirect("Accounts.aspx");

    }
Beispiel #5
0
        public ActionResult Logout()
        {
            var manager = new AccountManager();
            manager.Logout();

            return RedirectToAction("Login");
        }
    protected void btnAddCostCenter_Click(object sender, EventArgs e)
    {
        accountManager = new AccountManager(this);
        costCenter = new CostCenter();

        if (treCostCenter.SelectedNode != null)
        {
            CostCenter original_costCenter = accountManager.GetCostCenter(Convert.ToInt32(treCostCenter.SelectedNode.Value));
            costCenter.CopyPropertiesFrom(original_costCenter);

            if (!String.IsNullOrEmpty(cboTreeCostCenters.SelectedValue))
                costCenter.ParentId = Convert.ToInt32(cboTreeCostCenters.SelectedValue);
            else
                costCenter.ParentId = null;

            costCenter.Name = txtName.Text;
            accountManager.UpdateCostCenter(original_costCenter, costCenter);
        }
        else
        {
            costCenter.CompanyId = Company.CompanyId;
            costCenter.Name = txtName.Text;

            if (!String.IsNullOrEmpty(cboTreeCostCenters.SelectedValue))
                costCenter.ParentId = Convert.ToInt32(cboTreeCostCenters.SelectedValue);
            else
                costCenter.ParentId = null;

            accountManager.InsertCostCenter(costCenter);
        }

        BindTree();
    }
    protected override void OnDataBinding(EventArgs e)
    {
        base.OnDataBinding(e);

        AccountManager manager = new AccountManager(this);
        DataTable table = manager.GetAccountingPlan(Page.Company.CompanyId);
        treeAcountingPlan.DataSource = table;
    }
 public ChannelServer(string ipAddress, int port)
     : base(ipAddress, port)
 {
     gameEngine = new GameEngine();
     mapEngine = new MapEngine(ConfigurationManager.ConnectionStrings["XiahDb"].ConnectionString, ConfigurationManager.ConnectionStrings["XiahDb"].ProviderName);
     accountManager = new AccountManager(ConfigurationManager.ConnectionStrings["XiahDb"].ConnectionString, ConfigurationManager.ConnectionStrings["XiahDb"].ProviderName);
     characterManager = new CharacterManager(ConfigurationManager.ConnectionStrings["XiahDb"].ConnectionString, ConfigurationManager.ConnectionStrings["XiahDb"].ProviderName);
     itemDataManager = new ItemDataManager(ConfigurationManager.ConnectionStrings["XiahDb"].ConnectionString, ConfigurationManager.ConnectionStrings["XiahDb"].ProviderName);
 }
Beispiel #9
0
 public BotClient()
 {
     AccountManager = new AccountManager("Accounts");
     PokemonEvolver = new PokemonEvolver(this);
     MoveTeacher = new MoveTeacher(this);
     StaffAvoider = new StaffAvoider(this);
     AutoReconnector = new AutoReconnector(this);
     MovementResynchronizer = new MovementResynchronizer(this);
     Rand = new Random();
 }
 //This method meets the tree with the plans of accounts
 public void BindTree()
 {
     accountManager = new AccountManager(this);
     DataTable table = accountManager.GetAccountingPlan(Company.CompanyId);
     treAccountingPlan.DataSource = table;
     treAccountingPlan.DataBind();
     treAccountingPlan.ExpandAllNodes();
     cboTreeAccountingPlan.SelectedValue = "";
     txtName.Text = "";
 }
Beispiel #11
0
	void Awake()
	{
		if (Instance != null && Instance != this)
		{
			Destroy(gameObject);
		}
		Instance = this;
		// Furthermore we make sure that we don't destroy between scenes (this is optional)
		DontDestroyOnLoad(gameObject);
	}
        public ActionResult CreateAccount(string username, string password, string firstName, string surname)
        {
            var account = new AccountManager();
            var user = new User(username, password, firstName, surname);

            account.CreateNewUserAccount(user);

            //var createdAccountModel = new CreatedAccountModel(userAccount, "Successfully Created");

            return View("Index");
        }
    public void BindTree()
    {
        accountManager = new AccountManager(this);
        treCostCenter.DataSource = accountManager.GetCostsCenterAsDataTable(Company.CompanyId);

        treCostCenter.DataBind();
        treCostCenter.ExpandAllNodes();
        txtName.Text = String.Empty;
        cboTreeCostCenters.SelectedValue = String.Empty;

    }
        // Methods
        public LoginWindow()
        {
            this.accountManager = new AccountManager();
            this.LoginResult = false;
            base.Loaded += new RoutedEventHandler(this.LoginWindow_Loaded);
            this.InitializeComponent();

            this.FillAccountInfo();
            App.Messenger.LoginCompleted += new EventHandler<LoginEventArgs>(this.OnLogin);
            //QQHelper.SetLoginServer();
            LoginVerifyCode.Init(this, new LoginVerifyCode.NeedtoSavePasswordEventHandler(this.LoginVerifyCode_NeedtoSavePassword));
        }
Beispiel #15
0
 public AccountContext(
     IDbContext dbContext,
     IEmailService mailService,
     AccountManager accoutnManager,
     IBlobService blobService,
     IJobManager jobManager)
 {
     this.dbContext = dbContext;
     this.accountManager = accoutnManager;
     this.blobService = blobService;
     this.jobManager = jobManager;
     this.mailService = mailService;
 }
Beispiel #16
0
        /// <summary>
        ///     Initializes a new instance of the Server class.
        /// </summary>
        /// <param name="name">Server name.</param>
        /// <param name="speed">Server speed.</param>
        /// <param name="address">Server url address.</param>
        public Server(string name, int speed, string address)
        {
            Name = name;
            Speed = speed;
            Address = address;
            ClientManager = new ClientManager(this);
            AccountManager = new AccountManager();
            PlayerManager = new PlayerManager(this);
            VillageManager = new VillageManager(this);
            AllyManager = new AllyManager(this);

            ClientManager.NewClient += OnNewClientCreated;
        }
Beispiel #17
0
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel(AccountManager accountManagerModel)
        {
            _selectedAccountIndex = -1;
            _isAccountSelectorMode = false;
            _noSelectableAccount = false;
            _accountManagerModel = accountManagerModel;
            Accounts = new ObservableCollection<AccountViewModel>();
            Pages = new ObservableCollection<AccountViewModel>();
            Pages.Add(null);

            _accountManagerModel.Initialized += _accountManagerModel_Initialized;
            _accountManagerModel.Accounts.CollectionChanged += PageSwitcherViewModel_CollectionChanged;
            Initialize();
        }
        public ActionResult Login(string username, string password)
        {
            var accountManager = new AccountManager();
            var validUser = accountManager.ValidateUser(username, password);
            if (validUser == false)
            {
                ViewBag.Message = "Login Failed - no match for username & password you provided";
                return View("Index");
            }
            var cookie = new HttpCookie("UserId") { Value = username };
            Response.Cookies.Add(cookie);

            return RedirectToAction("DisplayAddressBook");
        }
 public static bool DeleteAccount(int accountId, int companyId)
 {
     bool result = true;
     using (AccountManager accountManager = new AccountManager(null))
     {
         try
         {
             accountManager.Delete(accountManager.GetAccount(accountId, companyId));
         }
         catch (System.Data.SqlClient.SqlException)
         {
             result = false;
         }
     }
     return result;
 }
Beispiel #20
0
        protected void FtpAccount_Login(object sender, EventArgs e)
        {
            string username = UserName.Text;
            string password = Password.Text;

            var accountManager = new AccountManager();
            bool loginSuccess = accountManager.CertificateAccount(username, password);
            if (!loginSuccess)
            {
                FailureText.Text = "登录失败,请确保用户名和密码输入正确";
                return;
            }

            FormsAuthentication.SetAuthCookie(username, false /* createPersistentCookie */);
            Response.Redirect("~/");
        }
    private void ShowAccount()
    {
        accountManager = new AccountManager(this);
        originalAccount = accountManager.GetAccount(Convert.ToInt32(Page.ViewState["AccountId"]), Company.CompanyId);
       
        cboBank.SelectedValue = Convert.ToString(originalAccount.BankId);        
        txtAccountNumber.Text = originalAccount.AccountNumber;
        txtAgency.Text = originalAccount.Agency;
        txtAgencyMail.Text = originalAccount.AgencyMail;
        txtAgencyManager.Text = originalAccount.AgencyManager;
        txtAgencyPhone.Text = originalAccount.AgencyPhone;

        ucAddress.PostalCode = originalAccount.PostalCode;
        ucAddress.AddressComp = originalAccount.AddressComp;
        ucAddress.AddressNumber = originalAccount.AddressNumber;

    }
Beispiel #22
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Please input the user name and password.");
                ViewBag.ReturnUrl = returnUrl;
                return View();
            }

            var manager = new AccountManager();
            if (manager.Login(model.UserName, model.Password, model.RememberMe))
                return Url.IsLocalUrl(returnUrl) ? Redirect(returnUrl) : RedirectToHome();

            ModelState.AddModelError("", "The user name and password is not matched.");
            ViewBag.ReturnUrl = returnUrl;

            return View();
        }
Beispiel #23
0
        public OrderRepository(
            IJobManager manager,
            SupportedOrderStore supportedOrderStore,
            AccountManager accountManager,
            IHRIDService hridService,
            IPaymentManager paymentManager,
            IVendorService vendorService
            )
        {
            this.manager = manager;
            this.supportedOrderStore = supportedOrderStore;
            this.accountManager = accountManager;
            this.hridService = hridService;
            this.vendorService = vendorService;

            orderCalculationService = new DefaultOrderCalculationService();
            serviceChargeCalculationService = new DefaultDeliveryServiceChargeCalculationService();
            paymentService = new PaymentService(paymentManager);
        }
    /// <summary>
    ///  This method calculates the possible cash of the company, cash that the company has in bank
    ///  and make the subtraction them
    /// </summary>
    private void CalculateBalance()
    {

        var accountManager = new AccountManager(this);

        //
        // Calculates the possible cash of the company
        //
        
        totalPossible = accountManager.GetParcelsValueFromInvoices(Company.CompanyId) - accountManager.GetParcelsValueFromBills(Company.CompanyId);

        //
        // Calculates the cash that the company has in bank
        //
        
        totalDone = (decimal)accountManager.GetSumConciliatedParcelsValueFromInvoices(Company.CompanyId) - (decimal)accountManager.GetSumConciliatedParcelsValueFromBills(Company.CompanyId);
        
        txtDone.Text = String.Format("{0:c}", totalDone); 
        txtPossible.Text = String.Format("{0:c}", totalPossible);
    }
        public ActionResult LogIn(string Email, string Password , string ReturnUrl)
        {
            ViewData["Exception"] = null;
            acMng = new AccountManager<Account>();
            if (!ModelState.IsValid)
            {
                return View();
            }
            try
            {
                AuthManager(acMng.CreateIdentity(Email, Password));

                return Redirect(Url.Action("Index", "WorkArea"));
            }
            catch (Exception ex)
            {
                ViewData["Exception"] = ex;
                return View(new Account());
            }
        }
    public static bool DeleteFinancierOperation(Int32 companyId, int financierOperationId)
    {
        bool result = true;
        using (AccountManager accountManager = new AccountManager(null))
        {
            try
            {
                accountManager.DeleteFinancierConditions(companyId, financierOperationId);
                accountManager.DeleteFinancierOperation(accountManager.GetFinancierOperation(companyId, financierOperationId));
            }
            catch (System.Data.SqlClient.SqlException e)
            {

                result = false;
            }


        }
        return result;
    }
Beispiel #27
0
    protected void loginToServer(object sender, EventArgs e)
    {
        try
        {
            AccountManager am = new AccountManager(account_url.Text);
            bool res = am.login(username.Text, password.Text);

            if (res == true)
            {
                Session["LCCSAccount"] = am;
                Response.Redirect("LCCSClient.aspx");
            }
            else
            {
                outputtext.Text = "login failed";
            }

        }
        catch (Exception ex)
        {
            LCCS.Utils.printException(ex);
            throw new Error(ex.Message);
        }
    }
Beispiel #28
0
        public void Execute()
        {
            AccountManager manager = AccountManagerFactory.Create();

            Console.Clear();
            Console.WriteLine("Add an Order");
            Console.WriteLine($"{Menu.stars}");

            // Validates user input and parses to DateTime
            do
            {
                // resets date
                Date.OrderDate = Convert.ToDateTime(EditOrDeleteOrderWorkflow.DATE_TIME_ORIGIN);

                try
                {
                    Date.OrderDate = DateTime.Parse(ConsoleInput.ConsoleInput.GetStringFromUser(Date.DatePrompt));
                }
                catch
                {
                    Console.WriteLine("Date must be a legitimate date in the future.");
                }
            } while (Date.OrderDate.Date.ToString() == EditOrDeleteOrderWorkflow.DATE_TIME_ORIGIN);

            Order order = new Order();

            // Validates Customer Name
            do
            {
                order.CustomerName = ConsoleInput.ConsoleInput.GetStringFromUser("Enter customer's name (a-z 0-9 , or . are excepted): ");
            } while (!(Regex.IsMatch(order.CustomerName, @"^[a-zA-Z0-9., ]+$")));

            // Validates State Abbreviation
            do
            {
                order.State = ConsoleInput.ConsoleInput.GetStringFromUser("Enter the state abbreviation (PA, OH, MI, or IN): ").ToUpper();
            } while (!(order.State == Taxes.statePA || order.State == Taxes.stateOH ||
                       order.State == Taxes.stateMI || order.State == Taxes.stateIN));

            // Validates Product Type
            do
            {
                order.ProductType = ConsoleInput.ConsoleInput.GetStringFromUser("Enter a product ( Carpet, Laminate, Tile, or Wood ): ");
            } while (!(order.ProductType.ToUpper() == Products.typeCarpet ||
                       order.ProductType.ToUpper() == Products.typeLaminate ||
                       order.ProductType.ToUpper() == Products.typeTile ||
                       order.ProductType.ToUpper() == Products.typeWood));

            // Validates Order Area
            order.Area = ConsoleInput.ConsoleInput.GetDecimalFromUser("Enter the area: ", Order.MIN_AREA, EditOrDeleteOrderWorkflow.MAX_INT);

            // Sends response to Data layer to add an order to an existing file or to create a new file and add it there
            AddEditOrDeleteOrderResponse response = manager.AddOrder(Date.OrderDate, order);

            if (response.Success)
            {
                ConsoleIO.DisplayOrderDetails(response.Order);
            }
            else
            {
                Console.WriteLine("An error occurred: ");
                Console.WriteLine(response.Message);
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Beispiel #29
0
 void Start()
 {
     acm = AccountManager.GetAccountManager();
 }
Beispiel #30
0
 public AccountApiController(AccountManager account)
 {
     _account = account;
 }
Beispiel #31
0
 void OnMainWindowClosing(object sender, CancelEventArgs e)
 {
     AccountManager.SaveAccounts();
 }
Beispiel #32
0
 private static void UpdateLocation()
 {
     s_scanIndex++;
     if (s_scanIndex == s_scanAreas.Count)
     {
         s_scanIndex = 0;
         PokewatchLogger.Log("[!]All Regions Scanned. Starting over.", AccountManager.GetAccountName(s_account));
     }
     if (s_currentScan == null || s_currentScan.Name != s_scanAreas[s_scanIndex].Name)
     {
         PokewatchLogger.Log("[!]Scanning new region: " + s_scanAreas[s_scanIndex].Name, AccountManager.GetAccountName(s_account));
     }
     s_currentScan = s_scanAreas[s_scanIndex];
     SetLocation(s_currentScan.Location);
 }
Beispiel #33
0
 public void CleanUp()
 {
     target = null;
     saving = null;
 }
Beispiel #34
0
        //Sign in to Twitter.
        private static bool PrepareTwitterClient()
        {
            if (s_config.TwitterConsumerToken.IsNullOrEmpty() || s_config.TwitterConsumerSecret.IsNullOrEmpty() ||
                s_config.TwitterAccessToken.IsNullOrEmpty() || s_config.TwitterConsumerSecret.IsNullOrEmpty())
            {
                PokewatchLogger.Log("[-]Must supply Twitter OAuth strings.", AccountManager.GetAccountName(s_account));
                return(false);
            }

            PokewatchLogger.Log("[!]Signing in to Twitter.", AccountManager.GetAccountName(s_account));
            var userCredentials = Auth.CreateCredentials(s_config.TwitterConsumerToken, s_config.TwitterConsumerSecret, s_config.TwitterAccessToken, s_config.TwitterAccessSecret);

            ExceptionHandler.SwallowWebExceptions = false;
            try
            {
                s_twitterClient = User.GetAuthenticatedUser(userCredentials);
            }
            catch (Exception ex)
            {
                PokewatchLogger.Log("[-]Unable to authenticate Twitter account." + ex, AccountManager.GetAccountName(s_account));
                return(false);
            }
            return(true);
        }
Beispiel #35
0
        public static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                PokewatchLogger.Log("[-]Missing Arguments. Indeces of account and regions must be specified.", "PokewatchUnknown");
                Environment.Exit(2);
            }
            s_config = ConfigurationManager.ReadConfiguration("Pokewatch");
            if (s_config == null)
            {
                Environment.Exit(2);
            }
            try
            {
                s_account = s_config.PoGoAccounts[int.Parse(args[0])];
                for (int i = 1; i < args.Length; i++)
                {
                    s_regions.Add(s_config.Regions[int.Parse(args[i])]);
                }
            }
            catch
            {
                PokewatchLogger.Log("[-]Arguments do not align with provided configuration: " + string.Join(" ", args), "PokewatchUnknown");
                Environment.Exit(2);
            }

            try
            {
                s_scanAreas = s_regions.SelectMany(r => r.Locations.Select(l => new ScanArea
                {
                    Location   = l,
                    Name       = r.Name,
                    Prefix     = r.Prefix,
                    Suffix     = r.Suffix,
                    Inclusions = r.Inclusions,
                    Exclusions = r.Exclusions
                })).ToList();
                s_currentScan = s_scanAreas.First();
                s_scanIndex   = 0;
            }
            catch
            {
                PokewatchLogger.Log("[-]Invalid Region Configuration", AccountManager.GetAccountName(s_account));
                Environment.Exit(2);
            }

            Console.Title = AccountManager.GetAccountName(s_account) + ": " + string.Join(", ", s_regions.Select(r => r.Name));

            s_pogoSession = AccountManager.SignIn(s_account, s_currentScan.Location);
            if (s_pogoSession == null)
            {
                PokewatchLogger.Log("[-]Unable to sign in to PokemonGo.", AccountManager.GetAccountName(s_account));
                Environment.Exit(3);
            }

            if (!PrepareTwitterClient())
            {
                Environment.Exit(4);
            }

            PokewatchLogger.Log("[+]Sucessfully signed in to twitter.", AccountManager.GetAccountName(s_account));

            s_pogoSession.Startup();

            s_pogoSession.AccessTokenUpdated += (sender, eventArgs) =>
            {
                PokewatchLogger.Log("[+]Access token updated.", AccountManager.GetAccountName(s_account));
            };

            s_pogoSession.Map.Update += (sender, eventArgs) =>
            {
                PokewatchLogger.Log("[+]Location Acknowleged. Searching...", AccountManager.GetAccountName(s_account));
                if (Search())
                {
                    UpdateLocation();
                }
            };

            Console.CancelKeyPress += (sender, eArgs) => {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            QuitEvent.WaitOne();
        }
Beispiel #36
0
        protected override async Task OnInitializeAsync(IActivatedEventArgs args)
        {
#if DEBUG
            if (_DEBUG_XBOX_RESOURCE)
#else
            if (Helpers.DeviceTypeHelper.IsXbox)
#endif
            {
                this.Resources.MergedDictionaries.Add(new ResourceDictionary()
                {
                    Source = new Uri("ms-appx:///Styles/TVSafeColor.xaml")
                });
                this.Resources.MergedDictionaries.Add(new ResourceDictionary()
                {
                    Source = new Uri("ms-appx:///Styles/TVStyle.xaml")
                });
            }



            Resources.Add("TitleBarCustomized", IsTitleBarCustomized);
            Resources.Add("TitleBarDummyHeight", IsTitleBarCustomized ? 32.0 : 0.0);

            if (IsTitleBarCustomized)
            {
                var coreApp = CoreApplication.GetCurrentView();
                coreApp.TitleBar.ExtendViewIntoTitleBar = true;

                var appView = ApplicationView.GetForCurrentView();
                appView.TitleBar.ButtonBackgroundColor         = Colors.Transparent;
                appView.TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
                appView.TitleBar.ButtonInactiveForegroundColor = Colors.Transparent;

                if (RequestedTheme == ApplicationTheme.Light)
                {
                    appView.TitleBar.ButtonForegroundColor      = Colors.Black;
                    appView.TitleBar.ButtonHoverBackgroundColor = Colors.DarkGray;
                    appView.TitleBar.ButtonHoverForegroundColor = Colors.Black;
                }
            }


            Microsoft.Toolkit.Uwp.UI.ImageCache.Instance.CacheDuration = TimeSpan.FromHours(24);

            // TwitterAPIの初期化
//			await TwitterHelper.Initialize();

            await RegisterTypes();

#if DEBUG
            Views.UINavigationManager.Pressed += UINavigationManager_Pressed;
#endif

            // ウィンドウサイズの保存と復元
            if (Helpers.DeviceTypeHelper.IsDesktop)
            {
                var localObjectStorageHelper = Container.Resolve <Microsoft.Toolkit.Uwp.Helpers.LocalObjectStorageHelper>();
                if (localObjectStorageHelper.KeyExists(HohoemaViewManager.primary_view_size))
                {
                    var view = ApplicationView.GetForCurrentView();
                    MainViewId      = view.Id;
                    _PrevWindowSize = localObjectStorageHelper.Read <Size>(HohoemaViewManager.primary_view_size);
                    view.TryResizeView(_PrevWindowSize);
                    ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto;
                }
            }


            var localStorge = Container.Resolve <Microsoft.Toolkit.Uwp.Helpers.LocalObjectStorageHelper>();


            var pageManager = Container.Resolve <PageManager>();
            var hohoemaApp  = Container.Resolve <HohoemaApp>();

            try
            {
                await hohoemaApp.InitializeAsync().ConfigureAwait(false);
            }
            catch
            {
                Debug.WriteLine("HohoemaAppの初期化に失敗");
            }


#if false
            try
            {
                if (localStorge.Read(IS_COMPLETE_INTRODUCTION, false) == false)
                {
                    // アプリのイントロダクションを開始
                    pageManager.OpenIntroductionPage();
                }
                else
                {
                    pageManager.OpenStartupPage();
                }
            }
            catch
            {
                Debug.WriteLine("イントロダクションまたはスタートアップのページ表示に失敗");
                pageManager.OpenPage(HohoemaPageType.RankingCategoryList);
            }
#else
            try
            {
                pageManager.OpenStartupPage();
            }
            catch
            {
                Debug.WriteLine("スタートアップのページ表示に失敗");
                pageManager.OpenPage(HohoemaPageType.RankingCategoryList);
            }
#endif



            try
            {
                // ログインを試行
                if (!hohoemaApp.IsLoggedIn && AccountManager.HasPrimaryAccount())
                {
                    // サインイン処理の待ちを初期化内でしないことで初期画面表示を早める
                    hohoemaApp.SignInWithPrimaryAccount();
                }
            }
            catch
            {
                Debug.WriteLine("ログイン処理に失敗");
            }

            await base.OnInitializeAsync(args);
        }
Beispiel #37
0
        protected override async Task OnActivateApplicationAsync(IActivatedEventArgs args)
        {
            var pageManager = Container.Resolve <PageManager>();
            var hohoemaApp  = Container.Resolve <HohoemaApp>();

            try
            {
                if (!hohoemaApp.IsLoggedIn && AccountManager.HasPrimaryAccount())
                {
                    await hohoemaApp.SignInWithPrimaryAccount();
                }
            }
            catch { }

            // ログインしていない場合、
            bool isNeedNavigationDefault = !hohoemaApp.IsLoggedIn;

            try
            {
                if (args.Kind == ActivationKind.ToastNotification)
                {
                    //Get the pre-defined arguments and user inputs from the eventargs;
                    var toastArgs = args as IActivatedEventArgs as ToastNotificationActivatedEventArgs;
                    var arguments = toastArgs.Argument;


                    if (arguments == ACTIVATION_WITH_ERROR)
                    {
                        await ShowErrorLog().ConfigureAwait(false);
                    }
                    else if (arguments.StartsWith("cache_cancel"))
                    {
                        var query  = arguments.Split('?')[1];
                        var decode = new WwwFormUrlDecoder(query);

                        var videoId = decode.GetFirstValueByName("id");
                        var quality = (NicoVideoQuality)Enum.Parse(typeof(NicoVideoQuality), decode.GetFirstValueByName("quality"));

                        await hohoemaApp.CacheManager.CancelCacheRequest(videoId, quality);
                    }
                    else
                    {
                        var nicoContentId = Helpers.NicoVideoExtention.UrlToVideoId(arguments);

                        if (Mntone.Nico2.NiconicoRegex.IsVideoId(nicoContentId))
                        {
                            await PlayVideoFromExternal(nicoContentId);
                        }
                        else if (Mntone.Nico2.NiconicoRegex.IsLiveId(nicoContentId))
                        {
                            await PlayLiveVideoFromExternal(nicoContentId);
                        }
                    }
                }
                else if (args.Kind == ActivationKind.Protocol)
                {
                    var param = (args as IActivatedEventArgs) as ProtocolActivatedEventArgs;
                    var uri   = param.Uri;
                    var maybeNicoContentId = new string(uri.OriginalString.Skip("niconico://".Length).TakeWhile(x => x != '?' && x != '/').ToArray());


                    if (Mntone.Nico2.NiconicoRegex.IsVideoId(maybeNicoContentId) ||
                        maybeNicoContentId.All(x => x >= '0' && x <= '9'))
                    {
                        await PlayVideoFromExternal(maybeNicoContentId);
                    }
                    else if (Mntone.Nico2.NiconicoRegex.IsLiveId(maybeNicoContentId))
                    {
                        await PlayLiveVideoFromExternal(maybeNicoContentId);
                    }
                }
                else
                {
                    if (hohoemaApp.IsLoggedIn)
                    {
                        pageManager.OpenStartupPage();
                    }
                    else
                    {
                        pageManager.OpenPage(HohoemaPageType.RankingCategoryList);
                    }
                }
            }
            catch
            {
                /*
                 * if (!pageManager.NavigationService.CanGoBack())
                 * {
                 *  if (!hohoemaApp.IsLoggedIn && AccountManager.HasPrimaryAccount())
                 *  {
                 *      await hohoemaApp.SignInWithPrimaryAccount();
                 *
                 *      pageManager.OpenStartupPage();
                 *  }
                 *  else
                 *  {
                 *      pageManager.OpenPage(HohoemaPageType.Login);
                 *  }
                 * }
                 */
            }



            await base.OnActivateApplicationAsync(args);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (error != null)
            {
                Message = null;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, error.Message);
                error  = null;
                stream = null;
            }
            else if (streams == null)
            {
                if (!DA.GetDataTree(0, out GH_Structure <GH_SpeckleStream> ghStreamTree))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Could not convert object to Stream.");
                    Message = null;
                    return;
                }
                Message = "Fetching";
                if (ghStreamTree.DataCount == 0)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input S failed to collect data.");
                    return;
                }

                if (ghStreamTree.DataCount >= 20)
                {
                    tooManyItems = true;
                }

                Task.Run(async() =>
                {
                    try
                    {
                        int count = 0;
                        var tasks = new Dictionary <GH_Path, Task <Stream> >();

                        ghStreamTree.Paths.ToList().ForEach(path =>
                        {
                            if (count >= 20)
                            {
                                return;
                            }
                            var branch    = ghStreamTree[path];
                            var itemCount = 0;
                            branch.ForEach(item =>
                            {
                                if (item == null || count >= 20)
                                {
                                    itemCount++;
                                    return;
                                }
                                var account = item.Value.AccountId == null
                  ? AccountManager.GetDefaultAccount()
                  : AccountManager.GetAccounts().FirstOrDefault(a => a.userInfo.id == item.Value.AccountId);
                                if (account == null)
                                {
                                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Could not find default account in this machine. Use the Speckle Manager to add an account.");
                                    return;
                                }
                                var client = new Client(account);

                                var task = client.StreamGet(item.Value?.StreamId);
                                tasks[path.AppendElement(itemCount)] = task;
                                count++;
                                itemCount++;
                            });
                        });

                        var values         = await Task.WhenAll(tasks.Values);
                        var fetchedStreams = new Dictionary <GH_Path, Stream>();

                        for (int i = 0; i < tasks.Keys.ToList().Count; i++)
                        {
                            var key             = tasks.Keys.ToList()[i];
                            fetchedStreams[key] = values[i];
                        }

                        streams = fetchedStreams;
                    }
                    catch (Exception e)
                    {
                        error = e;
                    }
                    finally
                    {
                        Rhino.RhinoApp.InvokeOnUiThread((Action) delegate { ExpireSolution(true); });
                    }
                });
            }
            else
            {
                if (tooManyItems)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                      "Input data has too many items. Only the first 20 streams will be fetched.");
                    tooManyItems = false;
                }
                var id            = new GH_Structure <IGH_Goo>();
                var name          = new GH_Structure <IGH_Goo>();
                var description   = new GH_Structure <IGH_Goo>();
                var createdAt     = new GH_Structure <IGH_Goo>();
                var updatedAt     = new GH_Structure <IGH_Goo>();
                var isPublic      = new GH_Structure <GH_Boolean>();
                var collaborators = new GH_Structure <IGH_Goo>();
                var branches      = new GH_Structure <IGH_Goo>();

                streams.AsEnumerable()?.ToList().ForEach(pair =>
                {
                    id.Append(GH_Convert.ToGoo(pair.Value.id), pair.Key);
                    name.Append(GH_Convert.ToGoo(pair.Value.name), pair.Key);
                    description.Append(GH_Convert.ToGoo(pair.Value.description), pair.Key);
                    createdAt.Append(GH_Convert.ToGoo(pair.Value.createdAt), pair.Key);
                    updatedAt.Append(GH_Convert.ToGoo(pair.Value.updatedAt), pair.Key);
                    isPublic.Append(new GH_Boolean(pair.Value.isPublic), pair.Key);
                    collaborators.AppendRange(pair.Value.collaborators.Select(GH_Convert.ToGoo).ToList(), pair.Key);
                    branches.AppendRange(pair.Value.branches.items.Select(GH_Convert.ToGoo), pair.Key);
                });

                Message = "Done";
                DA.SetDataTree(0, id);
                DA.SetDataTree(1, name);
                DA.SetDataTree(2, description);
                DA.SetDataTree(3, createdAt);
                DA.SetDataTree(4, updatedAt);
                DA.SetDataTree(5, isPublic);
                DA.SetDataTree(6, collaborators);
                DA.SetDataTree(7, branches);
                streams = null;
            }
        }
 void LogoutAccount()
 {
     Destroy(account);
     account     = gameObject.AddComponent <AccountManager>();
     accountMenu = Menu.Login;
 }
Beispiel #40
0
        //Evaluate if a pokemon is worth tweeting about.
        private static FoundPokemon ProcessPokemon(WildPokemon pokemon, Queue <FoundPokemon> alreadyFound, DateTime lastTweet)
        {
            FoundPokemon foundPokemon = new FoundPokemon
            {
                Location = new Location {
                    Latitude = pokemon.Latitude, Longitude = pokemon.Longitude
                },
                Kind           = pokemon.PokemonData.PokemonId,
                LifeExpectancy = pokemon.TimeTillHiddenMs / 1000
            };

            if ((s_config.ExcludedPokemon.Contains(foundPokemon.Kind) && !(s_currentScan.Inclusions != null && s_currentScan.Inclusions.Contains(foundPokemon.Kind))) || (s_currentScan.Exclusions != null && s_currentScan.Exclusions.Contains(foundPokemon.Kind)))
            {
                PokewatchLogger.Log($"[!]Excluded: {foundPokemon.Kind} ({foundPokemon.LifeExpectancy} seconds): {Math.Round(foundPokemon.Location.Latitude, 6)},{Math.Round(foundPokemon.Location.Longitude, 6)}", AccountManager.GetAccountName(s_account));
                return(null);
            }

            if (foundPokemon.LifeExpectancy < s_config.MinimumLifeExpectancy || foundPokemon.LifeExpectancy > 1000)
            {
                PokewatchLogger.Log($"[!]Expiring: {foundPokemon.Kind} ({foundPokemon.LifeExpectancy} seconds): {Math.Round(foundPokemon.Location.Latitude, 6)},{Math.Round(foundPokemon.Location.Longitude, 6)}", AccountManager.GetAccountName(s_account));
                return(null);
            }

            if (alreadyFound.Contains(foundPokemon))
            {
                PokewatchLogger.Log($"[!]Duplicate: {foundPokemon.Kind} ({foundPokemon.LifeExpectancy} seconds): {Math.Round(foundPokemon.Location.Latitude, 6)},{Math.Round(foundPokemon.Location.Longitude, 6)}", AccountManager.GetAccountName(s_account));
                return(null);
            }

            if ((lastTweet + TimeSpan.FromSeconds(s_config.RateLimit) > DateTime.Now) && !s_config.PriorityPokemon.Contains(foundPokemon.Kind))
            {
                PokewatchLogger.Log($"[!]Limiting: {foundPokemon.Kind} ({foundPokemon.LifeExpectancy} seconds): {Math.Round(foundPokemon.Location.Latitude, 6)},{Math.Round(foundPokemon.Location.Longitude, 6)}", AccountManager.GetAccountName(s_account));
                return(null);
            }

            PokewatchLogger.Log($"[!]Tweeting: {foundPokemon.Kind} ({foundPokemon.LifeExpectancy} seconds): {Math.Round(foundPokemon.Location.Latitude, 6)},{Math.Round(foundPokemon.Location.Longitude, 6)}", AccountManager.GetAccountName(s_account));
            return(foundPokemon);
        }
Beispiel #41
0
        public void ClientQuestLogin()
        {
            // TODO: Remove duplicate profile code in this and QueryProfile endpoints.

            // Note: Quests are items in the 'athena' profile.

            string accountId = Request.Url.Segments[Request.Url.Segments.Length - 3].Replace("/", "");

            if (!AccountManager.AccountExists(accountId))
            {
                Response.StatusCode = 404;
                return;
            }

            var account = AccountManager.GetAccount(accountId);

            Query.TryGetValue("profileId", out string profileId);
            Query.TryGetValue("rvn", out string rvn);
            int revision = Convert.ToInt32(rvn ?? "-2");

            var items          = account.AthenaItems;
            var itemsFormatted = new Dictionary <string, object>();

            foreach (string item in items)
            {
                var itemGuid = item; // Makes life easier - config file doesn't store numbers anymore, and it can be read anywhere.
                itemsFormatted.Add(itemGuid, new
                {
                    templateId = item,
                    attributes = new
                    {
                        max_level_bonus = 0,
                        level           = account.Level,
                        item_seen       = 1,
                        xp       = 0,
                        variants = new List <object>(),
                        favorite = false
                    },
                    quantity = 1
                });
            }

            string[] dances = new string[6];
            for (int i = 0; i < dances.Length; i++)
            {
                dances[i] = account.EquippedItems["favorite_dance" + i];
            }

            var response = new
            {
                profileRevision            = 10,
                profileId                  = "athena",
                profileChangesBaseRevision = 8,
                profileChanges             = new List <object>
                {
                    new
                    {
                        changeType = "fullProfileUpdate",
                        profile    = new
                        {
                            _id        = accountId, // not really account id but idk
                            created    = DateTime.Now.AddDays(-7).ToDateTimeString(),
                            updated    = DateTime.Now.AddDays(-1).ToDateTimeString(),
                            rvn        = 10,
                            wipeNumber = 5,
                            accountId,
                            profileId = "athena",
                            version   = "fortnitemares_part4_fixup_oct_18",
                            items     = itemsFormatted,
                            stats     = new
                            {
                                attributes = new
                                {
                                    past_seasons         = new string[0],
                                    season_match_boost   = 1000,
                                    favorite_victorypose = "",
                                    mfa_reward_claimed   = false,
                                    quest_manager        = new
                                    {
                                        dailyLoginInterval = DateTime.Now.AddDays(1).ToDateTimeString(),
                                        dailyQuestRerolls  = 1
                                    },
                                    book_level = account.PassLevel,
                                    season_num = ApiConfig.Current.Season,
                                    favorite_consumableemote = "",
                                    banner_color             = "defaultcolor1",
                                    favorite_callingcard     = "",
                                    favorite_character       = account.EquippedItems["favorite_character"],
                                    favorite_spray           = new string[0],
                                    book_xp = account.PassXP,
                                    favorite_loadingscreen = account.EquippedItems["favorite_loadingscreen"],
                                    book_purchased         = account.BattlePass,
                                    lifetime_wins          = 0,
                                    favorite_hat           = "",
                                    level = account.Level,
                                    favorite_battlebus       = "",
                                    favorite_mapmarker       = "",
                                    favorite_vehicledeco     = "",
                                    accountLevel             = account.TotalLevel,
                                    favorite_backpack        = account.EquippedItems["favorite_backpack"],
                                    favorite_dance           = dances,
                                    inventory_limit_bonus    = 0,
                                    favorite_skydivecontrail = account.EquippedItems["favorite_skydivecontrail"],
                                    favorite_pickaxe         = account.EquippedItems["favorite_pickaxe"],
                                    favorite_glider          = account.EquippedItems["favorite_glider"],
                                    daily_rewards            = new { },
                                    xp = 0,
                                    season_friend_match_boost = 0,
                                    favorite_musicpack        = account.EquippedItems["favorite_musicpack"],
                                    banner_icon = "standardbanner1"
                                }
                            },
                            commandRevision = 5
                        }
                    }
                },
                profileCommandRevision = 1,
                serverTime             = DateTime.Now.ToDateTimeString(),
                multiUpdate            = new[]
                {
                    new
                    {
                        profileRevision            = 10,
                        profileId                  = "common_core",
                        profileChangesBaseRevision = 8,
                        profileCommandRevision     = 5,
                        profileChanges             = new List <object>()
                    }
                },
                responseVersion = 1
            };

            Response.StatusCode  = 200;
            Response.ContentType = "application/json";
            Response.Write(JsonConvert.SerializeObject(response));
        }
Beispiel #42
0
        // コンストラクタ

        public AddAccountService(IUnityContainer unityContainer, LoggingService loggingService, AccountManager accountManager)
        {
            // DI
            _unityContainer = unityContainer;
            _loggingService = loggingService;
            _accountManager = accountManager;
        }
Beispiel #43
0
 private static void SetLocation(Location location)
 {
     PokewatchLogger.Log($"[!]Setting location to {location.Latitude},{location.Longitude}", AccountManager.GetAccountName(s_account));
     s_pogoSession.Player.SetCoordinates(location.Latitude, location.Longitude);
 }
Beispiel #44
0
        public override void ProcessServer()
        {
            // update our own timestamp here
            AccountManager.UpdateLastSeen(SenderSteamId, SenderLanguage);
            EconomyScript.Instance.ServerLogger.WriteVerbose("Manage Player Mission from '{0}'", SenderSteamId);

            switch (CommandType)
            {
            case PlayerMissionManage.Test:
                //EconomyScript.Instance.ServerLogger.WriteVerbose("Mission Text request '{0}' from '{1}'", MissionID, SenderSteamId);
                MessageClientTextMessage.SendMessage(SenderSteamId, "mission", (MissionId + " server side"));
                break;

            case PlayerMissionManage.AddSample:
            {
                var player       = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId);
                var playerMatrix = player.Character.WorldMatrix;
                //var position = player.Character.GetPosition();
                Vector3D position = playerMatrix.Translation + playerMatrix.Forward * 60f;

                MissionBaseStruct newMission = CreateMission(new TravelMission
                    {
                        AreaSphere = new BoundingSphereD(position, 50),
                        //AreaSphere = new BoundingSphereD(new Vector3D(0, 0, 0), 50),
                        Reward = 100,
                    }, SenderSteamId);

                ConnectionHelper.SendMessageToPlayer(SenderSteamId, new MessageMission {
                        CommandType = PlayerMissionManage.AddMission, Mission = newMission
                    });
            }
            break;

            case PlayerMissionManage.AddMission:
                // Nothing should happen here, because the server sends missions to the client, not the other way.
                break;

            case PlayerMissionManage.SyncMission:
                // TODO: sync details back from the client to the server.
                break;

            case PlayerMissionManage.DeleteMission:
                // TODO: Delete the mission.
                break;

            case PlayerMissionManage.MissionComplete:
                // This should process the mission reward if appropriate and then delete from server.
                // We aren't archiving finished missions.

                MissionBaseStruct serverinstanceMission = GetMission(Mission.MissionId);

                if (serverinstanceMission != null && serverinstanceMission.PlayerId == SenderSteamId)
                {
                    var player = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId);
                    if (player != null)
                    {
                        // we look up our bank record based on our Steam Id/
                        // create balance if not one already, then add our reward and update client.
                        var myaccount = AccountManager.FindOrCreateAccount(SenderSteamId, player.DisplayName, SenderLanguage);

                        EconomyScript.Instance.Data.CreditBalance -= serverinstanceMission.Reward;
                        myaccount.BankBalance += serverinstanceMission.Reward;
                        myaccount.Date         = DateTime.Now;

                        MessageUpdateClient.SendAccountMessage(myaccount);
                    }

                    RemoveMission(serverinstanceMission);
                }

                break;
            }
        }
        private void InitializeWindow()
        {
            // Upgrade the stored settings if needed
            if (Properties.Settings.Default.UpgradeRequired)
            {
                Log.Information("Settings upgrade required...");
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpgradeRequired = false;
                Properties.Settings.Default.Save();
            }

            var gateStatus = false;

            try
            {
                gateStatus = _game.GetGateStatus();
            }
            catch
            {
                // ignored
            }

            if (!gateStatus)
            {
                WorldStatusPackIcon.Foreground = new SolidColorBrush(Color.FromRgb(242, 24, 24));
            }

            var version = Util.GetAssemblyVersion();

            if (Properties.Settings.Default.LastVersion != version)
            {
                new ChangelogWindow().ShowDialog();

                Properties.Settings.Default.LastVersion = version;
                Settings.UniqueIdCache = new List <UniqueIdCacheEntry>();

                if (version == "3.4.0.0")
                {
                    var savedCredentials = CredentialManager.GetCredentials("FINAL FANTASY XIV");

                    if (savedCredentials != null)
                    {
                        _accountManager.AddAccount(new XivAccount(savedCredentials.UserName)
                        {
                            Password               = savedCredentials.Password,
                            SavePassword           = true,
                            UseOtp                 = Settings.NeedsOtp(),
                            UseSteamServiceAccount = Settings.SteamIntegrationEnabled
                        });

                        Properties.Settings.Default.CurrentAccount = $"{savedCredentials.UserName}-{Settings.NeedsOtp()}-{Settings.SteamIntegrationEnabled}";;
                    }
                }

                Properties.Settings.Default.Save();
            }

            _accountManager = new AccountManager();

            var savedAccount = _accountManager.CurrentAccount;

            if (savedAccount != null)
            {
                SwitchAccount(savedAccount, false);
            }

            AutoLoginCheckBox.IsChecked = Settings.IsAutologin();

            if (Settings.IsAutologin() && savedAccount != null && !Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
            {
                Log.Information("Engaging Autologin...");

                try
                {
                    #if DEBUG
                    HandleLogin(true);
                    Settings.Save();
                    return;
                    #else
                    if (!gateStatus)
                    {
                        MessageBox.Show(
                            "Square Enix seems to be running maintenance work right now. The game shouldn't be launched.");
                        Settings.SetAutologin(false);
                        _isLoggingIn = false;
                    }
                    else
                    {
                        HandleLogin(true);
                        Settings.Save();
                        return;
                    }
                    #endif
                }
                catch (Exception exc)
                {
                    new ErrorWindow(exc, "Additionally, please check your login information or try again.", "AutoLogin")
                    .ShowDialog();
                    Settings.SetAutologin(false);
                    _isLoggingIn = false;
                }

                Settings.Save();
            }

            if (Settings.GamePath == null)
            {
                var setup = new FirstTimeSetup();
                setup.ShowDialog();
            }

            Task.Run(() => SetupHeadlines());

            Settings.LanguageChanged += SetupHeadlines;

            Show();
            Activate();

            Log.Information("MainWindow initialized.");
        }
 private void Signout()
 {
     AccountManager.Signout();
     ViewPresenter.PopView();
 }
Beispiel #47
0
        private static bool Search()
        {
            RepeatedField <MapCell> mapCells = s_pogoSession.Map.Cells;

            foreach (var mapCell in mapCells)
            {
                foreach (WildPokemon pokemon in mapCell.WildPokemons)
                {
                    FoundPokemon foundPokemon = ProcessPokemon(pokemon, s_tweetedPokemon, s_lastTweet);

                    if (foundPokemon == null)
                    {
                        continue;
                    }

                    string tweet = ComposeTweet(foundPokemon);

                    if (tweet == null)
                    {
                        throw new Exception();
                    }

                    if (Tweet.Length(tweet) > 140)
                    {
                        PokewatchLogger.Log("[-]Tweet exceeds 140 characters. Consider changing your template: " + tweet, AccountManager.GetAccountName(s_account));
                        continue;
                    }
                    try
                    {
                        s_twitterClient.PublishTweet(tweet);
                        PokewatchLogger.Log("[+]Tweet published: " + tweet, AccountManager.GetAccountName(s_account));
                        s_lastTweet = DateTime.Now;
                    }
                    catch (Exception ex)
                    {
                        PokewatchLogger.Log("[-]Tweet failed to publish: " + tweet + " " + ex.Message, AccountManager.GetAccountName(s_account));
                    }

                    s_tweetedPokemon.Enqueue(foundPokemon);

                    if (s_tweetedPokemon.Count > 10)
                    {
                        s_tweetedPokemon.Dequeue();
                    }
                }
            }
            return(true);
        }
    /// <summary>
    /// Prevents object from being destroyed, gets necessary references.
    /// </summary>
    void Awake()
    {
        instance = this;
        DontDestroyOnLoad(this.gameObject);

        facebookManager = this.GetComponent<FacebookManager>();
        playFabManager = this.GetComponent<PlayFabManager>();
    }
Beispiel #49
0
        public override List <StreamState> GetStreamsInFile()
        {
            var collection = new List <StreamState>();

            #region create dummy data

            var collabs = new List <Collaborator>()
            {
                new Collaborator
                {
                    id     = "123",
                    name   = "Matteo Cominetti",
                    role   = "stream:contributor",
                    avatar = "https://avatars0.githubusercontent.com/u/2679513?s=88&v=4"
                },
                new Collaborator
                {
                    id     = "321",
                    name   = "Izzy Lyseggen",
                    role   = "stream:owner",
                    avatar =
                        "https://avatars2.githubusercontent.com/u/7717434?s=88&u=08db51f5799f6b21580485d915054b3582d519e6&v=4"
                },
                new Collaborator
                {
                    id     = "456",
                    name   = "Dimitrie Stefanescu",
                    role   = "stream:contributor",
                    avatar =
                        "https://avatars3.githubusercontent.com/u/7696515?s=88&u=fa253b5228d512e1ce79357c63925b7258e69f4c&v=4"
                }
            };

            var branches = new Branches()
            {
                totalCount = 2,
                items      = new List <Branch>()
                {
                    new Branch()
                    {
                        id      = "123",
                        name    = "main",
                        commits = new Commits()
                        {
                            items = new List <Commit>()
                            {
                                new Commit()
                                {
                                    authorName = "izzy 2.0",
                                    id         = "commit123",
                                    message    = "a totally real commit 💫",
                                    createdAt  = "sometime"
                                },
                                new Commit()
                                {
                                    authorName = "izzy bot",
                                    id         = "commit321",
                                    message    = "look @ all these changes 👩‍🎤",
                                    createdAt  = "03/05/2030"
                                }
                            }
                        }
                    },
                    new Branch()
                    {
                        id = "321", name = "dev"
                    }
                }
            };

            var branches2 = new Branches()
            {
                totalCount = 2,
                items      = new List <Branch>()
                {
                    new Branch()
                    {
                        id      = "123",
                        name    = "main",
                        commits = new Commits()
                        {
                            items = new List <Commit>()
                            {
                                new Commit()
                                {
                                    authorName = "izzy 2.0",
                                    id         = "commit123",
                                    message    = "a totally real commit 💫",
                                    createdAt  = "sometime"
                                },
                                new Commit()
                                {
                                    authorName = "izzy bot",
                                    id         = "commit321",
                                    message    = "look @ all these changes 👩‍🎤",
                                    createdAt  = "03/05/2030"
                                }
                            }
                        }
                    },
                    new Branch()
                    {
                        id = "321", name = "dev/what/boats"
                    }
                }
            };


            var testStreams = new List <Stream>()
            {
                new Stream
                {
                    id            = "stream123",
                    name          = "Random Stream here 👋",
                    description   = "this is a test stream",
                    isPublic      = true,
                    collaborators = collabs.GetRange(0, 2),
                    branches      = branches
                },
                new Stream
                {
                    id            = "stream789",
                    name          = "Woop Cool Stream 🌊",
                    description   = "cool and good indeed",
                    isPublic      = true,
                    collaborators = collabs.GetRange(1, 2),
                    branches      = branches2
                }
            };

            #endregion
            var client = AccountManager.GetDefaultAccount() != null
        ? new Client(AccountManager.GetDefaultAccount())
        : new Client();

            foreach (var stream in testStreams)
            {
                collection.Add(new StreamState(client, stream));
            }

            collection[0].SelectedObjectIds.Add("random_obj");

            return(collection);
        }
        public void StartMultiThreadsUploadImage(object parameters)
        {
            try
            {
                if (!isStopUploadImage)
                {
                    try
                    {
                        listOfWorkingThread.Add(Thread.CurrentThread);
                        listOfWorkingThread.Distinct();
                        Thread.CurrentThread.IsBackground = true;
                    }
                    catch (Exception ex)
                    {
                        GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                    }
                    try
                    {
                        Array paramsArray = new object[1];
                        paramsArray = (Array)parameters;

                        InstagramUser objInstagramUser = (InstagramUser)paramsArray.GetValue(0);

                        if (!objInstagramUser.isloggedin)
                        {
                            GlobusHttpHelper objGlobusHttpHelper = new GlobusHttpHelper();

                            objInstagramUser.globusHttpHelper = objGlobusHttpHelper;
                            AccountManager objAccountManager = new AccountManager();
                            GlobusLogHelper.log.Info("Started Logging From Account : " + objInstagramUser.username);
                            if (IsPostPic)
                            {
                                LoginWithMobileDevice(ref objInstagramUser);
                            }
                            else
                            {
                                objAccountManager.LoginUsingGlobusHttp(ref objInstagramUser);
                            }
                        }
                        if (objInstagramUser.isloggedin)
                        {
                            StartActionUploadImage(ref objInstagramUser);
                        }
                        else
                        {
                            // StartActionVerifyAccount(ref objInstagramUser);
                            GlobusLogHelper.log.Info("Couldn't Login With Username : "******"Couldn't Login With Username : "******"Error : " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
            }
            finally
            {
                try
                {
                    lock (lockrThreadControllerUploadImage)
                    {
                        countThreadControllerUploadImage--;
                        Monitor.Pulse(lockrThreadControllerUploadImage);
                    }
                }
                catch (Exception ex)
                {
                    GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                }
            }
        }
Beispiel #51
0
        /// <summary>
        /// Сервис возвращает результат авторизации пользователя.
        /// </summary>
        /// <param name="email">E-mail пользователя.</param>
        /// <param name="passwordHash">Пароль пользователя.</param>
        /// <returns>true, если пользователь успешно авторизован, иначе - false.</returns>
        public bool SignIn(string email, string passwordHash)
        {
            var accountManager = new AccountManager(_authRepository);

            return(accountManager.SignIn(email, passwordHash));
        }
 public SmartStore()
 {
     _databasePath = GenerateDatabasePath(AccountManager.GetAccount());
     CreateMetaTables();
 }
Beispiel #53
0
 public DisplayReply(Reply rpl, AccountManager accManager, AttachmentManager attManager)
     : base(rpl, attManager, accManager)
 {
     this.MessageID = rpl.MessageID;
 }
Beispiel #54
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (DA.Iteration != 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot create multiple streams at the same time. This is an explicit guard against possibly unintended behaviour. If you want to create another stream, please use a new component.");
                return;
            }

            string  userId  = null;
            Account account = null;

            DA.GetData(0, ref userId);

            if (userId == null)
            {
                //account = AccountManager.GetDefaultAccount();
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"Using default account {account}");
            }
            else
            {
                account = AccountManager.GetAccounts().FirstOrDefault(a => a.userInfo.id == userId);
                if (account == null)
                {
                    // Really last ditch effort - in case people delete accounts from the manager, and the selection dropdown is still using an outdated list.
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"The user with id of {userId} was not found.");
                    return;
                }
            }

            Params.Input[0].AddVolatileData(new GH_Path(0), 0, account.userInfo.id);

            if (stream != null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using cached stream. If you want to create a new stream, create a new component.");
                DA.SetData(0, new GH_SpeckleStream(stream));
                NickName        = $"Id: {stream.StreamId}";
                MutableNickName = false;
                return;
            }

            Task.Run(async() =>
            {
                var client = new Client(account);
                try
                {
                    var streamId = await client.StreamCreate(new StreamCreateInput());
                    stream       = new StreamWrapper(
                        streamId,
                        account.userInfo.id,
                        account.serverInfo.url
                        );

                    Rhino.RhinoApp.InvokeOnUiThread((Action) delegate
                    {
                        ExpireSolution(true);
                    });
                }
                catch (Exception e)
                {
                    Rhino.RhinoApp.InvokeOnUiThread((Action) delegate
                    {
                        ExpireSolution(false);
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Could not create stream at {account.serverInfo.url}:\n{e.Message}");
                    });
                }
            });
        }
        public void FollowOperationequal(string Acc, string[] Hash)
        {
            string status = string.Empty;
            string[] arrAcc = Regex.Split(Acc, ":");
            InstagramUser objInstagramUser = new InstagramUser(arrAcc[0], arrAcc[1], arrAcc[2], arrAcc[3]);
            GlobusHttpHelper objGlobusHttpHelper = new GlobusHttpHelper();
            objInstagramUser.globusHttpHelper = objGlobusHttpHelper;
            AccountManager objAccountManager = new AccountManager();
            if (!objInstagramUser.isloggedin)
            {
                status = objAccountManager.LoginUsingGlobusHttp(ref objInstagramUser);
            }
            if (status == "Success" || (objInstagramUser.isloggedin))
            {

                foreach (string itemHash in Hash)
                {
                    if (!string.IsNullOrEmpty(itemHash))
                    {
                        //Operation
                        string[] Data_ID = Regex.Split(itemHash, ",");
                        string daaa = objInstagramUser.username;
                        foreach (string Photo_ID in Data_ID)
                        {
                            if (!string.IsNullOrEmpty(Photo_ID))
                            {
                                FollowUrls(ref objInstagramUser, Photo_ID);
                            }
                            else
                            {
                                break;
                            }

                            if (minDelayFollowerPoster != 0)
                            {
                                mindelay = minDelayFollowerPoster;
                            }
                            if (maxDelayFollowerPoster != 0)
                            {
                                maxdelay = maxDelayFollowerPoster;
                            }

                            Random obj_rn = new Random();
                            int delay = RandomNumberGenerator.GenerateRandom(mindelay, maxdelay);
                            delay = obj_rn.Next(mindelay, maxdelay);
                            GlobusLogHelper.log.Info("[ " + DateTime.Now + " ] => [ Delay For " + delay + " Seconds ]");
                            Thread.Sleep(delay * 1000);
                        }

                    }
                    GlobusLogHelper.log.Info("=========================");
                    GlobusLogHelper.log.Info("Process Completed !!!");
                    GlobusLogHelper.log.Info("=========================");
                }
            }
        }
        public void StartMultiThreadsSalesNavigator(object parameters)
        {
            try
            {
                if (!GlobalsScraper.isStopSalesNavigator)
                {
                    try
                    {
                        GlobalsScraper.lstThreadsSalesNavigator.Add(Thread.CurrentThread);
                        GlobalsScraper.lstThreadsSalesNavigator.Distinct();
                        Thread.CurrentThread.IsBackground = true;
                    }
                    catch (Exception ex)
                    {
                        GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                    }
                    try
                    {
                        Array paramsArray = new object[1];
                        paramsArray = (Array)parameters;

                        LinkedinUser objLinkedinUser = (LinkedinUser)paramsArray.GetValue(0);

                        if (!objLinkedinUser.isloggedin)
                        {
                            GlobusHttpHelper objGlobusHttpHelper = objLinkedinUser.globusHttpHelper;

                            //Login Process
                            Accounts.AccountManager objAccountManager = new AccountManager();
                            objAccountManager.LoginHttpHelper(ref objLinkedinUser);
                        }

                        if (objLinkedinUser.isloggedin)
                        {
                            // Call StartActionMessageReply
                            StartSalesNavigator(ref objLinkedinUser);
                        }
                        else
                        {
                            GlobusLogHelper.log.Info("Couldn't Login With Username : "******"Couldn't Login With Username : "******"Error : " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
            }

            finally
            {
                try
                {
                    // if (!isStopWallPoster)
                    {
                        lock (lockrThreadControllerSalesNavigator)
                        {
                            GlobalsScraper.countThreadControllerSalesNavigator = GlobalsScraper.countThreadControllerSalesNavigator--;
                            Monitor.Pulse(lockrThreadControllerSalesNavigator);
                        }
                    }
                }
                catch (Exception ex)
                {
                    GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                }
            }
        }
        public void StartMultiThreadsUsingUsername(object parameters)
        {
            try
            {
                if (!isStopUsingUsername)
                {
                    try
                    {
                        lstThreadsUsingUsername.Add(Thread.CurrentThread);
                        lstThreadsUsingUsername.Distinct();
                        Thread.CurrentThread.IsBackground = true;
                    }
                    catch (Exception ex)
                    {
                        GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                    }
                    try
                    {
                        Array paramsArray = new object[1];
                        paramsArray = (Array)parameters;

                        InstagramUser objFacebookUser = (InstagramUser)paramsArray.GetValue(0);

                        if (!objFacebookUser.isloggedin)
                        {
                            GlobusHttpHelper objGlobusHttpHelper = new GlobusHttpHelper();

                            objFacebookUser.globusHttpHelper = objGlobusHttpHelper;
                            //Login Process
                            Accounts.AccountManager objAccountManager = new AccountManager();
                            status = objAccountManager.LoginUsingGlobusHttp(ref objFacebookUser);
                        }

                        if (objFacebookUser.isloggedin)
                        {
                            StartActionFollowerModule(ref objFacebookUser);
                        }
                        else
                        {
                            GlobusLogHelper.log.Info("Couldn't Login With Username : "******"Couldn't Login With Username : "******"Error : " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
            }

            finally
            {
                try
                {

                    {
                        lock (lockrThreadControlleUsingUsername)
                        {
                            countThreadControllerUsingUsername--;
                            Monitor.Pulse(lockrThreadControlleUsingUsername);
                        }
                    }
                }
                catch (Exception ex)
                {
                    GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                }
            }
        }
Beispiel #58
0
 protected override void OnResume()
 {
     base.OnResume();
     AccountManager.RefreshUser();
 }
Beispiel #59
0
 // Code to execute when the application is deactivated (sent to background)
 // This code will not execute when the application is closing
 private async void Application_Deactivated(object sender, DeactivatedEventArgs e)
 {
     await AccountManager.LogoutAllAsync();
 }
Beispiel #60
0
        //Build a tweet with useful information about the pokemon, then cram in as many hashtags as will fit.
        private static string ComposeTweet(FoundPokemon pokemon)
        {
            PokewatchLogger.Log("[!]Composing Tweet.", AccountManager.GetAccountName(s_account));
            string latitude   = pokemon.Location.Latitude.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-us"));
            string longitude  = pokemon.Location.Longitude.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-us"));
            string mapsLink   = s_config.Pokevision ? $"https://pokevision.com/#/@{latitude},{longitude}" : $"https://www.google.com/maps/place/{latitude},{longitude}";
            string expiration = DateTime.Now.AddSeconds(pokemon.LifeExpectancy).ToLocalTime().ToShortTimeString();
            string tweet      = "";

            try
            {
                tweet = string.Format(s_config.PriorityPokemon.Contains(pokemon.Kind) ? s_config.PriorityTweet : s_config.RegularTweet,
                                      SpellCheckPokemon(pokemon.Kind),
                                      s_currentScan.Prefix,
                                      s_currentScan.Name,
                                      s_currentScan.Suffix,
                                      expiration,
                                      mapsLink);
            }
            catch
            {
                PokewatchLogger.Log("[-]Failed to format tweet. If you made customizations, they probably broke it.", AccountManager.GetAccountName(s_account));
                return(null);
            }

            tweet = Regex.Replace(tweet, @"\s\s", @" ");
            tweet = Regex.Replace(tweet, @"\s[!]", @"!");

            Regex hashtag = new Regex("[^a-zA-Z0-9]");

            if (s_config.TagPokemon && (Tweet.Length(tweet + " #" + hashtag.Replace(SpellCheckPokemon(pokemon.Kind), "")) < 140))
            {
                tweet += " #" + hashtag.Replace(SpellCheckPokemon(pokemon.Kind), "");
            }

            if (s_config.TagRegion && (Tweet.Length(tweet + " #" + hashtag.Replace(s_currentScan.Name, "")) < 140))
            {
                tweet += " #" + hashtag.Replace(s_currentScan.Name, "");
            }

            foreach (string tag in s_config.CustomTags)
            {
                if (Tweet.Length(tweet + " #" + hashtag.Replace(tag, "")) < 140)
                {
                    tweet += " #" + hashtag.Replace(tag, "");
                }
            }

            PokewatchLogger.Log("[!]Sucessfully composed tweet.", AccountManager.GetAccountName(s_account));
            return(tweet);
        }