public override void ExecuteCmdlet()
        {
            OperationResultWithTrackingId response = CallClient(() => Client.VNet.Delete(VNetName), Client.VNet);

            if (response != null)
            {
                WriteTrackingId(response);
            }
        }
Beispiel #2
0
        public void CanCreateVnet()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                HttpRecorderMode          mode = HttpMockServer.GetCurrentMode();
                RemoteAppManagementClient remoteAppManagementClient = GetRemoteAppManagementClient();

                string        vnetName = "hkutvnet1";
                VNetParameter payload  = new VNetParameter()
                {
                    Region            = "West US",
                    VnetAddressSpaces = new List <string>
                    {
                        "172.16.0.0/16"
                    },
                    LocalAddressSpaces = new List <string>
                    {
                        "11.0.0.0/16"
                    },
                    DnsServers = new List <string>()
                    {
                        "10.0.0.1"
                    },
                    VpnAddress  = "13.0.0.1",
                    GatewayType = GatewayType.StaticRouting
                };

                Assert.DoesNotThrow(() =>
                {
                    OperationResultWithTrackingId result = remoteAppManagementClient.VNet.CreateOrUpdate(vnetName, payload);

                    Assert.NotNull(result);
                    Assert.True(result.StatusCode == HttpStatusCode.OK || result.StatusCode == HttpStatusCode.Accepted, "StatusCode = " + result.StatusCode + "is not one of the expected");

                    if (result.StatusCode == HttpStatusCode.Accepted)
                    {
                        Assert.NotNull(result.TrackingId);
                    }

                    // verify the creation
                    VNetResult vnet = remoteAppManagementClient.VNet.Get(vnetName, false);

                    Assert.NotNull(vnet);
                    Assert.Equal(HttpStatusCode.OK, vnet.StatusCode);
                    Assert.NotNull(vnet.VNet);
                    Assert.Equal(vnetName, vnet.VNet.Name);
                    Assert.Equal(payload.VpnAddress, vnet.VNet.VpnAddress);
                    Assert.Equal(payload.GatewayType, vnet.VNet.GatewayType);
                    Assert.Equal(payload.Region, vnet.VNet.Region);
                });
            }
        }
        public override void ExecuteCmdlet()
        {
            OperationResultWithTrackingId response = null;

            if (ShouldProcess(CollectionName, "Remove collection"))
            {
                response = CallClient(() => Client.Collections.Delete(CollectionName), Client.Collections);
                if (response != null)
                {
                    WriteTrackingId(response);
                }
            }
        }
        public void CanEnsureStorageInRegion()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                HttpRecorderMode          mode = HttpMockServer.GetCurrentMode();
                RemoteAppManagementClient remoteAppManagementClient = GetRemoteAppManagementClient();

                // Assume region to be "West US" for test purposes
                OperationResultWithTrackingId ensureResult = remoteAppManagementClient.TemplateImages.EnsureStorageInRegion("West US");
                Assert.NotNull(ensureResult);
            }
        }
Beispiel #5
0
        private Collection CreateNewServiceWithPopulateOnlyTrue(RemoteAppManagementClient client)
        {
            string name = "hsut2861";
            string activeDirectoryName = "ghutad";
            string billingPlanName     = "Standard";
            string templateName        = "bluerefresh.2014.08.21.vhd"; //GetReadyTemplateImageName(client);

            ActiveDirectoryConfig adDetails = new ActiveDirectoryConfig()
            {
                DomainName = activeDirectoryName,
                UserName   = "******",
                Password   = "******"
            };

            CollectionCreationDetails collectionDetails = new CollectionCreationDetails()
            {
                Name               = name,
                AdInfo             = adDetails,
                PlanName           = billingPlanName,
                TemplateImageName  = templateName,
                Description        = "OneSDK test created.",
                Mode               = CollectionMode.Apps,
                ReadyForPublishing = true,
                VNetName           = "SomeVnet"
            };

            OperationResultWithTrackingId result = null;

            Assert.DoesNotThrow(() =>
            {
                result = client.Collections.Create(true, collectionDetails);
            });

            Assert.NotNull(result);

            // if OK is returned then the tracking id is the name of the newly created collection
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);

            Assert.NotNull(result.TrackingId);

            // now check if the object is actually created at the backend
            CollectionResult queriedService = client.Collections.Get(collectionDetails.Name);

            Assert.Equal(HttpStatusCode.OK, queriedService.StatusCode);
            Assert.Equal(queriedService.Collection.Name, name);
            Assert.Equal(queriedService.Collection.PlanName, collectionDetails.PlanName);
            Assert.Equal(queriedService.Collection.TemplateImageName, collectionDetails.TemplateImageName);
            Assert.Equal(queriedService.Collection.Status, "Creating");

            return(queriedService.Collection);
        }
Beispiel #6
0
        public void CanRestartVm()
        {
            using (UndoContext undoContext = UndoContext.Current)
            {
                undoContext.Start();

                RemoteAppManagementClient client = GetRemoteAppManagementClient();

                CollectionListResult collectionList = null;
                Assert.DoesNotThrow(() =>
                {
                    collectionList = client.Collections.List();
                });

                Assert.NotNull(collectionList);

                Assert.NotEmpty(collectionList.Collections);

                foreach (Collection collection in collectionList.Collections)
                {
                    CollectionVmsListResult vmsList = null;

                    Assert.DoesNotThrow(() =>
                    {
                        vmsList = client.Collections.ListVms(collection.Name);
                    });

                    Assert.NotNull(vmsList);

                    Assert.NotEmpty(vmsList.Vms);

                    Assert.DoesNotThrow(() =>
                    {
                        RestartVmCommandParameter restartParam = new RestartVmCommandParameter();

                        restartParam.VirtualMachineName      = vmsList.Vms[0].VirtualMachineName;
                        restartParam.LogoffMessage           = "You will be logged off after 2 minutes";
                        restartParam.LogoffWaitTimeInSeconds = 120;

                        OperationResultWithTrackingId restartResult = client.Collections.RestartVm(collection.Name, restartParam);

                        Assert.True(restartResult.StatusCode == HttpStatusCode.OK);

                        Assert.NotNull(restartResult.TrackingId);
                    });

                    break;
                }
            }
        }
Beispiel #7
0
        public override void ExecuteCmdlet()
        {
            OperationResultWithTrackingId response = null;

            if (ShouldProcess(CollectionName, "Export user disks of collection"))
            {
                response = CallClient(() => Client.UserDisks.Migrate(CollectionName, DestinationStorageAccountName, DestinationStorageAccountKey, DestinationStorageAccountContainerName, OverwriteExistingUserDisk.IsPresent), Client.UserDisks);

                if (response != null)
                {
                    WriteTrackingId(response);
                }
            }
        }
Beispiel #8
0
        public override void ExecuteCmdlet()
        {
            RemoteAppVm vm = GetVm(CollectionName, UserUpn);
            RestartVmCommandParameter     restartDetails = null;
            OperationResultWithTrackingId result         = null;

            if (vm == null)
            {
                WriteWarning(string.Format(Commands_RemoteApp.NoVmInCollectionForUser, UserUpn, CollectionName));

                return;
            }

            if (vm.LoggedOnUserUpns.Count > 1)
            {
                string otherLoggedInUsers = null;
                string warningCaption     = null;
                string warningMessage     = null;

                foreach (string user in vm.LoggedOnUserUpns)
                {
                    if (string.Compare(user, UserUpn, true) != 0)
                    {
                        otherLoggedInUsers += "\n" + user;
                    }
                }

                warningMessage = string.Format(Commands_RemoteApp.RestartVmWarningMessage, UserUpn, vm.VirtualMachineName, otherLoggedInUsers);
                warningCaption = string.Format(Commands_RemoteApp.RestartVmWarningCaption, vm.VirtualMachineName);

                WriteWarning(warningMessage);

                if (!ShouldProcess(null, Commands_RemoteApp.GenericAreYouSureQuestion, warningCaption))
                {
                    return;
                }
            }

            restartDetails = new RestartVmCommandParameter(vm.VirtualMachineName);
            restartDetails.LogoffWaitTimeInSeconds = LogoffWaitSeconds <= 0 ? 60 : LogoffWaitSeconds;
            restartDetails.LogoffMessage           = string.IsNullOrEmpty(LogoffMessage) ? string.Format(Commands_RemoteApp.DefaultLogoffMessage, restartDetails.LogoffWaitTimeInSeconds) : LogoffMessage;

            result = CallClient(() => Client.Collections.RestartVm(CollectionName, restartDetails), Client.Collections);

            if (result != null)
            {
                TrackingResult trackingId = new TrackingResult(result);
                WriteObject(trackingId);
            }
        }
Beispiel #9
0
        public void CanResetVpnSharedKey()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                HttpRecorderMode          mode = HttpMockServer.GetCurrentMode();
                RemoteAppManagementClient remoteAppManagementClient = GetRemoteAppManagementClient();

                Assert.DoesNotThrow(() =>
                {
                    string vNet = "hkutvnet1";

                    // lets remember the vpn shared key before the reset request
                    VNetResult vnetBefore = remoteAppManagementClient.VNet.Get(vNet, true);

                    Assert.Equal(HttpStatusCode.OK, vnetBefore.StatusCode);
                    Assert.NotNull(vnetBefore.VNet);
                    Assert.Equal(vNet, vnetBefore.VNet.Name);
                    Assert.NotNull(vnetBefore.VNet.SharedKey);

                    // now reset the key
                    OperationResultWithTrackingId result = remoteAppManagementClient.VNet.ResetVpnSharedKey(vNet);

                    Assert.NotNull(result);
                    Assert.InRange(result.StatusCode, HttpStatusCode.OK, HttpStatusCode.Accepted);
                    if (result.StatusCode == HttpStatusCode.Accepted)
                    {
                        Assert.NotNull(result.TrackingId);
                        TrackingId = result.TrackingId;
                    }

                    VNetOperationStatusResult vnetOperationResult = remoteAppManagementClient.VNet.GetResetVpnSharedKeyOperationStatus(TrackingId);

                    Assert.NotNull(vnetOperationResult);
                    Assert.Equal(HttpStatusCode.OK, vnetOperationResult.StatusCode);

                    // lets check if the key is actually reset
                    VNetResult vnetAfter = remoteAppManagementClient.VNet.Get(vNet, true);

                    Assert.Equal(HttpStatusCode.OK, vnetAfter.StatusCode);
                    Assert.NotNull(vnetAfter.VNet);
                    Assert.Equal(vNet, vnetAfter.VNet.Name);
                    Assert.NotNull(vnetAfter.VNet.SharedKey);

                    // make sure that the key before and after does not match
                    Assert.NotEqual(vnetBefore.VNet.SharedKey, vnetAfter.VNet.SharedKey);
                });
            }
        }
 public void CanExportUserDisk()
 {
     using (UndoContext context = UndoContext.Current)
     {
         context.Start();
         HttpRecorderMode          mode = HttpMockServer.GetCurrentMode();
         RemoteAppManagementClient remoteAppManagementClient = GetRemoteAppManagementClient();
         string collectionName = "collectionname";
         string accountKey     = "accountkey";
         string accountName    = "accountname";
         string containerName  = "containername";
         OperationResultWithTrackingId result = remoteAppManagementClient.UserDisks.Migrate(collectionName, accountName, accountKey, containerName, true);
         Assert.NotNull(result);
     }
 }
Beispiel #11
0
        public void CanSendMessageToASessionInACollection()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                RemoteAppManagementClient client = GetRemoteAppManagementClient();

                SessionSendMessageCommandParameter parameter = new SessionSendMessageCommandParameter
                {
                    UserUpn = "*****@*****.**",
                    Message = "Hello there!"
                };

                // testing the web fault
                OperationResultWithTrackingId response = null;

                response = client.Collections.SendMessageToSession("simple", parameter);


                Assert.NotNull(response);
                Assert.NotNull(response.TrackingId);
                Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

                AssertLongrunningOperation(client, RemoteAppOperationStatus.Success, response.TrackingId);

                CollectionSessionListResult sessionList = client.Collections.ListSessions("simple");

                Assert.NotNull(sessionList);
                Assert.NotNull(sessionList.Sessions);
                Assert.True(sessionList.StatusCode == HttpStatusCode.OK);
                Assert.NotEmpty(sessionList.Sessions);

                RemoteAppSession session = null;

                foreach (var s in sessionList.Sessions)
                {
                    if (s.UserUpn == parameter.UserUpn)
                    {
                        session = s;
                        break;
                    }
                }

                Assert.NotNull(session);
                Assert.True(session.State == SessionState.Connected);
            }
        }
Beispiel #12
0
        public void CanDeleteVnet()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                HttpRecorderMode          mode = HttpMockServer.GetCurrentMode();
                RemoteAppManagementClient remoteAppManagementClient = GetRemoteAppManagementClient();

                VNet vnet = null;

                // verify the creation
                VNetListResult vnetList = null;
                Assert.DoesNotThrow(() =>
                {
                    vnetList = remoteAppManagementClient.VNet.List();
                });

                Assert.NotNull(vnetList);
                Assert.Equal(HttpStatusCode.OK, vnetList.StatusCode);
                Assert.NotNull(vnetList.VNetList);
                Assert.NotEmpty(vnetList.VNetList);

                foreach (VNet v in vnetList.VNetList)
                {
                    if (Regex.IsMatch(v.Name, @"^hkutvnet"))
                    {
                        // found a match
                        if (v.State == VNetState.Connecting || v.State == VNetState.Ready)
                        {
                            vnet = v;
                            break;
                        }
                    }
                }

                Assert.NotNull(vnet);

                OperationResultWithTrackingId deleteResult = remoteAppManagementClient.VNet.Delete(vnet.Name);

                Assert.NotNull(deleteResult);
                Assert.True(deleteResult.StatusCode == HttpStatusCode.OK || deleteResult.StatusCode == HttpStatusCode.Accepted, "StatusCode = " + deleteResult.StatusCode + "is not one of the expected");

                if (deleteResult.StatusCode == HttpStatusCode.Accepted)
                {
                    Assert.NotNull(deleteResult.TrackingId);
                }
            }
        }
        public static int SetUpDefaultRemoteAppCollectionCreate(Mock <IRemoteAppManagementClient> clientMock, string collectionName, string region, string billingPlan, string imageName, string description, string customProperties, string trackingId)
        {
            CollectionCreationDetails collectionDetails = new CollectionCreationDetails()
            {
                Name              = collectionName,
                PlanName          = billingPlan,
                TemplateImageName = imageName,
                Mode              = CollectionMode.Apps,
                Region            = region,
                Description       = description,
                CustomRdpProperty = customProperties
            };

            List <Collection> collectionList = new List <Collection>()
            {
                new Collection()
                {
                    Name              = collectionDetails.Name,
                    Region            = collectionDetails.Region,
                    PlanName          = collectionDetails.PlanName,
                    TemplateImageName = collectionDetails.TemplateImageName,
                    Mode              = collectionDetails.Mode,
                    Description       = collectionDetails.Description,
                    Status            = "Active"
                }
            };

            OperationResultWithTrackingId response = new OperationResultWithTrackingId()
            {
                StatusCode = System.Net.HttpStatusCode.Accepted,
                TrackingId = trackingId,
                RequestId  = "111-2222-4444"
            };

            mockTrackingId = new List <TrackingResult>()
            {
                new TrackingResult(response)
            };

            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > setup = clientMock.Setup(c => c.Collections.CreateAsync(It.IsAny <bool>(), It.IsAny <CollectionCreationDetails>(), It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));

            mockCollectionList = collectionList;

            return(mockCollectionList.Count);
        }
Beispiel #14
0
        public void CanLogOffASessionFromACollection()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                RemoteAppManagementClient client = GetRemoteAppManagementClient();

                SessionCommandParameter parameter = new SessionCommandParameter
                {
                    UserUpn = "*****@*****.**"
                };

                // testing the web fault
                OperationResultWithTrackingId response = null;

                response = client.Collections.LogoffSession("simple", parameter);

                Assert.NotNull(response);
                Assert.NotNull(response.TrackingId);
                Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

                AssertLongrunningOperation(client, RemoteAppOperationStatus.Success, response.TrackingId);

                TestUtilities.Wait(20000); //wait a little bit

                CollectionSessionListResult sessionList = client.Collections.ListSessions("simple");

                Assert.NotNull(sessionList);
                Assert.NotNull(sessionList.Sessions);
                Assert.True(sessionList.StatusCode == HttpStatusCode.OK);

                RemoteAppSession session = null;

                foreach (var s in sessionList.Sessions)
                {
                    if (s.UserUpn == parameter.UserUpn)
                    {
                        session = s;
                        break;
                    }
                }

                Assert.Null(session);
            }
        }
        public static int SetUpDefaultRemoteAppVm(Mock <IRemoteAppManagementClient> clientMock, string collectionName, string vmName, string userUpn, string trackingId)
        {
            CollectionVmsListResult       response        = new CollectionVmsListResult();
            OperationResultWithTrackingId restartResponse = new OperationResultWithTrackingId()
            {
                StatusCode = System.Net.HttpStatusCode.Accepted,
                TrackingId = trackingId,
                RequestId  = "111-2222-4444"
            };

            response.Vms = new List <RemoteAppVm>()
            {
                new RemoteAppVm()
                {
                    VirtualMachineName = vmName,
                    LoggedOnUserUpns   = { userUpn, "*****@*****.**" }
                },

                new RemoteAppVm()
                {
                    VirtualMachineName = "testVm2",
                    LoggedOnUserUpns   = { "*****@*****.**" }
                }
            };

            mockVmList = new List <RemoteAppVm>();
            foreach (RemoteAppVm vm in response.Vms)
            {
                RemoteAppVm mockVm = new RemoteAppVm()
                {
                    VirtualMachineName = vm.VirtualMachineName,
                    LoggedOnUserUpns   = vm.LoggedOnUserUpns
                };
                mockVmList.Add(mockVm);
            }

            ISetup <IRemoteAppManagementClient, Task <CollectionVmsListResult> > setup = clientMock.Setup(c => c.Collections.ListVmsAsync(collectionName, It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));

            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > setupRestart = clientMock.Setup(c => c.Collections.RestartVmAsync(collectionName, It.IsAny <RestartVmCommandParameter>(), It.IsAny <CancellationToken>()));

            setupRestart.Returns(Task.Factory.StartNew(() => restartResponse));

            return(mockVmList.Count);
        }
        public override void ExecuteCmdlet()
        {
            OperationResultWithTrackingId response = null;
            string description = Commands_RemoteApp.VnetSharedKeyResetConfirmationDescription;
            string warning     = Commands_RemoteApp.GenericAreYouSureQuestion;
            string caption     = Commands_RemoteApp.VnetSharedKeyResetCaptionMessage;

            if (ShouldProcess(description, warning, caption))
            {
                response = CallClient(() => Client.VNet.ResetVpnSharedKey(VNetName), Client.VNet);
            }

            if (response != null)
            {
                VNetOperationStatusResult operationStatus = null;
                int maxRetries = 600; // 5 minutes?
                // wait for the reset key operation to succeed to get the new key
                do
                {
                    System.Threading.Thread.Sleep(5000); //wait a while before the next check
                    operationStatus = CallClient(() => Client.VNet.GetResetVpnSharedKeyOperationStatus(response.TrackingId), Client.VNet);
                }while (operationStatus.Status != VNetOperationStatus.Failed &&
                        operationStatus.Status != VNetOperationStatus.Success &&
                        --maxRetries > 0);

                if (operationStatus.Status == VNetOperationStatus.Success)
                {
                    VNetResult vnet = CallClient(() => Client.VNet.Get(VNetName, true), Client.VNet);
                    WriteObject(vnet.VNet);

                    WriteVerboseWithTimestamp("The request completed successfully.");
                }
                else
                {
                    if (maxRetries > 0)
                    {
                        WriteErrorWithTimestamp("The request failed.");
                    }
                    else
                    {
                        WriteErrorWithTimestamp("The request took a long time to complete.");
                    }
                }
            }
        }
        public static void SetUpDefaultRemoteAppCollectionDelete(Mock <IRemoteAppManagementClient> clientMock, string collectionName, string trackingId)
        {
            OperationResultWithTrackingId response = new OperationResultWithTrackingId()
            {
                StatusCode = System.Net.HttpStatusCode.Accepted,
                TrackingId = trackingId,
                RequestId  = "02111-222-3456"
            };

            mockTrackingId = new List <TrackingResult>()
            {
                new TrackingResult(response)
            };

            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > setup = clientMock.Setup(c => c.Collections.DeleteAsync(collectionName, It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));
        }
        public override void ExecuteCmdlet()
        {
            OperationResultWithTrackingId response = null;
            AccountDetailsParameter       details  = new AccountDetailsParameter()
            {
                AccountInfo = new AccountDetails()
                {
                    EndUserFeedName = WorkspaceName
                }
            };

            response = CallClient(() => Client.Account.Set(details), Client.Account);

            if (response != null)
            {
                WriteTrackingId(response);
            }
        }
Beispiel #19
0
        public static void SetUpDefaultRemoteAppExportTemplateImage(Mock <IRemoteAppManagementClient> clientMock, string sourceCollectionName, string DestinationStorageAccountName, string DestinationStorageAccountKey, string DestinationStorageAccountContainerName, string trackingId)
        {
            OperationResultWithTrackingId response = new OperationResultWithTrackingId()
            {
                StatusCode = System.Net.HttpStatusCode.Accepted,
                TrackingId = trackingId,
                RequestId  = "02111-222-3456"
            };

            mockTrackingId = new List <TrackingResult>()
            {
                new TrackingResult(response)
            };

            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > setup =
                clientMock.Setup(c => c.TemplateImages.MigrateAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));
        }
        public override void ExecuteCmdlet()
        {
            VNetParameter payload = null;
            OperationResultWithTrackingId response = null;

            payload = new VNetParameter()
            {
                VnetAddressSpaces  = new List <string>(VirtualNetworkAddressSpace),
                LocalAddressSpaces = new List <string>(LocalNetworkAddressSpace),
                DnsServers         = new List <string>(DnsServerIpAddress),
                VpnAddress         = VpnDeviceIpAddress,
            };

            response = CallClient(() => Client.VNet.CreateOrUpdate(VNetName, payload), Client.VNet);
            if (response != null)
            {
                WriteTrackingId(response);
            }
        }
Beispiel #21
0
        public static void SetUpDefaultRemoteAppRemoveVNet(Mock <IRemoteAppManagementClient> clientMock, string name)
        {
            OperationResultWithTrackingId response = new OperationResultWithTrackingId()
            {
                StatusCode = System.Net.HttpStatusCode.Accepted,
                TrackingId = "225986",
                RequestId  = "6233-2222-4444"
            };

            mockTrackingId = new List <TrackingResult>()
            {
                new TrackingResult(response)
            };

            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > setup =
                clientMock.Setup(c => c.VNet.DeleteAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));
        }
Beispiel #22
0
        public void CanCreateAndDeleteRemoteAppService()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                var client = GetRemoteAppManagementClient();

                Collection collection = CreateNewServiceWithPopulateOnlyTrue(client);

                OperationResultWithTrackingId response = null;

                Assert.DoesNotThrow(() =>
                {
                    response = client.Collections.Delete(collection.Name);
                });

                Assert.NotNull(response);
                Assert.True(response.StatusCode == HttpStatusCode.OK);
            }
        }
Beispiel #23
0
        public override void ExecuteCmdlet()
        {
            SessionCommandParameter parameter = new SessionCommandParameter
            {
                UserUpn = UserUpn
            };

            OperationResultWithTrackingId response = null;
            string caption = Commands_RemoteApp.SessionLogOffCaptionMessage;
            string warning = String.Format(System.Globalization.CultureInfo.CurrentCulture,
                                           Commands_RemoteApp.SessionLogOffWarningQuestionFormat,
                                           UserUpn);

            if (ShouldProcess(caption, warning, caption))
            {
                response = CallClient(() => Client.Collections.LogoffSession(CollectionName, parameter), Client.Collections);
            }

            if (response != null)
            {
                WriteTrackingId(response);
            }
        }
Beispiel #24
0
        public override void ExecuteCmdlet()
        {
            VNetParameter payload = null;
            OperationResultWithTrackingId response = null;

            payload = new VNetParameter()
            {
                Region             = Location,
                VnetAddressSpaces  = new List <string>(VirtualNetworkAddressSpace),
                LocalAddressSpaces = new List <string>(LocalNetworkAddressSpace),
                DnsServers         = new List <string>(DnsServerIpAddress),
                VpnAddress         = VpnDeviceIpAddress,
                GatewayType        = GatewayType
            };

            RegisterSubscriptionWithRdfeForRemoteApp();

            response = CallClient(() => Client.VNet.CreateOrUpdate(VNetName, payload), Client.VNet);
            if (response != null)
            {
                WriteTrackingId(response);
            }
        }
Beispiel #25
0
        public static int SetUpDefaultRemoteAppAddVNet(Mock <IRemoteAppManagementClient> clientMock, VNetParameter vNetDetails)
        {
            List <VNet> vnetList = new List <VNet>()
            {
                new VNet()
                {
                    Region             = vNetDetails.Region,
                    VnetAddressSpaces  = vNetDetails.VnetAddressSpaces,
                    LocalAddressSpaces = vNetDetails.LocalAddressSpaces,
                    DnsServers         = vNetDetails.DnsServers,
                    VpnAddress         = vNetDetails.VpnAddress,
                    GatewayType        = vNetDetails.GatewayType
                }
            };

            mockVNetList = vnetList;

            OperationResultWithTrackingId response = new OperationResultWithTrackingId()
            {
                StatusCode = System.Net.HttpStatusCode.Accepted,
                TrackingId = "12345",
                RequestId  = "111-2222-4444"
            };

            mockTrackingId = new List <TrackingResult>()
            {
                new TrackingResult(response)
            };

            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > setup =
                clientMock.Setup(c => c.VNet.CreateOrUpdateAsync(It.IsAny <string>(), It.IsAny <VNetParameter>(), It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));

            return(mockVNetList.Count);
        }
Beispiel #26
0
        /// <summary>
        /// Migrate user disks of all the users from a collection to the
        /// specified azure storage account
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The collection name.
        /// </param>
        /// <param name='targetAccountName'>
        /// Required. The destination storage account name
        /// </param>
        /// <param name='targetAccountKey'>
        /// Required. The destination storage account key
        /// </param>
        /// <param name='targetContainerName'>
        /// Required. The destination container name
        /// </param>
        /// <param name='overwriteExistingUserDisk'>
        /// Required. A flag denoting if the request is to overwrite the
        /// existing user disk in the destination storage account
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task <OperationResultWithTrackingId> MigrateAsync(string collectionName, string targetAccountName, string targetAccountKey, string targetContainerName, bool overwriteExistingUserDisk, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (targetAccountName == null)
            {
                throw new ArgumentNullException("targetAccountName");
            }
            if (targetAccountKey == null)
            {
                throw new ArgumentNullException("targetAccountKey");
            }
            if (targetContainerName == null)
            {
                throw new ArgumentNullException("targetContainerName");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("collectionName", collectionName);
                tracingParameters.Add("targetAccountName", targetAccountName);
                tracingParameters.Add("targetAccountKey", targetAccountKey);
                tracingParameters.Add("targetContainerName", targetContainerName);
                tracingParameters.Add("overwriteExistingUserDisk", overwriteExistingUserDisk);
                TracingAdapter.Enter(invocationId, this, "MigrateAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/accounts/desktops/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/MigrateUserDiskAsync";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("targetAccountName=" + Uri.EscapeDataString(targetAccountName));
            queryParameters.Add("targetAccountKey=" + Uri.EscapeDataString(targetAccountKey));
            queryParameters.Add("targetContainerName=" + Uri.EscapeDataString(targetContainerName));
            queryParameters.Add("overwrite=" + Uri.EscapeDataString(overwriteExistingUserDisk.ToString().ToLower()));
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Post;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result            = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("x-remoteapp-operation-tracking-id"))
                    {
                        result.TrackingId = httpResponse.Headers.GetValues("x-remoteapp-operation-tracking-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            // register the subscription for this service if it has not been before
            // sebsequent call to register is redundent
            RegisterSubscriptionWithRdfeForRemoteApp();

            NetworkCredential         creds   = null;
            CollectionCreationDetails details = new CollectionCreationDetails()
            {
                Name = CollectionName,
                TemplateImageName = ImageName,
                Region            = Location,
                PlanName          = Plan,
                Description       = Description,
                CustomRdpProperty = CustomRdpProperty,
                Mode = (ResourceType == null || ResourceType == CollectionMode.Unassigned) ? CollectionMode.Apps : ResourceType.Value
            };
            OperationResultWithTrackingId response = null;


            if (ParameterSetName == "AzureVNet")
            {
                details.VNetName   = VNetName;
                details.SubnetName = SubnetName;
                ValidateCustomerVNetParams(details.VNetName, details.SubnetName);

                if (DnsServers != null)
                {
                    details.DnsServers = DnsServers.Split(new char[] { ',' });
                }

                if (!String.IsNullOrWhiteSpace(Domain) || Credential != null)
                {
                    if (String.IsNullOrWhiteSpace(Domain) || Credential == null)
                    {
                        // you supplied either a domain or a cred, but not both.
                        ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                            Commands_RemoteApp.InvalidADArguments,
                            String.Empty,
                            Client.Collections,
                            ErrorCategory.InvalidArgument
                            );

                        ThrowTerminatingError(er);
                    }

                    creds          = Credential.GetNetworkCredential();
                    details.AdInfo = new ActiveDirectoryConfig()
                    {
                        DomainName         = Domain,
                        OrganizationalUnit = OrganizationalUnit,
                        UserName           = creds.UserName,
                        Password           = creds.Password,
                    };
                }
            }
            else
            {
                if (String.IsNullOrEmpty(details.Region))
                {
                    ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                        Commands_RemoteApp.InvalidLocationArgument,
                        String.Empty,
                        Client.Collections,
                        ErrorCategory.InvalidArgument
                        );

                    ThrowTerminatingError(er);
                }
            }

            response = CallClient(() => Client.Collections.Create(false, details), Client.Collections);

            if (response != null)
            {
                TrackingResult trackingId = new TrackingResult(response);
                WriteObject(trackingId);
            }
        }
Beispiel #28
0
        public override void ExecuteCmdlet()
        {
            NetworkCredential             creds    = null;
            CollectionUpdateDetails       details  = null;
            OperationResultWithTrackingId response = null;
            Collection collection    = null;
            bool       forceRedeploy = false;

            collection = FindCollection(CollectionName);
            if (collection == null)
            {
                return;
            }

            details = new CollectionUpdateDetails();

            if (Credential != null)
            {
                if (collection.AdInfo == null)
                {
                    ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                        Commands_RemoteApp.AadInfoCanNotBeAddedToCloudOnlyCollectionMessage,
                        String.Empty,
                        Client.Collections,
                        ErrorCategory.InvalidArgument);
                    ThrowTerminatingError(er);
                }

                details.AdInfo = new ActiveDirectoryConfig();

                creds = Credential.GetNetworkCredential();
                details.AdInfo.UserName           = Credential.UserName;
                details.AdInfo.Password           = creds.Password;
                details.AdInfo.DomainName         = collection.AdInfo.DomainName;
                details.AdInfo.OrganizationalUnit = collection.AdInfo.OrganizationalUnit;

                if (String.Equals("Inactive", collection.Status, StringComparison.OrdinalIgnoreCase))
                {
                    // the collection may have failed due to bad domain join information before,
                    // re-trying with the new information
                    forceRedeploy = true;
                }
            }
            else if (Plan != null)
            {
                details.PlanName = Plan;
            }
            else if (Description != null)
            {
                details.Description = Description;
            }
            else if (CustomRdpProperty != null)
            {
                details.CustomRdpProperty = CustomRdpProperty;
            }
            else
            {
                ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                    "At least one parameter must be set with this cmdlet",
                    String.Empty,
                    Client.Collections,
                    ErrorCategory.InvalidArgument);
                ThrowTerminatingError(er);
            }

            response = CallClient(() => Client.Collections.Set(CollectionName, forceRedeploy, false, details), Client.Collections);
            if (response != null)
            {
                WriteTrackingId(response);
            }
        }
        public override void ExecuteCmdlet()
        {
            // register the subscription for this service if it has not been before
            // sebsequent call to register is redundent
            RegisterSubscriptionWithRdfeForRemoteApp();

            NetworkCredential         creds   = null;
            CollectionCreationDetails details = new CollectionCreationDetails()
            {
                Name = CollectionName,
                TemplateImageName = ImageName,
                Region            = Location,
                PlanName          = Plan,
                Description       = Description,
                CustomRdpProperty = CustomRdpProperty,
                Mode = CollectionMode.Apps
            };
            OperationResultWithTrackingId response = null;

            switch (ParameterSetName)
            {
            case DomainJoined:
            case AzureVNet:
            {
                creds            = Credential.GetNetworkCredential();
                details.VNetName = VNetName;

                if (SubnetName != null)
                {
                    if (!IsFeatureEnabled(EnabledFeatures.azureVNet))
                    {
                        ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                            string.Format(Commands_RemoteApp.LinkAzureVNetFeatureNotEnabledMessage),
                            String.Empty,
                            Client.Account,
                            ErrorCategory.InvalidOperation
                            );

                        ThrowTerminatingError(er);
                    }

                    details.SubnetName = SubnetName;
                    ValidateCustomerVNetParams(details.VNetName, details.SubnetName);

                    if (DnsServers != null)
                    {
                        details.DnsServers = DnsServers.Split(new char[] { ',' });
                    }

                    details.Region = Location;
                }

                details.AdInfo = new ActiveDirectoryConfig()
                {
                    DomainName         = Domain,
                    OrganizationalUnit = OrganizationalUnit,
                    UserName           = creds.UserName,
                    Password           = creds.Password,
                };
                break;
            }

            case NoDomain:
            default:
            {
                details.Region = Location;
                break;
            }
            }

            response = CallClient(() => Client.Collections.Create(false, details), Client.Collections);

            if (response != null)
            {
                TrackingResult trackingId = new TrackingResult(response);
                WriteObject(trackingId);
            }
        }
        /// <summary>
        /// Sets the new details of the account.
        /// </summary>
        /// <param name='accountInfo'>
        /// Required. New details of account.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task <OperationResultWithTrackingId> SetAsync(AccountDetailsParameter accountInfo, CancellationToken cancellationToken)
        {
            // Validate
            if (accountInfo == null)
            {
                throw new ArgumentNullException("accountInfo");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("accountInfo", accountInfo);
                TracingAdapter.Enter(invocationId, this, "SetAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/account";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc     = null;

                JObject accountDetailsParameterValue = new JObject();
                requestDoc = accountDetailsParameterValue;

                if (accountInfo.AccountInfo != null)
                {
                    if (accountInfo.AccountInfo.EndUserFeedName != null)
                    {
                        accountDetailsParameterValue["WorkspaceName"] = accountInfo.AccountInfo.EndUserFeedName;
                    }
                }

                requestContent      = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result            = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }