/// <summary> /// Helper to make the REST call and handle exceptions. /// </summary> /// <param name="portal">DevicePortal reference for communicating with the device.</param> /// <param name="userList">UserList object for updating the remote device.</param> private static void UpdateXboxLiveUsers(DevicePortal portal, UserList userList) { try { Task updateUsers = portal.UpdateXboxLiveUsers(userList); updateUsers.Wait(); } catch (AggregateException e) { if (e.InnerException is DevicePortalException) { DevicePortalException innerException = e.InnerException as DevicePortalException; Console.WriteLine(string.Format("Exception encountered: 0x{0:X} : {1}", innerException.HResult, innerException.Reason)); } else if (e.InnerException is OperationCanceledException) { Console.WriteLine("The operation was cancelled."); } else { Console.WriteLine(string.Format("Unexpected exception encountered: {0}", e.Message)); } return; } }
/// <summary> /// Sends a message to the server. /// </summary> /// <param name="message">The message to send.</param> /// <returns>The task of sending the message to the websocket</returns> protected override async Task SendMessageInternalAsync(string message) { await this.webSocketTask.ConfigureAwait(false); this.webSocketTask.Wait(); using (HttpResponseMessage response = this.webSocketTask.Result) { if (!response.IsSuccessStatusCode) { throw await DevicePortalException.CreateAsync(response); } } }
#pragma warning restore 1998 /// <summary> /// Starts listening for messages from the websocket. /// Once they are received they are parsed and the WebSocketMessageReceived event is raised. /// </summary> /// <returns>The task of listening for messages from the websocket.</returns> protected override async Task StartListeningForMessagesInternalAsync() { this.IsListeningForMessages = true; this.keepListeningForMessages = true; try { while (this.keepListeningForMessages) { await this.webSocketTask.ConfigureAwait(false); using (HttpResponseMessage response = this.webSocketTask.Result) { if (!response.IsSuccessStatusCode) { throw await DevicePortalException.CreateAsync(response); } using (HttpContent content = response.Content) { MemoryStream dataStream = new MemoryStream(); await content.CopyToAsync(dataStream).ConfigureAwait(false); // Ensure we return with the stream pointed at the origin. dataStream.Position = 0; this.ConvertStreamToMessage(dataStream); } } } } catch { } finally { this.stoppedReceivingMessages.Set(); this.IsListeningForMessages = false; } }
public void AddSponsoredUserTest_Failure() { HttpResponseMessage response = new HttpResponseMessage((HttpStatusCode)422); HttpContent content = new StringContent( "{\"ErrorCode\":-2136866553,\"ErrorMessage\":\"The maximum number of sponsored users is already signed in.\"}", System.Text.Encoding.UTF8, "application/json"); response.Content = content; TestHelpers.MockHttpResponder.AddMockResponse(DevicePortal.XboxLiveUserApi, response, HttpMethods.Put); UserList users = new UserList(); UserInfo user = new UserInfo(); user.SponsoredUser = true; users.Add(user); try { Task updateUsersTask = TestHelpers.Portal.UpdateXboxLiveUsersAsync(users); updateUsersTask.Wait(); Assert.Fail("Expected an exception due to mock responder returning failure HRESULT."); } catch (Exception e) { Assert.IsTrue(e is AggregateException); Assert.IsNotNull(e.InnerException); Assert.IsTrue(e.InnerException is DevicePortalException); DevicePortalException exception = e.InnerException as DevicePortalException; Assert.AreEqual(-2136866553, exception.HResult); Assert.AreEqual("The maximum number of sponsored users is already signed in.", exception.Reason); } }
/// <summary> /// Main entry point for handling a Config operation /// </summary> /// <param name="portal">DevicePortal reference for communicating with the device.</param> /// <param name="parameters">Parsed command line parameters.</param> public static void HandleOperation(DevicePortal portal, ParameterHelper parameters) { if (parameters.HasFlag(ParameterHelper.HelpFlag)) { Console.WriteLine(AppUsageMessage); return; } string operationType = parameters.GetParameterValue("subop"); if (string.IsNullOrWhiteSpace(operationType)) { Console.WriteLine("Missing subop parameter"); Console.WriteLine(); Console.WriteLine(AppUsageMessage); return; } operationType = operationType.ToLowerInvariant(); try { if (operationType.Equals("list")) { Task <AppPackages> packagesTask = portal.GetInstalledAppPackages(); packagesTask.Wait(); Console.WriteLine(packagesTask.Result); } else { string packageFullName = parameters.GetParameterValue("pfn"); if (string.IsNullOrEmpty(packageFullName)) { Console.WriteLine("The Package Full Name is required as the /pfn<packageFullName> parameter for this operation."); Console.WriteLine(); Console.WriteLine(AppUsageMessage); return; } if (operationType.Equals("suspend")) { Console.WriteLine("Suspend isn't currently supported, but will be in the future."); } else if (operationType.Equals("resume")) { Console.WriteLine("Resume isn't currently supported, but will be in the future."); } else if (operationType.Equals("launch")) { string aumid = parameters.GetParameterValue("aumid"); if (string.IsNullOrEmpty(aumid)) { Console.WriteLine("The appId (AUMID) is required as the /aumid:<appId> parameter for the launch operation."); Console.WriteLine(); Console.WriteLine(AppUsageMessage); return; } Task launchTask = portal.LaunchApplication(aumid, packageFullName); launchTask.Wait(); Console.WriteLine("Application launched."); } else if (operationType.Equals("terminate")) { Task terminateTask = portal.TerminateApplication(packageFullName); terminateTask.Wait(); Console.WriteLine("Application terminated."); } else if (operationType.Equals("uninstall")) { Task uninstallTask = portal.UninstallApplication(packageFullName); uninstallTask.Wait(); Console.WriteLine("Application uninstalled."); } } } catch (AggregateException e) { if (e.InnerException is DevicePortalException) { DevicePortalException innerException = e.InnerException as DevicePortalException; Console.WriteLine(string.Format("Exception encountered: 0x{0:X} : {1}", innerException.HResult, innerException.Reason)); } else if (e.InnerException is OperationCanceledException) { Console.WriteLine("The operation was cancelled."); } else { Console.WriteLine(string.Format("Unexpected exception encountered: {0}", e.Message)); } return; } }
/// <summary> /// Main entry point /// </summary> /// <param name="args">command line args</param> public static void Main(string[] args) { ParameterHelper parameters = new ParameterHelper(); Program app = new Program(); try { parameters.ParseCommandLine(args); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(); Console.WriteLine(GeneralUsageMessage); return; } if (parameters.HasFlag(ParameterHelper.HelpFlag)) { Console.WriteLine(GeneralUsageMessage); return; } if (!parameters.HasParameter(ParameterHelper.FullAddress) || !parameters.HasParameter(ParameterHelper.WdpUser) || !parameters.HasParameter(ParameterHelper.WdpPassword)) { Console.WriteLine("Missing one or more required parameter(s). Must provide address, user, and pwd"); Console.WriteLine(); Console.WriteLine(GeneralUsageMessage); return; } IDevicePortalConnection connection = new DefaultDevicePortalConnection(parameters.GetParameterValue(ParameterHelper.FullAddress), parameters.GetParameterValue(ParameterHelper.WdpUser), parameters.GetParameterValue(ParameterHelper.WdpPassword)); DevicePortal portal = new DevicePortal(connection); Task connectTask = portal.Connect(updateConnection: false); connectTask.Wait(); if (portal.ConnectionHttpStatusCode != HttpStatusCode.OK) { if (!string.IsNullOrEmpty(portal.ConnectionFailedDescription)) { Console.WriteLine(string.Format("Failed to connect to WDP (HTTP {0}) : {1}", (int)portal.ConnectionHttpStatusCode, portal.ConnectionFailedDescription)); } else { Console.WriteLine("Failed to connect to WDP for unknown reason."); } return; } string directory = "MockData"; if (parameters.HasParameter("directory")) { directory = parameters.GetParameterValue("directory"); } if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (parameters.HasParameter("endpoint")) { HttpMethods httpMethod = HttpMethods.Get; if (parameters.HasParameter("method")) { // This is case sensitive. Since it's only used while generating mocks which is a development time action, // that seems okay. If we want to revisit I'd prefer keeping the casing of the enum and using a switch or // if/else block to manually convert. httpMethod = (HttpMethods)Enum.Parse(typeof(HttpMethods), parameters.GetParameterValue("method")); } string endpoint = parameters.GetParameterValue("endpoint"); string requestBodyFile = parameters.GetParameterValue("requestbody"); if (!string.IsNullOrEmpty(requestBodyFile)) { if (parameters.HasFlag("requestbodymultipartfile")) { string boundaryString = Guid.NewGuid().ToString(); using (MemoryStream dataStream = new MemoryStream()) { byte[] data; FileInfo fi = new FileInfo(requestBodyFile); data = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}\r\n", boundaryString)); dataStream.Write(data, 0, data.Length); CopyFileToRequestStream(fi, dataStream); // Close the multipart request data. data = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--\r\n", boundaryString)); dataStream.Write(data, 0, data.Length); dataStream.Position = 0; string contentType = string.Format("multipart/form-data; boundary={0}", boundaryString); Task saveResponseTask = portal.SaveEndpointResponseToFile(endpoint, directory, httpMethod, dataStream, contentType); saveResponseTask.Wait(); } } else { Stream fileStream = new FileStream(requestBodyFile, FileMode.Open); Task saveResponseTask = portal.SaveEndpointResponseToFile(endpoint, directory, httpMethod, fileStream, "application/json"); saveResponseTask.Wait(); } } else { Task saveResponseTask = portal.SaveEndpointResponseToFile(endpoint, directory, httpMethod); saveResponseTask.Wait(); } } else { foreach (Endpoint endpoint in Endpoints) { HttpMethods httpMethod = endpoint.Method; string finalEndpoint = endpoint.Value; try { Task saveResponseTask = portal.SaveEndpointResponseToFile(finalEndpoint, directory, httpMethod); saveResponseTask.Wait(); } catch (Exception e) { // Print an error message if possible but continue on. // Not all APIs are available on all device types. if (e.InnerException is DevicePortalException) { DevicePortalException exception = e.InnerException as DevicePortalException; Console.WriteLine(string.Format("Failed to generate .dat for {0} with status {1} ({2}).", endpoint, exception.HResult, exception.Reason)); } } } } Console.WriteLine("Data generated in directory {0}.", directory); Console.WriteLine(); Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); Console.WriteLine("Please make sure to remove any personally identifiable information from the\n" + "response(s) (such as alias/emails, ip addresses, and machine names) before\n" + "adding them as mock responses!"); Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); // If a debugger is attached, don't close but instead loop here until // closed. while (Debugger.IsAttached) { Thread.Sleep(0); } }
/// <summary> /// Main entry point /// </summary> /// <param name="args">command line args</param> public static void Main(string[] args) { ParameterHelper parameters = new ParameterHelper(); Program app = new Program(); string targetConsole = string.Empty; try { parameters.ParseCommandLine(args); OperationType operation = OperationType.None; if (parameters.HasParameter(ParameterHelper.Operation)) { operation = OperationStringToEnum(parameters.GetParameterValue("op")); } // Allow /ip: to still function, even though we've moved to /x: in the documentation. if (parameters.HasParameter(ParameterHelper.IpOrHostnameOld) && !parameters.HasParameter(ParameterHelper.IpOrHostname)) { targetConsole = parameters.GetParameterValue(ParameterHelper.IpOrHostnameOld); } else if (parameters.HasParameter(ParameterHelper.IpOrHostname)) { targetConsole = parameters.GetParameterValue(ParameterHelper.IpOrHostname); } if (string.IsNullOrEmpty(targetConsole)) { object regValue; regValue = Microsoft.Win32.Registry.GetValue(DefaultConsoleRegkey, null, null); if (regValue == null) { regValue = Microsoft.Win32.Registry.GetValue(DefaultXtfConsoleRegkey, null, null); } if (regValue is string) { targetConsole = regValue as string; } else { throw new Exception("No default console is currently set. Must provide an ip address or hostname to connect to: /x:<ip or hostname>."); } } string finalConnectionAddress = string.Format("https://{0}:11443", targetConsole); string userName = parameters.GetParameterValue(ParameterHelper.WdpUser); string password = parameters.GetParameterValue(ParameterHelper.WdpPassword); if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) { try { // No creds were provided on the command line. CredManager.RetrieveStoredCreds(targetConsole, ref userName, ref password); } catch (TypeLoadException) { // Windows 7 doesn't support credential storage so we'll get a TypeLoadException throw new Exception("Credential storage is not supported on your PC. It requires Windows 8+ to run. Please provide the user and password parameters."); } } else { try { // Creds were provided on the command line. CredManager.UpdateStoredCreds(targetConsole, userName, password); } catch (TypeLoadException) { // Do nothing. We can't store these on Win7 } } X509Certificate2 cert = null; IDevicePortalConnection connection = new DefaultDevicePortalConnection(finalConnectionAddress, userName, password); DevicePortal portal = new DevicePortal(connection); if (parameters.HasParameter(ParameterHelper.Cert)) { string certFile = parameters.GetParameterValue(ParameterHelper.Cert); try { cert = new X509Certificate2(certFile); } catch (Exception e) { throw new Exception(string.Format("Failed to read manual cert file {0}, {1}", certFile, e.Message), e); } } // Add additional handling for untrusted certs. portal.UnvalidatedCert += app.DoCertValidation; // If a thumbprint is provided, use it for this connection. Otherwise check the registry. if (parameters.HasParameter("thumbprint")) { app.AcceptedThumbprint = parameters.GetParameterValue("thumbprint"); } else { object regValue; regValue = Microsoft.Win32.Registry.GetValue(DefaultConsoleRegkey, targetConsole, null); if (regValue is string) { app.AcceptedThumbprint = regValue as string; } } Task connectTask = portal.ConnectAsync(updateConnection: false, manualCertificate: cert); connectTask.Wait(); if (portal.ConnectionHttpStatusCode != HttpStatusCode.OK) { if (portal.ConnectionHttpStatusCode == HttpStatusCode.Unauthorized) { if (connection.Credentials == null) { Console.WriteLine("The WDP connection was rejected due to missing credentials.\n\nPlease provide the /user:<username> and /pwd:<pwd> parameters on your first call to WDP."); } else { Console.WriteLine("The WDP connection was rejected due to bad credentials.\n\nPlease check the /user:<username> and /pwd:<pwd> parameters."); } } else if (!string.IsNullOrEmpty(portal.ConnectionFailedDescription)) { Console.WriteLine(string.Format("Failed to connect to WDP (HTTP {0}) : {1}", (int)portal.ConnectionHttpStatusCode, portal.ConnectionFailedDescription)); } else { Console.WriteLine("Failed to connect to WDP for unknown reason."); } } else { // If the operation is more than a couple lines, it should // live in its own file. These are arranged alphabetically // for ease of use. switch (operation) { case OperationType.AppOperation: AppOperation.HandleOperation(portal, parameters); break; case OperationType.ConfigOperation: ConfigOperation.HandleOperation(portal, parameters); break; case OperationType.ConnectOperation: // User provided a new ip or hostname to set as the default. if (parameters.HasParameter(ParameterHelper.IpOrHostname) || parameters.HasParameter(ParameterHelper.IpOrHostnameOld)) { Microsoft.Win32.Registry.SetValue(DefaultConsoleRegkey, null, targetConsole); Console.WriteLine("Default console set to {0}", targetConsole); } else { Console.WriteLine("Connected to Default console: {0}", targetConsole); } if (parameters.HasParameter("thumbprint")) { string thumbprint = parameters.GetParameterValue("thumbprint"); Microsoft.Win32.Registry.SetValue(DefaultConsoleRegkey, targetConsole, thumbprint); Console.WriteLine("Thumbprint {0} saved for console with address {1}.", thumbprint, targetConsole); } break; case OperationType.FiddlerOperation: FiddlerOperation.HandleOperation(portal, parameters); break; case OperationType.FileOperation: FileOperation.HandleOperation(portal, parameters); break; case OperationType.InfoOperation: Console.WriteLine("OS version: " + portal.OperatingSystemVersion); Console.WriteLine("Platform: " + portal.PlatformName + " (" + portal.Platform.ToString() + ")"); Task <string> getNameTask = portal.GetDeviceNameAsync(); getNameTask.Wait(); Console.WriteLine("Device name: " + getNameTask.Result); break; case OperationType.InstallOperation: // Ensure we have an IP since SMB might need it for path generation. parameters.AddParameter(ParameterHelper.IpOrHostname, targetConsole); InstallOperation.HandleOperation(portal, parameters); break; case OperationType.ListProcessesOperation: ListProcessesOperation.HandleOperation(portal, parameters); break; case OperationType.RebootOperation: Task rebootTask = portal.RebootAsync(); rebootTask.Wait(); Console.WriteLine("Rebooting device."); break; case OperationType.SandboxOperation: SandboxOperation.HandleOperation(portal, parameters); break; case OperationType.ScreenshotOperation: ScreenshotOperation.HandleOperation(portal, parameters); break; case OperationType.SystemPerfOperation: SystemPerfOperation.HandleOperation(portal, parameters); break; case OperationType.XblUserOperation: UserOperation.HandleOperation(portal, parameters); break; default: Console.WriteLine("Successfully connected to console but no operation was specified. \n" + "Use the '/op:<operation type>' parameter to run a specified operation."); Console.WriteLine(); Console.WriteLine(AvailableOperationsText); break; } } } catch (AggregateException e) { if (e.InnerException is DevicePortalException) { DevicePortalException innerException = e.InnerException as DevicePortalException; Console.WriteLine(string.Format("Exception encountered: {0}, hr = 0x{1:X} : {2}", innerException.StatusCode, innerException.HResult, innerException.Reason)); } else { Console.WriteLine(string.Format("Unexpected exception encountered: {0}", e.Message)); } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(); Console.WriteLine(GeneralUsageMessage); } // If a debugger is attached, don't close but instead loop here until // closed. while (Debugger.IsAttached) { Thread.Sleep(0); } }
/// <summary> /// Main entry point for handling an install operation /// </summary> /// <param name="portal">DevicePortal reference for communicating with the device.</param> /// <param name="parameters">Parsed command line parameters.</param> public static void HandleOperation(DevicePortal portal, ParameterHelper parameters) { if (parameters.HasFlag(ParameterHelper.HelpFlag)) { Console.WriteLine(XblInstallUsageMessage); return; } InstallOperation operation = new InstallOperation(portal); portal.AppInstallStatus += operation.AppInstallStatusHandler; if (parameters.HasFlag(ParameterHelper.VerboseFlag)) { operation.verbose = true; } List <string> dependencies = new List <string>(); // Build up the list of dependencies. if (parameters.HasParameter("depend")) { dependencies.AddRange(parameters.GetParameterValue("depend").Split(';')); } string certificate = parameters.GetParameterValue("cer"); string appxFile = parameters.GetParameterValue("appx"); string folderPath = parameters.GetParameterValue("folder"); string registerPath = parameters.GetParameterValue("register"); try { if (!string.IsNullOrEmpty(appxFile)) { operation.mreAppInstall.Reset(); Task installTask = portal.InstallApplication(null, appxFile, dependencies, certificate); operation.mreAppInstall.WaitOne(); if (operation.installResults.Status == ApplicationInstallStatus.Completed) { Console.WriteLine("Install complete."); } else { Console.WriteLine("Install failed in phase {0}. {1}", operation.installResults.Phase, operation.installResults.Message); } } else if (!string.IsNullOrEmpty(folderPath)) { // Install all dependencies one at a time (loose folder doesn't handle dependencies well). foreach (string dependency in dependencies) { operation.mreAppInstall.Reset(); Task installTask = portal.InstallApplication(null, dependency, new List <string>()); operation.mreAppInstall.WaitOne(); if (operation.installResults.Status != ApplicationInstallStatus.Completed) { Console.WriteLine("Deploy failed during dependency installation. {0}", operation.installResults.Message); return; } } if (!Directory.Exists(folderPath)) { Console.WriteLine("Failed to find provided loose folder."); Console.WriteLine(); Console.WriteLine(XblInstallUsageMessage); return; } // Remove any trailing slash if (folderPath.EndsWith("\\")) { folderPath = folderPath.Remove(folderPath.Length - 1); } string destinationFolderName = parameters.GetParameterValue("destfoldername"); if (string.IsNullOrEmpty(destinationFolderName)) { // Get just the folder name string folderName = folderPath.Substring(folderPath.LastIndexOf('\\') + 1); destinationFolderName = folderName; } string transferType = parameters.GetParameterValue("transfer"); if (string.IsNullOrEmpty(transferType) || string.Equals(transferType, "smb", StringComparison.OrdinalIgnoreCase)) { string shareName = Path.Combine("\\\\", parameters.GetParameterValue(ParameterHelper.IpOrHostname), "DevelopmentFiles"); string destinationFolder = Path.Combine(shareName, "LooseApps", destinationFolderName); try { operation.CopyDirectory(folderPath, destinationFolder); } catch (IOException e) { if (e.HResult == ErrorLogonFailureHresult) { Task <SmbInfo> smbTask = portal.GetSmbShareInfo(); smbTask.Wait(); // Set the username/password for accessing the share. NetworkShare.DisconnectFromShare(shareName, true); int connected = NetworkShare.ConnectToShare(shareName, smbTask.Result.Username, smbTask.Result.Password); if (connected != 0) { Console.WriteLine(string.Format("Failed to connect to the network share: {0}", connected)); return; } operation.CopyDirectory(folderPath, destinationFolder); NetworkShare.DisconnectFromShare(shareName, false); } else { Console.WriteLine(string.Format("Unexpected exception encountered: {0}", e.Message)); return; } } } else if (string.Equals(transferType, "http", StringComparison.OrdinalIgnoreCase)) { operation.UploadDirectoryOverHttp(folderPath, destinationFolderName); } else { Console.WriteLine(string.Format("Unexpected transfer type received: {0}. Expecting one of SMB or HTTP.", transferType)); return; } Task registerTask = portal.RegisterApplication(destinationFolderName); registerTask.Wait(); Console.WriteLine("Install complete."); } else if (!string.IsNullOrEmpty(registerPath)) { Task registerTask = portal.RegisterApplication(registerPath); registerTask.Wait(); Console.WriteLine("Registration complete."); } else { Console.WriteLine("Must provide an appx package, loose folder, or path to register."); Console.WriteLine(); Console.WriteLine(XblInstallUsageMessage); return; } } catch (AggregateException e) { if (e.InnerException is DevicePortalException) { DevicePortalException innerException = e.InnerException as DevicePortalException; Console.WriteLine(string.Format("Exception encountered: {0}, hr = 0x{1:X} : {2}", innerException.StatusCode, innerException.HResult, innerException.Reason)); } else if (e.InnerException is OperationCanceledException) { Console.WriteLine("The operation was cancelled."); } else { Console.WriteLine(string.Format("Unexpected exception encountered: {0}", e.Message)); } return; } }
/// <summary> /// Main entry point for handling a Fiddler operation /// </summary> /// <param name="portal">DevicePortal reference for communicating with the device.</param> /// <param name="parameters">Parsed command line parameters.</param> public static void HandleOperation(DevicePortal portal, ParameterHelper parameters) { if (parameters.HasFlag(ParameterHelper.HelpFlag)) { Console.WriteLine(FiddlerUsageMessage); return; } string state = parameters.GetParameterValue("state"); if (string.IsNullOrEmpty(state)) { Console.WriteLine("/state parameter is required."); Console.WriteLine(); Console.WriteLine(FiddlerUsageMessage); return; } try { if (string.Equals(state, "on", StringComparison.OrdinalIgnoreCase)) { string proxyAddress = parameters.GetParameterValue("proxyaddress"); string proxyPort = parameters.GetParameterValue("proxyport"); if (string.IsNullOrEmpty(proxyAddress) || string.IsNullOrEmpty(proxyPort)) { Console.WriteLine("/proxyaddress and /proxyport are required for enabling Fiddler."); Console.WriteLine(); Console.WriteLine(FiddlerUsageMessage); return; } Task fiddlerEnableTask = portal.EnableFiddlerTracing(proxyAddress, proxyPort, parameters.GetParameterValue("certpath")); fiddlerEnableTask.Wait(); Console.WriteLine("Fiddler enabled."); } else if (string.Equals(state, "off", StringComparison.OrdinalIgnoreCase)) { Task fiddlerDisableTask = portal.DisableFiddlerTracing(); fiddlerDisableTask.Wait(); Console.WriteLine("Fiddler disabled."); } else { Console.WriteLine("Unknown state parameter: {0}. Must be 'on' or 'off'.", state); Console.WriteLine(); Console.WriteLine(FiddlerUsageMessage); return; } if (parameters.HasFlag("reboot")) { Task rebootTask = portal.Reboot(); rebootTask.Wait(); Console.WriteLine("Console rebooting..."); } else { Console.WriteLine("A reboot is required before this takes effect."); } } catch (AggregateException e) { if (e.InnerException is DevicePortalException) { DevicePortalException innerException = e.InnerException as DevicePortalException; Console.WriteLine(string.Format("Exception encountered: {0}, hr = 0x{1:X} : {2}", innerException.StatusCode, innerException.HResult, innerException.Reason)); } else { Console.WriteLine(string.Format("Unexpected exception encountered: {0}", e.Message)); } return; } }
/// <summary> /// Main entry point for handling a Setting operation /// </summary> /// <param name="portal">DevicePortal reference for communicating with the device.</param> /// <param name="parameters">Parsed command line parameters.</param> public static void HandleOperation(DevicePortal portal, ParameterHelper parameters) { if (parameters.HasFlag(ParameterHelper.HelpFlag)) { Console.WriteLine(XblFileUsageMessage); return; } string operationType = parameters.GetParameterValue("subop"); if (string.IsNullOrWhiteSpace(operationType)) { Console.WriteLine("Missing subop parameter"); Console.WriteLine(); Console.WriteLine(XblFileUsageMessage); return; } operationType = operationType.ToLowerInvariant(); string knownFolderId = parameters.GetParameterValue("knownfolderid"); string subPath = parameters.GetParameterValue("subpath"); string packageFullName = parameters.GetParameterValue("packagefullname"); try { if (operationType.Equals("knownfolders")) { Task <KnownFolders> getKnownFoldersTask = portal.GetKnownFolders(); getKnownFoldersTask.Wait(); Console.WriteLine(getKnownFoldersTask.Result); } else { if (string.IsNullOrWhiteSpace(knownFolderId)) { Console.WriteLine("Missing knownfolderid parameter"); Console.WriteLine(); Console.WriteLine(XblFileUsageMessage); return; } if (operationType.Equals("dir")) { Task <FolderContents> getDirectoryContents = portal.GetFolderContents(knownFolderId, subPath, packageFullName); getDirectoryContents.Wait(); Console.WriteLine(getDirectoryContents.Result); } else if (operationType.Equals("upload")) { string filepath = parameters.GetParameterValue("filepath"); if (string.IsNullOrWhiteSpace(filepath)) { Console.WriteLine("Missing filepath parameter"); Console.WriteLine(); Console.WriteLine(XblFileUsageMessage); return; } Task uploadFileTask = portal.UploadFile(knownFolderId, filepath, subPath, packageFullName); uploadFileTask.Wait(); Console.WriteLine(string.Format("{0} uploaded.", filepath)); } else { string filename = parameters.GetParameterValue("filename"); if (string.IsNullOrWhiteSpace(filename)) { Console.WriteLine("Missing filename parameter"); Console.WriteLine(); Console.WriteLine(XblFileUsageMessage); return; } if (operationType.Equals("download")) { string destination = parameters.GetParameterValue("destination"); if (string.IsNullOrWhiteSpace(destination)) { Console.WriteLine("Missing destination parameter"); Console.WriteLine(); Console.WriteLine(XblFileUsageMessage); return; } destination += "/" + filename; Task <Stream> getFile = portal.GetFile(knownFolderId, filename, subPath, packageFullName); getFile.Wait(); using (FileStream filestream = new FileStream(destination, FileMode.OpenOrCreate, FileAccess.Write)) { getFile.Result.CopyTo(filestream); } Console.WriteLine(string.Format("Downloaded {0}.", destination)); } else if (operationType.Equals("rename")) { string newfilename = parameters.GetParameterValue("newfilename"); if (string.IsNullOrWhiteSpace(newfilename)) { Console.WriteLine("Missing newfilename parameter"); Console.WriteLine(); Console.WriteLine(XblFileUsageMessage); return; } Task renameFileTask = portal.RenameFile(knownFolderId, filename, newfilename, subPath, packageFullName); renameFileTask.Wait(); Console.WriteLine(string.Format("Renamed {0} to {1}.", filename, newfilename)); } else if (operationType.Equals("delete")) { Task deleteFileTask = portal.DeleteFile(knownFolderId, filename, subPath, packageFullName); deleteFileTask.Wait(); Console.WriteLine(string.Format("Deleted {0}.", filename)); } } } } catch (AggregateException e) { if (e.InnerException != null && e.InnerException is DevicePortalException) { DevicePortalException exception = e.InnerException as DevicePortalException; Console.WriteLine(string.Format("HTTP Status: {0}, Hresult: 0x{1:X8}. {2}", exception.StatusCode, exception.HResult, exception.Reason)); } } }