Example #1
0
        /// <summary>
        /// Connects to a HoloLens using the provided credentials.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task ConnectAsync(
            string address,
            string userName,
            string password)
        {
            this.devicePortalConnection = new HoloLensDevicePortalConnection(
                address,
                userName,
                password);
            DevicePortal portal = new DevicePortal(this.devicePortalConnection);

            portal.ConnectionStatus += DevicePortal_ConnectionStatus;

            // We are physically connected to the device.
            // We can safely accept the device's root certificate.
            Certificate certificate = await portal.GetRootDeviceCertificateAsync(true);

            // Establish the connection to the device.
            // TODO: Add support for optionally setting the SSID and key.
            await portal.ConnectAsync(
                null,
                null,
                updateConnection : true,
                manualCertificate : certificate);
        }
        /// <summary>
        /// Validate the server certificate
        /// </summary>
        /// <param name="sender">The sender object</param>
        /// <param name="certificate">The server's certificate</param>
        /// <param name="chain">The cert chain</param>
        /// <param name="sslPolicyErrors">Policy Errors</param>
        /// <returns>whether the cert passes validation</returns>
        private bool DoCertValidation(DevicePortal sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            X509Certificate2 cert = new X509Certificate2(certificate);

            // If we have previously said to accept this cert, don't prompt again for this session.
            if (!string.IsNullOrEmpty(this.thumbprint) && this.thumbprint.Equals(cert.Thumbprint, StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            // We could alternatively ask the user if they wanted to always trust
            // this device and we could persist the thumbprint in some way (registry, database, filesystem, etc).
            MessageBoxResult result = MessageBox.Show(string.Format(
                                                          "Do you want to accept the following certificate?\n\nThumbprint:\n  {0}\nIssuer:\n  {1}",
                                                          cert.Thumbprint,
                                                          cert.Issuer),
                                                      "Untrusted Certificate Detected",
                                                      MessageBoxButton.YesNo,
                                                      MessageBoxImage.Question,
                                                      MessageBoxResult.No);

            if (result == MessageBoxResult.Yes)
            {
                thumbprint = cert.Thumbprint;
                return(true);
            }
            return(false);
        }
Example #3
0
        private async Task <bool> TryAuthenticateAsync()
        {
            try
            {
                // Create portal object
                portal = new DevicePortal(
                    new DefaultDevicePortalConnection(
                        "https://127.0.0.1",
                        UserNameBox.Text,
                        PasswordBox.Password));

                // Get cert (OK to use untrusted since it's loopback)
                await portal.GetRootDeviceCertificate(acceptUntrustedCerts : true);

                // Attempt to connect
                await portal.Connect();

                // Get IPD
                var ipd = await portal.GetInterPupilaryDistance();

                // Success!
                return(true);
            }
            catch (Exception)
            {
                // Problem
                await new MessageDialog("Authentication was not successful. Please make sure Device Portal is enabled and check your password.", "Error").ShowAsync();
                return(false);
            }
        }
Example #4
0
        private async Task <bool> TryAuthenticateAsync()
        {
            try
            {
                // Create portal object
                var portal = new DevicePortal(
                    new DefaultDevicePortalConnection(
                        "https://127.0.0.1",
                        UserNameBox.Text,
                        PasswordBox.Password));

                // Attempt to connect
                await portal.Connect();

                // Get IPD
                var ipd = await portal.GetInterPupilaryDistance();

                // Success!
                return(true);
            }
            catch (Exception ex)
            {
                // Problem
                await new MessageDialog(ex.Message, "Error").ShowAsync();
                return(false);
            }
        }
        /// <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>
        /// Connects to a HoloLens using the provided credentials.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task ConnectAsync(
            string address,
            string userName,
            string password)
        {
            this.devicePortalConnection = new HoloLensDevicePortalConnection(
                address,
                userName,
                password);
            DevicePortal portal = new DevicePortal(this.devicePortalConnection);

            portal.ConnectionStatus += DevicePortal_ConnectionStatus;

            // If the address is localhost (127.0.0.1), we are physically connected
            // to the HoloLens. This allows us to implicitly trust the device
            // certificate.
            //
            // !! NOTE: UWP applications are not allowed to connect to localhost
            // unless explicitly configured.
            // * Development - Visual Studio performs this configuration automatically.
            // * Side-loading - Please see README.md for more details.
            // * Store submissions - Use only non-loopback connections.
            Certificate certificate = await portal.GetRootDeviceCertificateAsync(true);

            // Establish the connection to the device.
            // TODO: Add support for optionally setting the SSID and key.
            await portal.ConnectAsync(
                null,
                null,
                updateConnection : true,
                manualCertificate : certificate);
        }
Example #7
0
        /// <summary>
        /// Handles the ConnectionStatus event.
        /// </summary>
        /// <param name="sender">The object which sent this event.</param>
        /// <param name="args">Event arguments.</param>
        private void DevicePortal_ConnectionStatus(
            DevicePortal sender,
            DeviceConnectionStatusEventArgs args)
        {
            if (args.Status == DeviceConnectionStatus.Connected)
            {
                // Connection successfully established.
                this.firstContact = true;
                this.devicePortal = sender;
                this.devicePortal.AppInstallStatus += DevicePortal_AppInstallStatus;
                this.devicePortal.ConnectionStatus -= DevicePortal_ConnectionStatus;

                if (this.connectOptions.DeployNameToDevice)
                {
                    Task.Run(
                        async() =>
                    {
                        if (await this.SetDeviceNameAsync(this.connectOptions.Name))
                        {
                            await this.RebootAsync();
                        }
                    });
                }
            }
            else if (args.Status == DeviceConnectionStatus.Failed)
            {
                // Connection failed.
                this.firstContact = false;
                this.devicePortal.ConnectionStatus -= DevicePortal_ConnectionStatus;

                throw new Exception(args.Message);
            }
        }
Example #8
0
        public async Task <bool> Initialize(bool promptCredentials = false)
        {
            var result = true;

            if (promptCredentials)
            {
                result = (bool)PromptForCredentials();
            }
            if (!result)
            {
                return(false);
            }

            Portal = new DevicePortal(
                new DefaultDevicePortalConnection(
                    ipAddress,
                    username,
                    password));


            await Portal.Connect(null, null, autoDetectIP);

            ipAddress = Portal.Address;
            return(true);
        }
        static async public Task SetXboxLiveSandboxAsync(string url, string sandbox, string userName = null, string password = null)
        {
            DevicePortal connection = GetConnection(url, userName, password);
            await connection.SetXboxLiveSandboxAsync(sandbox);

            await connection.RebootAsync();
        }
        /// <summary>
        /// Main entry point for handling a Screenshot 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(XblScreenshotUsageMessage);
                return;
            }

            string filepath = parameters.GetParameterValue("filepath");

            if (string.IsNullOrEmpty(filepath))
            {
                filepath = "xbox_screenshot.png";
            }

            if (File.Exists(filepath) && !parameters.HasFlag("override"))
            {
                Console.WriteLine("Found an existing file: {0}. Specify /override flag to override this file.", filepath);
            }
            else
            {
                Task <Stream> screenshotTask = portal.TakeXboxScreenshotAsync();
                screenshotTask.Wait();

                using (var fileStream = new FileStream(filepath, FileMode.Create))
                {
                    screenshotTask.Result.CopyTo(fileStream);
                }

                Console.WriteLine("Screenshot saved as {0}.", filepath);
            }
        }
        /// <summary>
        /// Click handler for the connectToDevice button.
        /// </summary>
        /// <param name="sender">The caller of this method.</param>
        /// <param name="e">The arguments associated with this event.</param>
        private void ConnectToDevice_Click(object sender, RoutedEventArgs e)
        {
            this.EnableConnectionControls(false);
            this.EnableDeviceControls(false);

            this.ClearOutput();

            portal = new DevicePortal(
                new DefaultDevicePortalConnection(
                    this.address.Text,
                    this.username.Text,
                    this.password.Password));

            // Add additional handling for untrusted certs.
            portal.UnvalidatedCert += DoCertValidation;

            StringBuilder sb          = new StringBuilder();
            Task          connectTask = new Task(
                async() =>
            {
                sb.Append(this.MarshalGetCommandOutput());
                sb.AppendLine("Connecting...");
                this.MarshalUpdateCommandOutput(sb.ToString());
                portal.ConnectionStatus += (portal, connectArgs) =>
                {
                    if (connectArgs.Status == DeviceConnectionStatus.Connected)
                    {
                        sb.Append("Connected to: ");
                        sb.AppendLine(portal.Address);
                        sb.Append("OS version: ");
                        sb.AppendLine(portal.OperatingSystemVersion);
                        sb.Append("Device family: ");
                        sb.AppendLine(portal.DeviceFamily);
                        sb.Append("Platform: ");
                        sb.AppendLine(String.Format("{0} ({1})",
                                                    portal.PlatformName,
                                                    portal.Platform.ToString()));
                    }
                    else if (connectArgs.Status == DeviceConnectionStatus.Failed)
                    {
                        sb.AppendLine("Failed to connect to the device.");
                        sb.AppendLine(connectArgs.Message);
                    }
                };

                await portal.ConnectAsync();

                this.MarshalUpdateCommandOutput(sb.ToString());
            });

            Task continuationTask = connectTask.ContinueWith(
                (t) =>
            {
                this.MarshalEnableDeviceControls(true);
                this.MarshalEnableConnectionControls(true);
            });

            connectTask.Start();
        }
        public AppOperation(DevicePortal portal)
        {
            if (portal == null)
            {
                throw new System.ArgumentNullException("Must specify a valid DevicePortal object");
            }

            _portal           = portal;
            _runningOperation = new SemaphoreSlim(1, 1);
        }
Example #13
0
    private async Task <bool> AuthSilentAsync()
    {
        // Placeholder
        PasswordCredential cred = null;

        // Try to get user name and password
        try
        {
            cred = vault.FindAllByResource(PortalResourceName).FirstOrDefault();

            // Password does not come across with the method above. We must call another method.
            if (cred != null)
            {
                cred = vault.Retrieve(PortalResourceName, cred.UserName);
            }
        }
        catch { }

        // If no credentials were found, fail
        if (cred == null)
        {
            return(false);
        }

        // Credentials found. Try and log into portal
        try
        {
            // Create portal object
            portal = new DevicePortal(
                new DefaultDevicePortalConnection(
                    "https://127.0.0.1",
                    cred.UserName,
                    cred.Password));

            // Get cert (OK to use untrusted since it's loopback)
            await portal.GetRootDeviceCertificate(acceptUntrustedCerts : true);

            // Attempt to connect
            await portal.Connect();

            // Get IPD
            var ipd = await portal.GetInterPupilaryDistance();

            // Success!
            return(true);
        }
        catch (Exception ex)
        {
            // Problem
            ShowError(ex.Message);
            return(false);
        }
    }
 public static bool TryExecuteApplicationOperation(DevicePortal portal, ParameterHelper parameters)
 {
     try
     {
         var appOperation = new AppOperation(portal);
         appOperation.ExecuteOperation(AppOperation.OperationStringToEnum(parameters.GetParameterValue(ParameterHelper.Operation)), parameters);
     }
     catch (Exception)
     {
         return(false);
     }
     return(true);
 }
Example #15
0
        private void DevicePortalConnectionStatus(DevicePortal sender, DeviceConnectionStatusEventArgs args)
        {
            // This can get called back on random threads.  Marshal it back to the UI thread if needed

            if (MainThread.IsMainThread)
            {
                this.DeviceConnectionStatus = args.Status;
            }
            else
            {
                // Not clear if this is the right thing to do in the Xamarin world using TPL
                MainThread.BeginInvokeOnMainThread(() => { this.DevicePortalConnectionStatus(sender, args); });
            }
        }
        /// <summary>
        /// Main entry point for handling a System Perf 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)
        {
            SystemPerformanceInformation systemPerformanceInformation = null;

            if (parameters.HasFlag(ParameterHelper.Listen))
            {
                ManualResetEvent systemPerfReceived = new ManualResetEvent(false);

                WebSocketMessageReceivedEventHandler <SystemPerformanceInformation> systemPerfReceivedHandler =
                    delegate(DevicePortal sender, WebSocketMessageReceivedEventArgs <SystemPerformanceInformation> sysPerfInfoArgs)
                {
                    if (sysPerfInfoArgs.Message != null)
                    {
                        systemPerformanceInformation = sysPerfInfoArgs.Message;
                        systemPerfReceived.Set();
                    }
                };

                portal.SystemPerfMessageReceived += systemPerfReceivedHandler;

                Task startListeningForSystemPerfTask = portal.StartListeningForSystemPerf();
                startListeningForSystemPerfTask.Wait();

                systemPerfReceived.WaitOne();

                Task stopListeningForSystemPerfTask = portal.StopListeningForRunningProcesses();
                stopListeningForSystemPerfTask.Wait();

                portal.SystemPerfMessageReceived -= systemPerfReceivedHandler;
            }
            else
            {
                Task <SystemPerformanceInformation> getRunningProcessesTask = portal.GetSystemPerf();
                systemPerformanceInformation = getRunningProcessesTask.Result;
            }

            Console.WriteLine("Available Pages: " + systemPerformanceInformation.AvailablePages);
            Console.WriteLine("Commit Limit: " + systemPerformanceInformation.CommitLimit);
            Console.WriteLine("Commited Pages: " + systemPerformanceInformation.CommittedPages);
            Console.WriteLine("CPU Load: " + systemPerformanceInformation.CpuLoad);
            Console.WriteLine("IoOther Speed: " + systemPerformanceInformation.IoOtherSpeed);
            Console.WriteLine("IoRead Speed: " + systemPerformanceInformation.IoReadSpeed);
            Console.WriteLine("IoWrite Speed: " + systemPerformanceInformation.IoWriteSpeed);
            Console.WriteLine("Non-paged Pool Pages: " + systemPerformanceInformation.NonPagedPoolPages);
            Console.WriteLine("Paged Pool Pages: " + systemPerformanceInformation.PagedPoolPages);
            Console.WriteLine("Page Size: " + systemPerformanceInformation.PageSize);
            Console.WriteLine("Total Installed Kb: " + systemPerformanceInformation.TotalInstalledKb);
            Console.WriteLine("Total Pages: " + systemPerformanceInformation.TotalPages);
        }
Example #17
0
        /// <summary>
        /// Cleans up encapsulated resources.
        /// </summary>
        public void Dispose()
        {
            if (this.devicePortal != null)
            {
                this.devicePortal.AppInstallStatus += DevicePortal_AppInstallStatus;
                this.devicePortal = null;
            }

            // Release the resources we manage.
            this.heartbeatTimer?.Dispose();
            this.heartbeatTimer = null;

                        // Suppress finalization to avoid attempting to clean up twice.
                        GC.SuppressFinalize(this);
        }
        /// <summary>
        /// TextChanged handler for the address text box.
        /// </summary>
        /// <param name="sender">The caller of this method.</param>
        /// <param name="e">The arguments associated with this event.</param>


        private async void btnTakePicture2_Click(object sender, RoutedEventArgs e)
        {
            portal = new DevicePortal(
                new DefaultDevicePortalConnection(HoloLensUrl, "Tolegen", "*****"));

            StringBuilder sb = new StringBuilder();

            sb.Append(this.messageb.Text);
            sb.AppendLine("Connecting...");
            this.messageb.Text       = sb.ToString();
            portal.ConnectionStatus += (portal, connectArgs) =>
            {
                if (connectArgs.Status == DeviceConnectionStatus.Connected)
                {
                    sb.Append("Connected to: ");
                    sb.AppendLine(portal.Address);
                    sb.Append("OS version: ");
                    sb.AppendLine(portal.OperatingSystemVersion);
                    sb.Append("Device family: ");
                    sb.AppendLine(portal.DeviceFamily);
                    sb.Append("Platform: ");
                    sb.AppendLine(String.Format("{0} ({1})",
                                                portal.PlatformName,
                                                portal.Platform.ToString()));
                }
                else if (connectArgs.Status == DeviceConnectionStatus.Failed)
                {
                    sb.AppendLine("Failed to connect to the device.");
                    sb.AppendLine(connectArgs.Message);
                }
            };
            try
            {
                // If the user wants to allow untrusted connections, make a call to GetRootDeviceCertificate
                // with acceptUntrustedCerts set to true. This will enable untrusted connections for the
                // remainder of this session.

                this.certificate = await portal.GetRootDeviceCertificateAsync(true);

                await portal.ConnectAsync(manualCertificate : this.certificate);
            }
            catch (Exception exception)
            {
                sb.AppendLine(exception.Message);
            }
            this.messageb.Text = sb.ToString();
        }
Example #19
0
        /// <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;
            }
        }
Example #20
0
    public void ContinueAuthFromLogin(DevicePortal portal)
    {
        // Overwrite portal variable with the one passed to us from auth window
        this.portal = portal;

        // If we have a valid portal we're signed in
        if (portal != null)
        {
            State = FBControllerState.LoggedIn;
        }
        else
        {
            State = FBControllerState.LoggedOut;
        }

        // Auth view has been closed. Continue auth state machine.
        AuthStateMachine();
    }
        static private DevicePortal GetConnection(string url, string userName, string password)
        {
            DevicePortal connection = connections.GetOrAdd(url, (key) =>
            {
                var newConnection              = new DevicePortal(new DefaultDevicePortalConnection(key, userName, password));
                newConnection.UnvalidatedCert += Connection_UnvalidatedCert;
                newConnection.ConnectAsync().Wait();

                if (newConnection.ConnectionHttpStatusCode != HttpStatusCode.OK)
                {
                    throw new DevicePortalException(newConnection.ConnectionHttpStatusCode, "Failed to connect to windows develop portal: " + newConnection.ConnectionFailedDescription);
                }

                return(newConnection);
            });

            return(connection);
        }
        /// <summary>
        /// Main entry point for handling listing processes
        /// </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)
        {
            RunningProcesses runningProcesses = null;

            if (parameters.HasFlag(ParameterHelper.Listen))
            {
                ManualResetEvent runningProcessesReceived = new ManualResetEvent(false);

                WebSocketMessageReceivedEventHandler <RunningProcesses> runningProcessesReceivedHandler =
                    delegate(DevicePortal sender, WebSocketMessageReceivedEventArgs <RunningProcesses> runningProccesesArgs)
                {
                    if (runningProccesesArgs.Message != null)
                    {
                        runningProcesses = runningProccesesArgs.Message;
                        runningProcessesReceived.Set();
                    }
                };

                portal.RunningProcessesMessageReceived += runningProcessesReceivedHandler;

                Task startListeningForProcessesTask = portal.StartListeningForRunningProcesses();
                startListeningForProcessesTask.Wait();

                runningProcessesReceived.WaitOne();

                Task stopListeningForProcessesTask = portal.StopListeningForRunningProcesses();
                stopListeningForProcessesTask.Wait();

                portal.RunningProcessesMessageReceived -= runningProcessesReceivedHandler;
            }
            else
            {
                Task <DevicePortal.RunningProcesses> getRunningProcessesTask = portal.GetRunningProcesses();
                runningProcesses = getRunningProcessesTask.Result;
            }

            foreach (DeviceProcessInfo process in runningProcesses.Processes)
            {
                if (!string.IsNullOrEmpty(process.Name))
                {
                    Console.WriteLine(process.Name);
                }
            }
        }
Example #23
0
        private static bool TryOpenDevicePortalConnection(Uri targetDevice, ParameterHelper parameters, out DevicePortal portal)
        {
            string userName = parameters.GetParameterValue(ParameterHelper.WdpUser);
            string password = parameters.GetParameterValue(ParameterHelper.WdpPassword);

            bool success = true;

            portal = new DevicePortal(new DefaultDevicePortalConnection(targetDevice.ToString(), userName, password));
            try
            {
                // We need to handle this event otherwise remote connection will be rejected if
                // device isn't trusted by local PC
                portal.UnvalidatedCert += DoCertValidation;

                var connectTask = portal.ConnectAsync(updateConnection: false);
                connectTask.Wait();

                if (portal.ConnectionHttpStatusCode != System.Net.HttpStatusCode.OK)
                {
                    if (portal.ConnectionHttpStatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        throw new System.UnauthorizedAccessException("Connection rejected due to missing/incorrect credentials; specify valid credentials with /user and /pwd switches");
                    }
                    else if (!string.IsNullOrEmpty(portal.ConnectionFailedDescription))
                    {
                        throw new System.OperationCanceledException(string.Format("WDP connection failed (HTTP {0}) : {1}", (int)portal.ConnectionHttpStatusCode, portal.ConnectionFailedDescription));
                    }
                    else
                    {
                        throw new System.OperationCanceledException(string.Format("WDP connection failed (HTTP {0}) : no additional information", (int)portal.ConnectionHttpStatusCode));
                    }
                }
            }
            catch (Exception ex)
            {
                bool verbose = parameters.HasFlag(ParameterHelper.VerboseFlag);
                Console.Out.WriteLine("Failed to open DevicePortal connection to '" + portal.Address + "'\n" + (verbose ? ex.ToString() : ex.Message));

                success = false;
            }

            return(success);
        }
        /// <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(ConfigUsageMessage);
                return;
            }

            string desiredSetting = parameters.GetParameterValue("setting");
            string desiredValue   = parameters.GetParameterValue("value");

            // Determine if this is for all settings or a single setting.
            if (string.IsNullOrWhiteSpace(desiredSetting))
            {
                Task <XboxSettingList> getSettingsTask = portal.GetXboxSettings();
                getSettingsTask.Wait();

                Console.WriteLine(getSettingsTask.Result);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(desiredValue))
                {
                    Task <XboxSetting> getSettingTask = portal.GetXboxSetting(desiredSetting);
                    getSettingTask.Wait();

                    Console.WriteLine(getSettingTask.Result);
                }
                else
                {
                    XboxSetting setting = new XboxSetting();
                    setting.Name  = desiredSetting;
                    setting.Value = desiredValue;

                    Task <XboxSetting> setSettingTask = portal.UpdateXboxSetting(setting);
                    setSettingTask.Wait();

                    Console.WriteLine(setSettingTask.Result);
                }
            }
        }
Example #25
0
        public async Task ConnectAsync()
        {
            if (_devicePortal != null)
            {
                _devicePortal.ConnectionStatus -= DevicePortal_ConnectionStatus;
            }

            // 入力された情報をもとに接続
            _devicePortal = new DevicePortal(new DefaultDevicePortalConnection(Address, UserName, Password));
            _devicePortal.ConnectionStatus += DevicePortal_ConnectionStatus;
            try
            {
                // 証明書をデバイスポータルから取得して、それを使って接続を行う
                await _devicePortal.ConnectAsync(manualCertificate : await _devicePortal.GetRootDeviceCertificateAsync(true));
            }
            catch (Exception ex)
            {
                Message = ex.Message;
                Debug.WriteLine(ex);
            }
        }
Example #26
0
        /// <summary>
        /// Connects to a device.
        /// </summary>
        /// <param name="connectOptions">Options that specify how the connection is to be established.</param>
        /// <returns></returns>
        public async Task ConnectAsync(
            ConnectOptions connectOptions)
        {
            string address = connectOptions.Address.ToLower();

            if (!address.StartsWith("http"))
            {
                string scheme = "https";

                if ((address == DefaultConnectionAddress) ||
                    (address == DefaultConnectionAddressAsIp))
                {
                    scheme = "http";
                }

                address = string.Format(
                    "{0}://{1}",
                    scheme,
                    address);
            }

            this.devicePortalConnection = new DefaultDevicePortalConnection(
                address,
                connectOptions.UserName,
                connectOptions.Password);
            DevicePortal portal = new DevicePortal(this.devicePortalConnection);

            portal.ConnectionStatus += DevicePortal_ConnectionStatus;

            // We are physically connected to the device.
            // We can safely accept the device's root certificate.
            Certificate certificate = await portal.GetRootDeviceCertificateAsync(true);

            // Establish the connection to the device.
            await portal.ConnectAsync(
                connectOptions.Ssid,
                connectOptions.NetworkKey,
                updateConnection : connectOptions.UpdateConnection,
                manualCertificate : certificate);
        }
        /// <summary>
        /// Validate the server certificate
        /// </summary>
        /// <param name="sender">The sender object</param>
        /// <param name="certificate">The server's certificate</param>
        /// <param name="chain">The cert chain</param>
        /// <param name="sslPolicyErrors">Policy Errors</param>
        /// <returns>whether the cert passes validation</returns>
        private bool DoCertValidation(DevicePortal sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            X509Certificate2 cert = new X509Certificate2(certificate);

            if (!string.IsNullOrEmpty(this.AcceptedThumbprint))
            {
                if (cert.Thumbprint.Equals(this.AcceptedThumbprint, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
            }

            Console.WriteLine("The certificate provided by the device failed validation.");
            Console.WriteLine("Issuer:\t\t{0}", cert.Issuer);
            Console.WriteLine("Thumbprint:\t{0}", cert.Thumbprint);
            Console.WriteLine();

            Console.WriteLine("If you trust this endpoint, you can manually specify this certificate should be accepted by adding the following to any call:\n\t/thumbprint:{0}", cert.Thumbprint);
            Console.WriteLine("Or you can permanently add this as a trusted certificate for this device by calling the following:\n\tXboxWdpDriver.exe /op:connect /thumbprint:{0}", cert.Thumbprint);
            Console.WriteLine();

            return(false);
        }
        /// <summary>
        /// Handles the ConnectionStatus event.
        /// </summary>
        /// <param name="sender">The object which sent this event.</param>
        /// <param name="args">Event arguments.</param>
        private void DevicePortal_ConnectionStatus(
            DevicePortal sender,
            DeviceConnectionStatusEventArgs args)
        {
            if (args.Status == DeviceConnectionStatus.Connected)
            {
                // Connection successfully established.
                this.devicePortal = sender;
                this.devicePortal.AppInstallStatus += DevicePortal_AppInstallStatus;

                // Start the heartbeat.
                Task t = CheckHeartbeatAsync();
                t.Wait();

                this.devicePortal.ConnectionStatus -= DevicePortal_ConnectionStatus;
            }
            else if (args.Status == DeviceConnectionStatus.Failed)
            {
                this.devicePortal.ConnectionStatus -= DevicePortal_ConnectionStatus;

                // Connection failed.
                throw new Exception(args.Message);
            }
        }
Example #29
0
        /// <summary>
        /// Main entry point for handling a Sandbox 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(SandboxUsageMessage);
                return;
            }

            string desiredValue = parameters.GetParameterValue("value");

            if (string.IsNullOrEmpty(desiredValue))
            {
                Task <Sandbox> getSandboxTask = portal.GetXboxLiveSandbox();
                getSandboxTask.Wait();

                Console.WriteLine(getSandboxTask.Result);
            }
            else
            {
                Task <Sandbox> setSandboxTask = portal.SetXboxLiveSandbox(desiredValue);
                setSandboxTask.Wait();

                Console.WriteLine("{0} -> {1}", setSandboxTask.Result, desiredValue);

                if (parameters.HasFlag("reboot"))
                {
                    Task rebootTask = portal.Reboot();
                    rebootTask.Wait();
                    Console.WriteLine("Console rebooting...");
                }
                else
                {
                    Console.WriteLine("A reboot is required before this setting takes effect.");
                }
            }
        }
 private void DevicePortal_AppInstallStatus(
     DevicePortal sender,
     ApplicationInstallStatusEventArgs args)
 {
     NotifyAppInstallStatus(args);
 }