/// <summary>
 /// Creates a collection with the given details.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.RemoteApp.ICollectionOperations.
 /// </param>
 /// <param name='populateOnly'>
 /// Required. A flag denoting if the request is to populate the
 /// creation details of the collection or update and deploy (true for
 /// populate only).
 /// </param>
 /// <param name='collectionDetails'>
 /// Required. Details for the collection to be created.
 /// </param>
 /// <returns>
 /// The response containing the operation tracking id.
 /// </returns>
 public static OperationResultWithTrackingId Create(this ICollectionOperations operations, bool populateOnly, CollectionCreationDetails collectionDetails)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((ICollectionOperations)s).CreateAsync(populateOnly, collectionDetails);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        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;
        }
        public static int SetUpDefaultRemoteAppCollectionSet(Mock<IRemoteAppManagementClient> clientMock,string collectionName, string subscriptionId, string billingPlan, string imageName, PSCredential credential, string domainName, string trackingId)
        {

            NetworkCredential cred = credential != null ? credential.GetNetworkCredential() : null;

            CollectionCreationDetails collectionDetails = new CollectionCreationDetails()
            {
                Name = collectionName,
                PlanName = billingPlan,
                TemplateImageName = imageName,
                Mode = CollectionMode.Apps,
                Description = "unit test"
            };

            if (cred != null)
            {
                collectionDetails.AdInfo = new ActiveDirectoryConfig()
                {
                    DomainName = domainName,
                    UserName = cred.UserName,
                    Password = cred.Password
                };
            }

            List<Collection> collectionList = new List<Collection>()
            {
                new Collection()
                {
                    Name = collectionDetails.Name,
                    PlanName = collectionDetails.PlanName,
                    TemplateImageName = collectionDetails.TemplateImageName,
                    Mode = collectionDetails.Mode,
                    Description = collectionDetails.Description,
                    Status = "Active",
                    AdInfo = collectionDetails.AdInfo != null ? collectionDetails.AdInfo : null
                }
            };

            OperationResultWithTrackingId response = new OperationResultWithTrackingId()
            {
                StatusCode = System.Net.HttpStatusCode.Accepted,
                TrackingId = trackingId,
                RequestId = "222-3456-789"
            };

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

            ISetup<IRemoteAppManagementClient, Task<OperationResultWithTrackingId>> setup = 
                clientMock.Setup(
                    c => c.Collections.SetAsync(
                            collectionName, 
                            It.IsAny<bool>(), 
                            It.IsAny<bool>(), 
                            It.IsAny<CollectionUpdateDetails>(), 
                            It.IsAny<CancellationToken>()));
            setup.Returns(Task.Factory.StartNew(() => response));

            mockCollectionList = collectionList;

           return mockCollectionList.Count;
        }
        private void CanCreateNonPopulateOnlyAndDeleteRemoteAppService()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                var client = GetRemoteAppManagementClient();

                string name = TestUtilities.GenerateName("ghut");
                string activeDirectoryName = TestUtilities.GenerateName("ghut");
                string billingPlanName = "Standard";
                string templateName = TestUtilities.GenerateName("ghut");    // BUGBUG this must be a real template
                HttpStatusCode[] statusSuccess = { HttpStatusCode.OK, HttpStatusCode.Accepted };

                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"
                };

                CollectionResult queriedCollection = null;

                OperationResultWithTrackingId result = client.Collections.Create(false, collectionDetails);
                Assert.NotNull(result);
                Assert.Contains(result.StatusCode, statusSuccess);

                if (result.StatusCode == HttpStatusCode.Accepted)
                {
                    //                    RemoteAppManagementClient.WaitForLongRunningOperation(result.TrackingId, timeoutMs, client);
                    Assert.True(result.StatusCode == HttpStatusCode.OK, "Failed to create collection.");
                }

                queriedCollection = client.Collections.Get(collectionDetails.Name);
                Assert.Equal(queriedCollection.Collection.AdInfo.DomainName, collectionDetails.AdInfo.DomainName);
                Assert.Equal(queriedCollection.Collection.PlanName, collectionDetails.PlanName);
                Assert.Equal(queriedCollection.Collection.TemplateImageName, collectionDetails.TemplateImageName);
                Assert.Equal(queriedCollection.Collection.Mode, collectionDetails.Mode);
                Assert.Equal(queriedCollection.Collection.VNetName, collectionDetails.VNetName);
                Assert.Equal(queriedCollection.Collection.Description, collectionDetails.Description);
                Assert.Equal(queriedCollection.Collection.ReadyForPublishing, collectionDetails.ReadyForPublishing);

                OperationResultWithTrackingId response = client.Collections.Delete(queriedCollection.Collection.Name);
                Assert.True(result.StatusCode == HttpStatusCode.OK, "Delete collection did not return OK.");
            }
        }
        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;
        }
 /// <summary>
 /// Creates a collection with the given details.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.RemoteApp.ICollectionOperations.
 /// </param>
 /// <param name='populateOnly'>
 /// Required. A flag denoting if the request is to populate the
 /// creation details of the collection or update and deploy (true for
 /// populate only).
 /// </param>
 /// <param name='collectionDetails'>
 /// Required. Details for the collection to be created.
 /// </param>
 /// <returns>
 /// The response containing the operation tracking id.
 /// </returns>
 public static Task<OperationResultWithTrackingId> CreateAsync(this ICollectionOperations operations, bool populateOnly, CollectionCreationDetails collectionDetails)
 {
     return operations.CreateAsync(populateOnly, collectionDetails, CancellationToken.None);
 }
        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;


            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);
            }
        }