private async Task PushPublicKeyToMetadataAsync(
            InstanceLocator instance,
            bool useInstanceKeySet,
            ManagedMetadataAuthorizedKey metadataKey,
            CancellationToken token)
        {
            try
            {
                if (useInstanceKeySet)
                {
                    await this.computeEngineAdapter.UpdateMetadataAsync(
                        instance,
                        metadata => MergeKeyIntoMetadata(metadata, metadataKey),
                        token)
                    .ConfigureAwait(false);
                }
                else
                {
                    await this.computeEngineAdapter.UpdateCommonInstanceMetadataAsync(
                        instance.ProjectId,
                        metadata => MergeKeyIntoMetadata(metadata, metadataKey),
                        token)
                    .ConfigureAwait(false);
                }
            }
            catch (GoogleApiException e) when(e.Error == null || e.Error.Code == 403)
            {
                ApplicationTraceSources.Default.TraceVerbose(
                    "Setting request payload metadata failed with 403: {0} ({1})",
                    e.Message,
                    e.Error?.Errors.EnsureNotNull().Select(er => er.Reason).FirstOrDefault());

                // Setting metadata failed due to lack of permissions. Note that
                // the Error object is not always populated, hence the OR filter.

                throw new SshKeyPushFailedException(
                          "You do not have sufficient permissions to publish an SSH key. " +
                          "You need the 'Service Account User' and " +
                          "'Compute Instance Admin' roles (or equivalent custom roles) " +
                          "to perform this action.",
                          HelpTopics.ManagingMetadataAuthorizedKeys);
            }
            catch (GoogleApiException e) when(e.IsBadRequest())
            {
                ApplicationTraceSources.Default.TraceVerbose(
                    "Setting request payload metadata failed with 400: {0} ({1})",
                    e.Message,
                    e.Error?.Errors.EnsureNotNull().Select(er => er.Reason).FirstOrDefault());

                // This slightly weirdly encoded error happens if the user has the necessary
                // permissions on the VM, but lacks ActAs permission on the associated
                // service account.

                throw new SshKeyPushFailedException(
                          "You do not have sufficient permissions to publish an SSH key. " +
                          "Because this VM instance uses a service account, you also need the " +
                          "'Service Account User' role.",
                          HelpTopics.ManagingMetadataAuthorizedKeys);
            }
        }
 public Task <NetworkCredential> ResetWindowsUserAsync(
     InstanceLocator instanceRef,
     string username,
     CancellationToken token)
 {
     return(ResetWindowsUserAsync(instanceRef, username, token, DefaultPasswordResetTimeout));
 }
        public void WhenNotConnected_ThenTryActivateReturnsFalse()
        {
            var sampleLocator = new InstanceLocator("project", "zone", "instance");
            var broker        = new RemoteDesktopSessionBroker(this.serviceProvider);

            Assert.IsFalse(broker.TryActivate(sampleLocator));
        }
예제 #4
0
        public async Task WhenInstanceDoesntExist_ThenPasswordResetExceptionIsThrown(
            [Credential(Role = PredefinedRole.ComputeInstanceAdminV1)] ResourceTask <ICredential> credential)
        {
            var computeService = CreateComputeService(await credential);
            var username       = "******" + Guid.NewGuid().ToString().Substring(20);

            // Use correct project, but wrong VM.
            var instanceRef = new InstanceLocator(
                TestProject.ProjectId,
                TestProject.Zone,
                "doesnotexist");

            try
            {
                await computeService.Instances.ResetWindowsUserAsync(
                    instanceRef,
                    username,
                    CancellationToken.None);

                Assert.Fail();
            }
            catch (PasswordResetException e)
            {
                Assert.IsNotEmpty(e.Message);
            }
        }
 public async Task <GuestAttributes> GetGuestAttributesAsync(
     InstanceLocator instanceLocator,
     string queryPath,
     CancellationToken cancellationToken)
 {
     using (TraceSources.IapDesktop.TraceMethod().WithParameters(instanceLocator))
     {
         try
         {
             var request = this.service.Instances.GetGuestAttributes(
                 instanceLocator.ProjectId,
                 instanceLocator.Zone,
                 instanceLocator.Name);
             request.QueryPath = queryPath;
             return(await request
                    .ExecuteAsync(cancellationToken)
                    .ConfigureAwait(false));
         }
         catch (GoogleApiException e) when(e.Error != null && e.Error.Code == 404)
         {
             // No guest attributes present.
             return(null);
         }
         catch (GoogleApiException e) when(e.Error != null && e.Error.Code == 403)
         {
             throw new ResourceAccessDeniedException(
                       $"Access to VM instance {instanceLocator.Name} has been denied", e);
         }
     }
 }
예제 #6
0
        public static void SetMainPage(User user)
        {
            var mainViewModel = InstanceLocator.GetInstance().Main;

            mainViewModel.LoadUser(user);
            App.Current.MainPage = new MasterPage();
        }
        private async Task <IRemoteDesktopSession> Connect(
            RdpTunnel tunnel,
            InstanceLocator vmInstanceReference)
        {
            using (var gceAdapter = new ComputeEngineAdapter(this.serviceProvider.GetService <IAuthorizationAdapter>()))
            {
                var credentials = await gceAdapter.ResetWindowsUserAsync(
                    vmInstanceReference,
                    CreateRandomUsername(),
                    CancellationToken.None);

                var rdpService = new RemoteDesktopConnectionBroker(this.serviceProvider);
                return(rdpService.Connect(
                           vmInstanceReference,
                           "localhost",
                           (ushort)tunnel.LocalPort,
                           new VmInstanceConnectionSettings()
                {
                    Username = credentials.UserName,
                    Password = credentials.SecurePassword,
                    AuthenticationLevel = RdpAuthenticationLevel.NoServerAuthentication,
                    BitmapPersistence = RdpBitmapPersistence.Disabled,
                    DesktopSize = RdpDesktopSize.ClientSize
                }));
            }
        }
예제 #8
0
        public async Task <NetworkCredential> GenerateCredentialsAsync(
            IWin32Window owner,
            InstanceLocator instanceRef,
            string suggestedUsername = null)
        {
            // Prompt for username to use.
            var username = new GenerateCredentialsDialog().PromptForUsername(
                owner,
                suggestedUsername ?? this.authService.Authorization.SuggestWindowsUsername());

            if (username == null)
            {
                return(null);
            }

            var credentials = await this.jobService.RunInBackground(
                new JobDescription("Generating Windows logon credentials..."),
                token => this.computeEngineAdapter.ResetWindowsUserAsync(
                    instanceRef,
                    username,
                    token));

            new ShowCredentialsDialog().ShowDialog(
                owner,
                credentials.UserName,
                credentials.Password);

            return(credentials);
        }
        private void AddExistingInstance(
            InstanceSetHistoryBuilder builder,
            int count,
            DateTime lastSeen,
            Tenancies tenancy)
        {
            for (int i = 0; i < count; i++)
            {
                instanceIdSequence++;

                var locator = new InstanceLocator("project", "zone", $"instance-{instanceIdSequence}");
                builder.AddExistingInstance(
                    instanceIdSequence,
                    locator,
                    new ImageLocator("project", $"image-{instanceIdSequence}"),
                    InstanceState.Running,
                    lastSeen,
                    tenancy,
                    tenancy == Tenancies.SoleTenant
                        ? "server-1"
                        : null,
                    null);
                builder.GetInstanceHistoryBuilder(instanceIdSequence)
                .OnStart(BaselineTime.AddDays(i), locator);
            }
        }
        public void WhenNotConnected_ThenIsConnectedIsFalse()
        {
            var sampleLocator = new InstanceLocator("project", "zone", "instance");
            var broker        = new SshTerminalSessionBroker(this.serviceProvider);

            Assert.IsFalse(broker.IsConnected(sampleLocator));
        }
        private async Task <IRemoteDesktopSession> Connect(
            RdpTunnel tunnel,
            InstanceLocator vmInstanceReference)
        {
            using (var gceAdapter = new ComputeEngineAdapter(this.serviceProvider.GetService <IAuthorizationAdapter>()))
            {
                var credentials = await gceAdapter.ResetWindowsUserAsync(
                    vmInstanceReference,
                    CreateRandomUsername(),
                    TimeSpan.FromSeconds(60),
                    CancellationToken.None);

                var settings = VmInstanceConnectionSettings.CreateNew(vmInstanceReference);
                settings.Username.Value            = credentials.UserName;
                settings.Password.Value            = credentials.SecurePassword;
                settings.AuthenticationLevel.Value = RdpAuthenticationLevel.NoServerAuthentication;
                settings.BitmapPersistence.Value   = RdpBitmapPersistence.Disabled;
                settings.DesktopSize.Value         = RdpDesktopSize.ClientSize;

                var rdpService = new RemoteDesktopSessionBroker(this.serviceProvider);
                return(rdpService.Connect(
                           vmInstanceReference,
                           "localhost",
                           (ushort)tunnel.LocalPort,
                           settings));
            }
        }
예제 #12
0
        //---------------------------------------------------------------------
        // Ctor
        //---------------------------------------------------------------------

        private InstanceHistoryBuilder(
            ulong instanceId,
            InstanceLocator reference,
            ImageLocator image,
            InstanceState state,
            DateTime?lastSeen,
            Tenancies tenancy)
        {
            Debug.Assert(!tenancy.IsFlagCombination());
            if (instanceId == 0)
            {
                throw new ArgumentException("Instance ID cannot be 0");
            }

            this.InstanceId    = instanceId;
            this.reference     = reference;
            this.image         = image;
            this.lastStoppedOn = lastSeen;

            if (state == InstanceState.Running)
            {
                Debug.Assert(tenancy != Tenancies.Unknown);
                Debug.Assert(lastSeen != null);

                // Add a synthetic placement.
                AddPlacement(new InstancePlacement(tenancy, null, lastSeen.Value, lastSeen.Value));
            }
        }
예제 #13
0
        private static void InitializeIocAndFramework()
        {
            //初始化IoC
            IUnityContainer container = new UnityContainer();

            container.RegisterType <IObjectEventMapping, DomainLayerObjectEventMapping>(new ContainerControlledLifetimeManager());
            container.RegisterType <IUnitOfWork, UnitOfWork>(new ContainerControlledLifetimeManager());

            //将IoC保存到静态变量中,以便永久保存该对象
            UnityContainerHolder.UnityContainer = container;

            //为框架提供一个InstanceLocator
            InstanceLocator.SetLocator(new ExampleInstanceLocator());

            container.RegisterInstance(typeof(BankAccountCollection), new BankAccountCollection());
            container.RegisterInstance(typeof(CustomerCollection), new CustomerCollection());
            container.RegisterInstance(typeof(ForumUserCollection), new ForumUserCollection());
            container.RegisterInstance(typeof(ReplyCollection), new ReplyCollection());
            container.RegisterInstance(typeof(TopicCollection), new TopicCollection());

            //将所有Event和EventHandler建立映射关系
            var eventSubscriberTypeMappingStore = EventSubscriberTypeMappingStore.Current;

            eventSubscriberTypeMappingStore.ResolveEventSubscriberTypeMappings(typeof(BankAccount).Assembly);
            eventSubscriberTypeMappingStore.ResolveEventSubscriberTypeMappings(typeof(BankAccountCollection).Assembly);
        }
예제 #14
0
 /// <summary>
 /// Read serial port output as a continuous stream.
 /// </summary>
 public static IAsyncReader <string> GetSerialPortOutputStream(
     this InstancesResource resource,
     InstanceLocator instanceRef,
     ushort port)
 {
     return(new SerialPortStream(resource, instanceRef, port));
 }
예제 #15
0
        public async Task WhenConnectSuccessful_OpenEventIsFired()
        {
            var mockTunnelService = new Mock <ITunnelService>();

            var mockEventService = new Mock <IEventService>();

            mockEventService.Setup(s => s.FireAsync(It.IsAny <TunnelOpenedEvent>()))
            .Returns(Task.FromResult(true));

            var mockTunnel = new Mock <ITunnel>();

            mockTunnel.Setup(t => t.Probe(It.IsAny <TimeSpan>()))
            .Returns(Task.FromResult(true));

            var broker        = new TunnelBrokerService(mockTunnelService.Object, mockEventService.Object);
            var vmInstanceRef = new InstanceLocator("project", "zone", "instance");
            var destination   = new TunnelDestination(vmInstanceRef, 3389);

            mockTunnelService.Setup(s => s.CreateTunnelAsync(
                                        destination,
                                        It.IsAny <ISshRelayPolicy>()))
            .Returns(Task.FromResult(mockTunnel.Object));

            var tunnel = await broker.ConnectAsync(
                destination,
                new AllowAllRelayPolicy(),
                TimeSpan.FromMinutes(1));

            mockEventService.Verify(s => s.FireAsync(It.IsAny <TunnelOpenedEvent>()), Times.Once);
        }
        //---------------------------------------------------------------------
        // Loading.
        //---------------------------------------------------------------------

        public async static Task <InstancePropertiesInspectorModel> LoadAsync(
            InstanceLocator instanceLocator,
            IComputeEngineAdapter computeEngineAdapter,
            IInventoryService inventoryService,
            CancellationToken token)
        {
            var instance = await computeEngineAdapter
                           .GetInstanceAsync(
                instanceLocator,
                token)
                           .ConfigureAwait(false);

            var project = await computeEngineAdapter
                          .GetProjectAsync(
                instanceLocator.ProjectId,
                token)
                          .ConfigureAwait(false);

            var osInfo = await inventoryService.GetInstanceInventoryAsync(
                instanceLocator,
                token)
                         .ConfigureAwait(false);

            return(new InstancePropertiesInspectorModel(
                       project,
                       instance,
                       osInfo));
        }
예제 #17
0
        public async Task WhenInstanceDoesntExist_ThenPasswordResetExceptionIsThrown(
            [WindowsInstance] InstanceRequest testInstance)
        {
            await testInstance.AwaitReady();

            var username = "******" + Guid.NewGuid().ToString();

            // Use correct project, but wrong VM.
            var instanceRef = new InstanceLocator(
                testInstance.Locator.ProjectId,
                testInstance.Locator.Zone,
                testInstance.Locator.Name + "-x");

            try
            {
                await this.instancesResource.ResetWindowsUserAsync(
                    instanceRef,
                    username,
                    CancellationToken.None);

                Assert.Fail();
            }
            catch (PasswordResetException e)
            {
                Assert.IsNotEmpty(e.Message);
            }
        }
예제 #18
0
        //---------------------------------------------------------------------
        // Publics.
        //---------------------------------------------------------------------

        public RemoteDesktopPane(
            IServiceProvider serviceProvider,
            InstanceLocator vmInstance)
            : base(serviceProvider)
        {
            this.exceptionDialog = serviceProvider.GetService <IExceptionDialog>();
            this.eventService    = serviceProvider.GetService <IEventService>();
            this.Instance        = vmInstance;

            this.TabText = vmInstance.Name;

            // The ActiveX fails when trying to drag/dock a window, so disable
            // that feature.
            this.AllowEndUserDocking = false;

            var singleScreenFullScreenMenuItem = new ToolStripMenuItem("&Full screen");

            singleScreenFullScreenMenuItem.Click += (sender, _)
                                                    => TrySetFullscreen(FullScreenMode.SingleScreen);
            this.TabContextStrip.Items.Add(singleScreenFullScreenMenuItem);
            this.TabContextStrip.Opening += tabContextStrip_Opening;

            var allScreensFullScreenMenuItem = new ToolStripMenuItem("&Full screen (multiple displays)");

            allScreensFullScreenMenuItem.Click += (sender, _)
                                                  => TrySetFullscreen(FullScreenMode.AllScreens);
            this.TabContextStrip.Items.Add(allScreensFullScreenMenuItem);
            this.TabContextStrip.Opening += tabContextStrip_Opening;
        }
예제 #19
0
        //---------------------------------------------------------------------
        // Loading.
        //---------------------------------------------------------------------

        public async static Task <InstanceDetailsModel> LoadAsync(
            InstanceLocator instanceLocator,
            IComputeEngineAdapter adapter,
            CancellationToken token)
        {
            var instance = await adapter
                           .GetInstanceAsync(
                instanceLocator,
                token)
                           .ConfigureAwait(false);

            var guestAttributes = await adapter
                                  .GetGuestAttributesAsync(
                instanceLocator,
                GuestOsInfo.GuestAttributePath,
                token)
                                  .ConfigureAwait(false);

            var guestAttributesList = guestAttributes?.QueryValue?.Items;

            return(new InstanceDetailsModel(
                       instance,
                       guestAttributesList != null
                    ? GuestOsInfo.FromGuestAttributes(guestAttributesList)
                    : null));
        }
예제 #20
0
        //---------------------------------------------------------------------
        // Static helpers.
        //---------------------------------------------------------------------

        private static bool IsInstanceMatch(InstanceLocator locator, string term)
        {
            term = term.ToLowerInvariant();

            return(locator.Zone.Contains(term) ||
                   locator.Name.Contains(term));
        }
        private static GuestOsInfo CreateGuestOsInfo(
            InstanceLocator locator,
            PackageInventoryType type,
            IList <Package> packages)
        {
            var packageInfo = packages == null ? null : new GuestPackages(
                packages,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);

            return(new GuestOsInfo(
                       locator,
                       null,
                       null,
                       null,
                       null,
                       null,
                       new Version(),
                       null,
                       null,
                       type == PackageInventoryType.InstalledPackages ? packageInfo : null,
                       type == PackageInventoryType.AvailablePackages ? packageInfo : null));
        }
예제 #22
0
        //---------------------------------------------------------------------
        // Guest attributes.
        //---------------------------------------------------------------------

        public async Task <GuestAttributes> GetGuestAttributesAsync(
            InstanceLocator instanceLocator,
            string queryPath,
            CancellationToken cancellationToken)
        {
            using (ApplicationTraceSources.Default.TraceMethod().WithParameters(instanceLocator))
            {
                try
                {
                    var request = this.service.Instances.GetGuestAttributes(
                        instanceLocator.ProjectId,
                        instanceLocator.Zone,
                        instanceLocator.Name);
                    request.QueryPath = queryPath;
                    return(await request
                           .ExecuteAsync(cancellationToken)
                           .ConfigureAwait(false));
                }
                catch (GoogleApiException e) when(e.IsNotFound())
                {
                    // No guest attributes present.
                    return(null);
                }
                catch (GoogleApiException e) when(e.IsAccessDenied())
                {
                    throw new ResourceAccessDeniedException(
                              $"Access to VM instance {instanceLocator.Name} has been denied",
                              HelpTopics.ProjectAccessControl,
                              e);
                }
            }
        }
예제 #23
0
 public void StartInitialize()
 {
     InstanceLocator.RegisterInstance <AppConfig>(this);
     this.StartCoroutine(this.InitializeAsync(() => {
         this.IsFullyInitialized = true;
     }));
 }
예제 #24
0
        public void WhenProbeFails_ThenOpenTunnelsDoesNotIncludeTunnel()
        {
            var mockTunnelService = new Mock <ITunnelService>();

            var mockEventService = new Mock <IEventService>();

            mockEventService.Setup(s => s.FireAsync(It.IsAny <TunnelOpenedEvent>()))
            .Returns(Task.FromResult(true));

            var mockTunnel = new Mock <ITunnel>();

            mockTunnel.Setup(t => t.Probe(It.IsAny <TimeSpan>()))
            .Returns(Task.FromException(new ApplicationException()));

            var broker        = new TunnelBrokerService(mockTunnelService.Object, mockEventService.Object);
            var vmInstanceRef = new InstanceLocator("project", "zone", "instance");
            var destination   = new TunnelDestination(vmInstanceRef, 3389);

            mockTunnelService.Setup(s => s.CreateTunnelAsync(
                                        destination,
                                        It.IsAny <ISshRelayPolicy>()))
            .Returns(Task.FromResult(mockTunnel.Object));

            AssertEx.ThrowsAggregateException <ApplicationException>(() =>
            {
                broker.ConnectAsync(
                    destination,
                    new AllowAllRelayPolicy(),
                    TimeSpan.FromMinutes(1)).Wait();
            });

            Assert.AreEqual(0, broker.OpenTunnels.Count());
        }
예제 #25
0
 public IAsyncReader <string> GetSerialPortOutput(InstanceLocator instanceRef, ushort portNumber)
 {
     using (TraceSources.IapDesktop.TraceMethod().WithParameters(instanceRef))
     {
         return(this.service.Instances.GetSerialPortOutputStream(instanceRef, portNumber));
     }
 }
예제 #26
0
        public async Task WhenClosingAllTunnels_AllTunnelsAreClosed()
        {
            var mockTunnelService = new Mock <ITunnelService>();

            var mockEventService = new Mock <IEventService>();

            mockEventService.Setup(s => s.FireAsync(It.IsAny <TunnelOpenedEvent>()))
            .Returns(Task.FromResult(true));

            var mockTunnel = new Mock <ITunnel>();

            mockTunnel.Setup(t => t.Probe(It.IsAny <TimeSpan>()))
            .Returns(Task.FromResult(true));
            mockTunnel.Setup(t => t.Close());

            var broker        = new TunnelBrokerService(mockTunnelService.Object, mockEventService.Object);
            var vmInstanceRef = new InstanceLocator("project", "zone", "instance");
            var destination   = new TunnelDestination(vmInstanceRef, 3389);

            mockTunnelService.Setup(s => s.CreateTunnelAsync(
                                        destination,
                                        It.IsAny <ISshRelayPolicy>()))
            .Returns(Task.FromResult(mockTunnel.Object));

            var tunnel = await broker.ConnectAsync(
                destination,
                new AllowAllRelayPolicy(),
                TimeSpan.FromMinutes(1));

            Assert.AreEqual(1, broker.OpenTunnels.Count());

            await broker.DisconnectAllAsync();

            Assert.AreEqual(0, broker.OpenTunnels.Count());
        }
예제 #27
0
        public static async Task <NetworkCredential> ResetWindowsUserAsync(
            this InstancesResource resource,
            InstanceLocator instanceRef,
            string username,
            TimeSpan timeout,
            CancellationToken token)
        {
            using (var timeoutCts = new CancellationTokenSource())
            {
                timeoutCts.CancelAfter(timeout);

                using (var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, token))
                {
                    try
                    {
                        return(await ResetWindowsUserAsync(
                                   resource,
                                   instanceRef,
                                   username,
                                   combinedCts.Token).ConfigureAwait(false));
                    }
                    catch (Exception e) when(e.IsCancellation() && timeoutCts.IsCancellationRequested)
                    {
                        TraceSources.Common.TraceError(e);
                        // This task was cancelled because of a timeout, not because
                        // the enclosing job was cancelled.
                        throw new PasswordResetException(
                                  $"Timeout waiting for Compute Engine agent to reset password for user {username}. " +
                                  "Verify that the agent is running.");
                    }
                }
            }
        }
예제 #28
0
        public async Task WhenConnectSuccessful_ThenOpenTunnelsIncludesTunnel()
        {
            var mockTunnelService = new Mock <ITunnelService>();

            var mockEventService = new Mock <IEventService>();

            mockEventService.Setup(s => s.FireAsync(It.IsAny <TunnelOpenedEvent>()))
            .Returns(Task.FromResult(true));

            var mockTunnel = new Mock <ITunnel>();

            mockTunnel.Setup(t => t.Probe(It.IsAny <TimeSpan>()))
            .Returns(Task.FromResult(true));

            var broker        = new TunnelBrokerService(mockTunnelService.Object, mockEventService.Object);
            var vmInstanceRef = new InstanceLocator("project", "zone", "instance");
            var destination   = new TunnelDestination(vmInstanceRef, 3389);

            mockTunnelService.Setup(s => s.CreateTunnelAsync(
                                        destination,
                                        It.IsAny <ISshRelayPolicy>()))
            .Returns(Task.FromResult(mockTunnel.Object));

            var tunnel = await broker.ConnectAsync(
                destination,
                new AllowAllRelayPolicy(),
                TimeSpan.FromMinutes(1));

            Assert.IsNotNull(tunnel);
            Assert.AreEqual(1, broker.OpenTunnels.Count());
            Assert.IsTrue(broker.IsConnected(destination));

            Assert.AreSame(tunnel, broker.OpenTunnels.First());
        }
예제 #29
0
 private GuestOsInfo(
     InstanceLocator instance,
     string architecture,
     string kernelRelease,
     string kernelVersion,
     string operatingSystem,
     string operatingSystemFullName,
     Version operatingSystemVersion,
     string agentVersion,
     DateTime?lastUpdated,
     GuestPackages installedPackages,
     GuestPackages availablePackages)
 {
     this.Instance                = instance;
     this.Architecture            = architecture;
     this.KernelRelease           = kernelRelease;
     this.KernelVersion           = kernelVersion;
     this.OperatingSystem         = operatingSystem;
     this.OperatingSystemFullName = operatingSystemFullName;
     this.OperatingSystemVersion  = operatingSystemVersion;
     this.AgentVersion            = agentVersion;
     this.LastUpdated             = lastUpdated;
     this.InstalledPackages       = installedPackages;
     this.AvailablePackages       = availablePackages;
 }
예제 #30
0
        public async Task GenerateCredentialsAsync(
            IWin32Window owner,
            InstanceLocator instanceLocator,
            ConnectionSettingsBase settings,
            bool silent)
        {
            // Prompt for username to use.
            string username;

            if (silent)
            {
                username = string.IsNullOrEmpty(settings.Username.StringValue)
                    ? this.serviceProvider
                           .GetService <IAuthorizationAdapter>()
                           .Authorization
                           .SuggestWindowsUsername()
                    : settings.Username.StringValue;
            }
            else
            {
                username = this.serviceProvider
                           .GetService <IGenerateCredentialsDialog>()
                           .PromptForUsername(
                    owner,
                    string.IsNullOrEmpty(settings.Username.StringValue)
                            ? this.serviceProvider
                    .GetService <IAuthorizationAdapter>()
                    .Authorization
                    .SuggestWindowsUsername()
                            : settings.Username.StringValue);
                if (username == null)
                {
                    // Aborted.
                    throw new OperationCanceledException();
                }
            }

            var credentials = await this.serviceProvider.GetService <IJobService>().RunInBackground(
                new JobDescription("Generating Windows logon credentials..."),
                token => this.serviceProvider
                .GetService <IComputeEngineAdapter>()
                .ResetWindowsUserAsync(
                    instanceLocator,
                    username,
                    token))
                              .ConfigureAwait(true);

            if (!silent)
            {
                this.serviceProvider.GetService <IShowCredentialsDialog>().ShowDialog(
                    owner,
                    credentials.UserName,
                    credentials.Password);
            }

            // Save credentials.
            settings.Username.StringValue    = credentials.UserName;
            settings.Password.ClearTextValue = credentials.Password;
            settings.Domain.StringValue      = null;
        }