/// <summary> /// Initializes a new instance of the <see cref="WebSocket{T}" /> class. /// </summary> /// <param name="connection">Implementation of a connection object.</param> /// <param name="serverCertificateValidationHandler">Server certificate handler.</param> /// <param name="sendStreams">specifies whether the web socket should send streams (useful for creating mock data).</param> public WebSocket(IDevicePortalConnection connection, Func <object, X509Certificate, X509Chain, SslPolicyErrors, bool> serverCertificateValidationHandler, bool sendStreams = false) { this.sendStreams = sendStreams; this.deviceConnection = connection; this.IsListeningForMessages = false; this.serverCertificateValidationHandler = serverCertificateValidationHandler; }
internal DevicePortal(IDevicePortalConnection connection, Func <ICredentials, Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>, IHttpClient> createHttpClient, IWebSocketFactory webSocketFactory = null) { this.deviceConnection = connection; this.HttpClient = createHttpClient(connection.Credentials, this.ServerCertificateValidation); this.WebSockets = webSocketFactory ?? new DefaultWebSocketFactory(); }
//------------------------------------------------------------------- // Constructors //------------------------------------------------------------------- #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DevicePortalViewModel" /> class. /// </summary> /// <param name="connection">IDevicePortalConnection used for connecting</param> /// <param name="diags">Diagnostic sink for reporting</param> public DevicePortalViewModel(IDevicePortalConnection connection, IDiagnosticSink diags) : base(connection, diags) { this.connectionStatus = DeviceConnectionStatus.None; // Add additional handling for untrusted certs. this.Portal.UnvalidatedCert += this.DoCertValidation; // Default number of retry attempts to make when reestablishing the connection this.ConnectionRetryAttempts = 3; }
//------------------------------------------------------------------- // Constructors //------------------------------------------------------------------- #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DevicePortalCommandModel" /> class. /// </summary> /// <param name="connection">IDevicePortalConnection object used for connecting</param> /// <param name="diags">Diagnostic sink for reporting</param> public DevicePortalCommandModel(IDevicePortalConnection connection, IDiagnosticSink diags) { if (connection == null) { throw new ArgumentException("Must provide a valid IDevicePortalConnection object"); } this.Connection = connection; this.Portal = new DevicePortal(connection); this.diagnostics = diags; this.commandQueue = new ObservableCommandQueue(); this.Ready = true; }
/// <summary> /// Makes sure there is a connection to the device. If device can't be contacted /// it will throw. Does not try to ping the device. /// </summary> /// <returns></returns> /// <remarks>Note that we let exceptions leave this function. We depend on caller for any retry</remarks> private async Task EnsureConnectionAsync() { // Make sure we're not trying multiple connections. // This logic assumes one thread. There will be a race condition // with the isConnecting field if multiple threads are executing this. if (this.isConnecting) { // we're already trying to connect on another task. Wait await WaitForCondition(TimeSpan.FromSeconds(2.0), new CancellationToken(), () => !this.isConnecting); // TODO: maybe make this timeout configurable } this.isConnecting = true; try { if (this.devicePortalConnection == null) { var address = FixupMachineAddress(this.Address, false); this.devicePortalConnection = new DefaultDevicePortalConnection( address, this.UserName, this.Password); this.devicePortal = new DevicePortal(this.devicePortalConnection); this.devicePortal.UnvalidatedCert += (sender, certificate, chain, sslPolicyErrors) => true; // Allow unvalidated certs this.devicePortal.ConnectionStatus += DevicePortalConnectionStatus; } if (this.DeviceConnectionStatus != DeviceConnectionStatus.Connected || this.DeviceConnectionStatus != DeviceConnectionStatus.Connecting) { X509Certificate2 certificate = await this.devicePortal.GetRootDeviceCertificateAsync(); // Establish the connection to the device. await this.devicePortal.ConnectAsync( ssid : null, ssidKey : null, updateConnection : false, manualCertificate : certificate); } } finally { this.isConnecting = false; } }
/// <summary> /// Initializes a new instance of the <see cref="WebSocket{T}" /> class. /// </summary> /// <param name="connection">Implementation of a connection object.</param> /// <param name="sendStreams">specifies whether the web socket should send streams (useful for creating mock data).</param> public WebSocket(IDevicePortalConnection connection, bool sendStreams = false) { this.sendStreams = sendStreams; this.deviceConnection = connection; this.IsListeningForMessages = false; }
/// <summary> /// Initializes a new instance of the <see cref="DevicePortal" /> class. /// </summary> /// <param name="connection">Implementation of a connection object.</param> public DevicePortal(IDevicePortalConnection connection) { this.deviceConnection = connection; }
/// <summary> /// Initializes a new instance of the <see cref="WebSocket{T}" /> class. /// </summary> /// <param name="connection">Implementation of a connection object.</param> /// <param name="serverCertificateValidationHandler">Server certificate handler.</param> /// <param name="sendStreams">specifies whether the web socket should send streams (useful for creating mock data).</param> public MockWebSocket(IDevicePortalConnection connection, Func <object, X509Certificate, X509Chain, SslPolicyErrors, bool> serverCertificateValidationHandler, bool sendStreams = false) : base(connection, serverCertificateValidationHandler, sendStreams) { }
/// <summary> /// Initializes a new instance of the <see cref="SignInAttemptEventArgs" /> class. /// </summary> /// <param name="conn">The IDevicePortalConnection instance associated with the sign in attempt</param> internal SignInAttemptEventArgs(IDevicePortalConnection conn) { this.Connection = conn; }
/// <summary> /// Initializes a new instance of the <see cref="DevicePortal" /> class. /// </summary> /// <param name="connection">Implementation of a connection object.</param> public DevicePortal(IDevicePortalConnection connection) : this(connection, (a, b) => new HttpClientWrapper(a, b)) { }
public WebSocket <T> Create <T>(IDevicePortalConnection connection, Func <object, X509Certificate, X509Chain, SslPolicyErrors, bool> serverCertificateValidationHandler, bool sendStreams = false) => new WebSocket <T>(connection, serverCertificateValidationHandler, sendStreams);
/// <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>."); } } IDevicePortalConnection connection = null; try { if (!parameters.HasParameter(ParameterHelper.WdpUser) || !parameters.HasParameter(ParameterHelper.WdpPassword)) { connection = new DevicePortalConnection(targetConsole); } else { connection = new DevicePortalConnection(targetConsole, parameters.GetParameterValue(ParameterHelper.WdpUser), parameters.GetParameterValue(ParameterHelper.WdpPassword)); } } catch (TypeLoadException) { // Windows 7 doesn't support credential storage so we'll get a TypeLoadException if (!parameters.HasParameter(ParameterHelper.WdpUser) || !parameters.HasParameter(ParameterHelper.WdpPassword)) { 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 { string connectionUri = string.Format("https://{0}:11443", targetConsole); connection = new DefaultDevicePortalConnection(connectionUri, parameters.GetParameterValue(ParameterHelper.WdpUser), parameters.GetParameterValue(ParameterHelper.WdpPassword)); } } DevicePortal portal = new DevicePortal(connection); byte[] rawCert = null; if (parameters.HasParameter(ParameterHelper.Cert)) { string certFile = parameters.GetParameterValue(ParameterHelper.Cert); try { rawCert = File.ReadAllBytes(certFile); connection.AllowCertOverride = true; } catch (Exception e) { throw new Exception(string.Format("Failed to read manual cert file {0}, {1}", certFile, e.Message), e); } } Task connectTask = portal.Connect(updateConnection: false, rawManualCertificate: rawCert); 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 (portal.ConnectionHttpStatusCode != 0) { Console.WriteLine(string.Format("Failed to connect to WDP with HTTP Status code: {0}", portal.ConnectionHttpStatusCode)); } else { Console.WriteLine("Failed to connect to WDP for unknown reason.\n\nEnsure your address is the system IP or hostname ({0}) and the machine has WDP configured.", targetConsole); } } 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); } 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.GetDeviceName(); 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.Reboot(); 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 (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); } }