/// <inheritdoc/> protected override void Process() { if (!Enum.TryParse(this.AccountSource, out AccountSourceOption source)) { throw new ArgumentException("Invalid account source. Must be either 'WindowsDevCenter'.", nameof(this.AccountSource)); } DevAccount devAccount = ToolAuthentication.SignInAsync((DevAccountSource)source, this.UserName).Result; this.WriteObject($"Developer account {devAccount.Name} has successfully signed in."); this.WriteObject(devAccount); }
/// <inheritdoc/> protected override void Process() { DevAccount account = ToolAuthentication.LoadLastSignedInUser(); if (account != null) { this.WriteObject($"Developer account {account.Name} from {account.AccountSource} is currently signed in."); this.WriteObject(account); } else { this.WriteObject($"No signed in account found."); } }
/// <summary> /// Reset one player's data in test sandboxes, includes: achievements, leaderboards, player stats and title history. /// </summary> /// <param name="serviceConfigurationId">The service configuration ID (SCID) of the title for player data resetting</param> /// <param name="sandbox">The target sandbox id for player resetting</param> /// <param name="xboxUserId">The Xbox user id of the player to be reset</param> /// <returns>The UserResetResult object for the reset result</returns> public static async Task <UserResetResult> ResetPlayerDataAsync(string serviceConfigurationId, string sandbox, string xboxUserId) { // Pre-fetch the product/sandbox etoken before getting into the loop, so that we can // populate the auth error up-front. if (ToolAuthentication.Client.AuthContext.AccountSource == DevAccountSource.TestAccount) { await ToolAuthentication.GetTestTokenSilentlyAsync(sandbox); } else { await ToolAuthentication.GetDevTokenSilentlyAsync(serviceConfigurationId, sandbox); } return(await SubmitJobAndPollStatus(sandbox, serviceConfigurationId, xboxUserId)); }
private static int OnShow() { DevAccount account = ToolAuthentication.LoadLastSignedInUser(); if (account != null) { Console.WriteLine($"Developer account {account.Name} from {account.AccountSource} is currently signed in."); DisplayDevAccount(account, "\t"); return(0); } else { Console.WriteLine($"No signed in account found."); return(-1); } }
private static int OnSignOut() { DevAccount account = ToolAuthentication.LoadLastSignedInUser(); if (account != null) { ToolAuthentication.SignOut(); Console.WriteLine($"Developer account {account.Name} from {account.AccountSource} has successfully signed out."); return(0); } else { Console.WriteLine($"No signed in account found."); return(-1); } }
private void UpdateAccountPanel() { this.signedInuser = ToolAuthentication.LoadLastSignedInUser(); if (this.signedInuser != null) { this.btnSingInout.Text = "Sign Out"; this.cmbAccountSource.Enabled = false; this.labelUserName.Text = this.signedInuser.Name; this.btnQuery.Enabled = true; } else { this.btnSingInout.Text = "Sign In"; this.cmbAccountSource.Enabled = true; this.labelUserName.Text = string.Empty; this.btnQuery.Enabled = false; } }
private async Task <Tuple <string, string> > QueryForDocSessionHistoryChangeAsync(string sessionName, string branch, long changeNumber) { string snapshot = null; string errorMsg = null; if (changeNumber == SessionHistory.MaxChangeValue) { return(new Tuple <string, string>(null, null)); // there is nothing to get, so don't bother trying } string hashKey = this.snapshotCache.GetHashString( sessionName, branch, changeNumber); if (!this.snapshotCache.TryGetSnapshot(hashKey, out snapshot)) { string eToken = await ToolAuthentication.GetDevTokenSilentlyAsync(this.tbScid.Text, this.tbSandbox.Text); this.lblExplanation.Text = string.Format("Downloading session snapshot #{0}", changeNumber); var response = await SessionHistory.GetSessionHistoryDocumentChangeAsync( this.tbScid.Text, this.tbTemplateName.Text, sessionName, branch, changeNumber, eToken); if (response.Item1 == HttpStatusCode.OK) { snapshot = response.Item2; this.snapshotCache.AddSnapshotToCache(hashKey, response.Item2); } else if (response.Item1 != HttpStatusCode.NoContent) { errorMsg = response.Item2; } } return(new Tuple <string, string>(snapshot, errorMsg)); }
private static async Task <int> Main(string[] args) { VirtualTerminal.Enable(); int exitCode = 0; DevAccount account = ToolAuthentication.LoadLastSignedInUser(); if (account == null) { Console.Error.WriteLine("Didn't find dev signin info, please use \"XblDevAccount.exe signin\" to initiate."); return(-1); } if (account.AccountSource != DevAccountSource.WindowsDevCenter) { Console.Error.WriteLine("You must sign in with a valid Windows Dev Center account."); } string invokedVerb = null; object opts = null; Console.WriteLine($"Using Dev account {account.Name} from {account.AccountSource}"); try { // Find all of the subclasses which inherit from BaseOptions. Type[] argumentTypes = typeof(Program).GetNestedTypes(BindingFlags.NonPublic).Where(c => c.IsSubclassOf(typeof(BaseOptions))).ToArray(); // Only assign the option and verb here, as the commandlineParser doesn't support async callback yet. Parser.Default.ParseArguments(args, argumentTypes) .WithParsed(options => { VerbAttribute verbAttribute = Attribute.GetCustomAttribute(options.GetType(), typeof(VerbAttribute)) as VerbAttribute; invokedVerb = verbAttribute?.Name; opts = options; }) .WithNotParsed(err => exitCode = -1); if (opts != null) { // Find property called AccountId. If it not set, then set it to the logged in user's account Id. PropertyInfo accountIdProperty = opts.GetType().GetProperty("AccountId"); if (accountIdProperty != null) { Guid accountIdPropertyValue = (Guid)accountIdProperty.GetValue(opts); if (accountIdPropertyValue == Guid.Empty) { accountIdProperty.SetValue(opts, new Guid(account.AccountId)); } } // Find the method which takes this class as an argument. MethodInfo method = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.NonPublic).Where(c => c.GetParameters().FirstOrDefault()?.ParameterType == opts.GetType()).FirstOrDefault(); if (method == null) { // This should never happen, but just in case... throw new InvalidOperationException($"Method with parameter {opts.GetType()} not found."); } Task <int> methodResult = (Task <int>)method.Invoke(null, new object[] { opts }); exitCode = await methodResult; } } catch (HttpRequestException ex) { Console.Error.WriteLine($"Error: XblConfig {invokedVerb} failed."); if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Unauthorized))) { Console.Error.WriteLine( $"Unable to authorize the account with the XboxLive service, please contact your administrator."); } else if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Forbidden))) { Console.Error.WriteLine( "Your account doesn't have access to perform the operation, please contact your administrator."); } else { Console.WriteLine(ex.Message); } exitCode = -1; } catch (Exception ex) { Console.Error.WriteLine("Error: unexpected error found."); Console.Error.WriteLine(ex.Message); exitCode = -1; } if (System.Diagnostics.Debugger.IsAttached) { Console.Read(); } return(exitCode); }
public void TestCleanup() { TestHook.MockHttpHandler = null; ToolAuthentication.SignOut(); }
private async Task <DevAccount> SignInAsync(DevAccountSource accountSource, string userName) { return(await ToolAuthentication.SignInAsync(accountSource, userName, this.authMock.Object)); }
private static async Task <int> Main(string[] args) { int exitCode = 0; string invokedVerb = string.Empty; BaseOptions baseOptions = null; try { // Only assign the option and verb here, as the commandlineParser doesn't support async callback yet. var result = Parser.Default.ParseArguments <QuotaOptions, BlobMetadataOptions, DeleteOptions, DownloadOptions, UploadOptions>(args) .WithParsed(options => { var verbAttribute = Attribute.GetCustomAttribute(options.GetType(), typeof(VerbAttribute)) as VerbAttribute; invokedVerb = verbAttribute?.Name; baseOptions = options as BaseOptions; }) .WithNotParsed(err => exitCode = -1); DevAccount account = ToolAuthentication.LoadLastSignedInUser(); if (account == null) { Console.Error.WriteLine("Didn't found dev sign in info, please use \"XblDevAccount.exe signin\" to initiate."); return(-1); } Console.WriteLine($"Using Dev account {account.Name} from {account.AccountSource}"); if (invokedVerb == "quota" && baseOptions is QuotaOptions quotaOptions) { exitCode = await OnGetQuota(quotaOptions); } else if (invokedVerb == "list" && baseOptions is BlobMetadataOptions blobMetadataOptions) { exitCode = await OnGetBlobMetadata(blobMetadataOptions); } else if (invokedVerb == "delete" && baseOptions is DeleteOptions deleteOptions) { exitCode = await OnDelete(deleteOptions); } else if (invokedVerb == "download" && baseOptions is DownloadOptions downloadOptions) { exitCode = await OnDownload(downloadOptions); } else if (invokedVerb == "upload" && baseOptions is UploadOptions uploadOptions) { exitCode = await OnUpload(uploadOptions); } else { Console.Error.WriteLine("Parsing parameters error."); exitCode = -1; } } catch (HttpRequestException ex) { Console.WriteLine($"Error: GlobalStorage {invokedVerb} failed."); if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Unauthorized))) { Console.WriteLine( $"Unable to authorize the account with XboxLive service with scid : {baseOptions?.ServiceConfigurationId} and sandbox : {baseOptions?.Sandbox}, please contact your administrator."); } else if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Forbidden))) { Console.WriteLine( "Your account doesn't have access to perform the operation, please contact your administrator."); } else { Console.WriteLine(ex.Message); } return(-1); } catch (Exception ex) { Console.Error.WriteLine("Error: unexpected error found."); Console.Error.WriteLine(ex.Message); exitCode = -1; } return(exitCode); }
private static async Task <int> OnReset(ResetOptions options) { if (options == null) { Console.WriteLine("Unknown parameter error"); return(-1); } DevAccount account = ToolAuthentication.LoadLastSignedInUser(); if (account == null) { Console.Error.WriteLine("Didn't found dev sign in info, please use \"XblDevAccount.exe signin\" to initiate."); return(-1); } Console.WriteLine($"Using Dev account {account.Name} from {account.AccountSource}"); Console.WriteLine($"Resetting player {options.XboxUserId} data for scid {options.ServiceConfigurationId}, sandbox {options.Sandbox}"); try { UserResetResult result = await PlayerReset.ResetPlayerDataAsync( options.ServiceConfigurationId, options.Sandbox, options.XboxUserId); switch (result.OverallResult) { case ResetOverallResult.Succeeded: Console.WriteLine("Resetting has completed successfully."); return(0); case ResetOverallResult.CompletedError: Console.WriteLine("Resetting has completed with some error:"); if (!string.IsNullOrEmpty(result.HttpErrorMessage)) { Console.WriteLine($"\t{result.HttpErrorMessage}"); } PrintProviderDetails(result.ProviderStatus); return(-1); case ResetOverallResult.Timeout: Console.WriteLine("Resetting has timed out:"); PrintProviderDetails(result.ProviderStatus); return(-1); default: Console.WriteLine("has completed with unknown error"); return(-1); } } catch (HttpRequestException ex) { Console.WriteLine("Error: player data reset failed"); if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Unauthorized))) { Console.WriteLine( $"Unable to authorize the account with XboxLive service with scid : {options.ServiceConfigurationId} and sandbox : {options.Sandbox}, please contact your administrator."); } else if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Forbidden))) { Console.WriteLine( "Your account doesn't have access to perform the operation, please contact your administrator."); } else { Console.WriteLine(ex.Message); } return(-1); } }
private static async Task <int> GetDocumentsAsync(GetDocumentsOptions options) { if (options.DocumentType == DocumentType.Sandbox && string.IsNullOrEmpty(options.Sandbox)) { throw new ArgumentException("Sandbox must be specified when obtaining sandbox documents."); } if (options.DocumentType == DocumentType.Sandbox && options.Scid == Guid.Empty) { throw new ArgumentException("SCID must be specified when obtaining sandbox documents."); } if (options.DocumentType == DocumentType.Account) { options.Sandbox = null; } EnsureDirectory(options.Destination); Task <DocumentsResponse> documentsTask; if (options.DocumentType == DocumentType.Sandbox) { Console.WriteLine("Obtaining sandbox documents."); documentsTask = ConfigurationManager.GetSandboxDocumentsAsync(options.Scid, options.Sandbox); } else { Console.WriteLine("Obtaining account documents."); if (options.AccountId == Guid.Empty) { DevAccount user = ToolAuthentication.LoadLastSignedInUser(); options.AccountId = new Guid(user.AccountId); } documentsTask = ConfigurationManager.GetAccountDocumentsAsync(options.AccountId); } using (DocumentsResponse documents = await documentsTask) { Console.WriteLine($"ETag: {documents.ETag}"); Console.WriteLine($"Version: {documents.Version}"); Console.WriteLine("Files: "); foreach (ConfigFileStream file in documents.Documents) { string path = Path.Combine(options.Destination, file.Name); using (FileStream fileStream = File.Create(path)) { await file.Stream.CopyToAsync(fileStream); } Console.WriteLine($" - {file.Name}"); } SaveETag(documents.ETag, options.Destination, options.Sandbox); Console.WriteLine($"Saved {documents.Documents.Count()} files to {options.Destination}."); } return(0); }
private static async Task <int> Main(string[] args) { Options options = null; try { // Only assign the option and verb here, as the commandlineParser doesn't support async callback yet. ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args) .WithParsed(parsedOptions => { options = parsedOptions; }); if (options == null) { Console.Error.WriteLine("Parsing parameters error."); return(-1); } if (options.GamerTag.Contains("#")) { Console.Error.WriteLine("Modern gamertags are not supported. Please use a legacy gamertag."); return(-1); } DevAccount account = ToolAuthentication.LoadLastSignedInUser(); if (account == null) { Console.Error.WriteLine("Didn't found dev sign in info, please use \"XblDevAccount.exe signin\" to initiate."); return(-1); } Console.WriteLine($"Using Dev account {account.Name} from {account.AccountSource}"); return(await OnDownload(options)); } catch (HttpRequestException ex) { Console.WriteLine($"Error: XblConnectedStorage failed."); if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Unauthorized))) { Console.WriteLine( $"Unable to authorize the account with XboxLive service with scid : {options?.ServiceConfigurationId} and sandbox : {options?.Sandbox}, please contact your administrator."); } else if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Forbidden))) { Console.WriteLine( "Your account doesn't have access to perform the operation, please contact your administrator."); } else { Console.WriteLine(ex.Message); } return(-1); } catch (Exception ex) { Console.Error.WriteLine("Error: unexpected error found."); Console.Error.WriteLine(ex.Message); return(-1); } }
private async Task SearchForHistoricalDocumentsAsync(QueryBundle queryBundle, bool addToStack) { this.tbSandbox.Text = queryBundle.Sandbox; this.tbScid.Text = queryBundle.Scid; this.tbTemplateName.Text = queryBundle.TemplateName; this.tbQueryKey.Text = queryBundle.QueryKey; this.cmbQueryType.SelectedIndex = queryBundle.QueryKeyIndex; this.dateTimePicker1.Value = queryBundle.QueryFrom; this.dateTimePicker2.Value = queryBundle.QueryTo; string eToken = await ToolAuthentication.GetDevTokenSilentlyAsync(this.tbScid.Text, this.tbSandbox.Text); this.lblExplanation.Text = "Searching for MPSD historical documents..."; Tuple <HttpStatusCode, string> response = null; string continuationToken = null; do { response = await this.QueryForHistoricalSessionDocuments(eToken, queryBundle, continuationToken); if (response.Item1 == HttpStatusCode.OK) { continuationToken = response.Item2; } else { continuationToken = null; } }while (continuationToken != null); this.downloadPanel.Hide(); if (response.Item1 != HttpStatusCode.OK) { if (response.Item1 == HttpStatusCode.Unauthorized) { MessageBox.Show("Your auth token has expired. Re-try the query to get a new token", "Expired Token"); } else if (response.Item1 == HttpStatusCode.InternalServerError) { MessageBox.Show("The server is busy. Please try again", QueryFailure); } else { MessageBox.Show(response.Item2, QueryFailure); } } else { if (this.listView1.Items.Count == 0) { this.btnPriorQuery.Visible = this.queryStack.Count > 0; // show the back button following un unsuccesful query (if there was a prior successul one) MessageBox.Show("No results found. Try expanding the query time window (if possible)\nor use different search criteria.", "Query Results"); } else { if (addToStack) { this.queryStack.Push(queryBundle); // succesful query, so remember it this.btnPriorQuery.Visible = this.queryStack.Count > 1; } else { this.btnPriorQuery.Visible = this.queryStack.Count > 0; } } } }
private async void SaveSessionHistoryToolStripMenuItem_Click(object sender, EventArgs e) { if (this.listView1.SelectedItems.Count != 1) { return; } int selectedIndex = this.listView1.SelectedIndices[0]; HistoricalDocument document = new HistoricalDocument() { SessionName = this.listView1.Items[selectedIndex].SubItems[0].Text, Branch = this.listView1.Items[selectedIndex].SubItems[1].Text, NumSnapshots = int.Parse(this.listView1.Items[selectedIndex].SubItems[2].Text), LastModified = this.listView1.Items[selectedIndex].SubItems[3].Text, IsExpired = bool.Parse(this.listView1.Items[selectedIndex].SubItems[4].Text), ActivityId = this.listView1.Items[selectedIndex].SubItems[5].Text, }; string eToken = await ToolAuthentication.GetDevTokenSilentlyAsync(this.tbScid.Text, this.tbSandbox.Text); this.lblExplanation.Text = "Downloading change history for the selected session..."; Tuple <SessionHistoryDocumentResponse, string> queryResponse = await this.QueryForDocSessionHistoryAsync(eToken, document.SessionName, document.Branch); if (queryResponse.Item2 != null) { this.downloadPanel.Hide(); MessageBox.Show(string.Format("{0}\n\nThe server may have been busy.\nPlease try again.", queryResponse.Item2), "Error!"); return; } string errMsg = null; if (queryResponse.Item1 != null) { foreach (var item in queryResponse.Item1.Results) { Tuple <string, string> getSnapshotResponse = await this.QueryForDocSessionHistoryChangeAsync(document.SessionName, document.Branch, item.ChangeNumber); string snapshotBody = getSnapshotResponse.Item1; errMsg = getSnapshotResponse.Item2; if (errMsg != null) { break; } DocumentStateSnapshot snapshot = new DocumentStateSnapshot() { Change = item.ChangeNumber, ModifiedByXuids = item.ChangedBy, Timestamp = item.Timestamp, TitleId = item.TitleId, ServiceId = item.ServiceId, CorrelationId = item.CorrelationId, ChangeDetails = item.Details, Body = snapshotBody != null ? snapshotBody : string.Empty }; document.DocumentSnapshots.Add(snapshot); } } this.downloadPanel.Hide(); if (errMsg != null) { MessageBox.Show(string.Format("{0}\n\nPlease try again.", errMsg), "Error"); } else { // serialize the HistoricalDocument to json string testString = JsonConvert.SerializeObject(document); var saveDialog = new SaveFileDialog() { Filter = SessionHistoryFileFilter, FileName = string.Format("{0}~{1}", document.SessionName, document.Branch) }; if (saveDialog.ShowDialog() == DialogResult.OK) { using (StreamWriter sw = new StreamWriter(saveDialog.FileName)) { sw.Write(testString); } } } }
private static async Task <int> OnReset(ResetOptions options) { string xuid = string.Empty; if (options == null) { Console.WriteLine("Unknown parameter error"); return(-1); } if (!string.IsNullOrEmpty(options.TestAccount)) { TestAccount testAccount = await ToolAuthentication.SignInTestAccountAsync(options.TestAccount, options.Sandbox); if (testAccount == null) { Console.Error.WriteLine($"Failed to log in to test account {options.TestAccount}."); return(-1); } xuid = testAccount.Xuid; Console.WriteLine($"Using Test account {options.TestAccount} ({testAccount.Gamertag}) with xuid {xuid}"); } else if (!string.IsNullOrEmpty(options.XboxUserId)) { DevAccount account = ToolAuthentication.LoadLastSignedInUser(); if (account == null) { Console.Error.WriteLine("Resetting by XUID requires a signed in Partner Center account. Please use \"XblDevAccount.exe signin\" to log in."); return(-1); } xuid = options.XboxUserId; Console.WriteLine($"Using Dev account {account.Name} from {account.AccountSource}"); } Console.WriteLine($"Resetting data for player with XUID {xuid} for SCID {options.ServiceConfigurationId} in sandbox {options.Sandbox}"); try { UserResetResult result = await PlayerReset.ResetPlayerDataAsync( options.ServiceConfigurationId, options.Sandbox, xuid); switch (result.OverallResult) { case ResetOverallResult.Succeeded: Console.WriteLine("Player data has been reset successfully."); return(0); case ResetOverallResult.CompletedError: Console.WriteLine("An error occurred while resetting player data:"); if (!string.IsNullOrEmpty(result.HttpErrorMessage)) { Console.WriteLine($"\t{result.HttpErrorMessage}"); } PrintProviderDetails(result.ProviderStatus); return(-1); case ResetOverallResult.Timeout: Console.WriteLine("Player data reset has timed out:"); PrintProviderDetails(result.ProviderStatus); return(-1); default: Console.WriteLine("An unknown error occurred while resetting player data."); return(-1); } } catch (HttpRequestException ex) { Console.WriteLine("Error: player data reset failed"); if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Unauthorized))) { Console.WriteLine( $"Unable to authorize the account with Xbox Live and scid : {options.ServiceConfigurationId} and sandbox : {options.Sandbox}, please contact your administrator."); } else if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Forbidden))) { Console.WriteLine( "Your account doesn't have access to perform the operation, please contact your administrator."); } else { Console.WriteLine(ex.Message); } return(-1); } }