public bool IsFeatureEnabled(string featureName) { EnabledFeaturesResult features = Client.Account.GetEnabledFeatures(); if (features.StatusCode != System.Net.HttpStatusCode.OK) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( string.Format("Failed to enumerate enabled features"), String.Empty, Client.Account, ErrorCategory.ConnectionError ); ThrowTerminatingError(er); } foreach (string feature in features.EnabledFeatures) { if (string.Compare(feature, featureName, true) == 0) { return(true); } } return(false); }
private void WriteUsageDetails(CollectionUsageDetailsResult detailsUsage) { // // Display the content pointed to by the returned URI // WebResponse response = null; WebRequest request = WebRequest.Create(detailsUsage.UsageDetails.SasUri); try { response = (HttpWebResponse)request.GetResponse(); } catch (Exception e) { ErrorRecord error = RemoteAppCollectionErrorState.CreateErrorRecordFromException(e, String.Empty, Client.Collections, ErrorCategory.InvalidResult); WriteError(error); } using (Stream dataStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { String csvContent = reader.ReadToEnd(); WriteObject(csvContent); } } }
protected T CallClient <T>(Func <T> func, object targetObject) where T : AzureOperationResponse { T response = default(T); try { response = func(); } catch (Exception e) { // Handle if this or the inner exception is of type CloudException CloudException ce = e as CloudException; ErrorRecord er = null; if (ce == null) { ce = e.InnerException as CloudException; } if (ce != null) { HandleCloudException(targetObject, ce); } else { er = RemoteAppCollectionErrorState.CreateErrorRecordFromException(e, String.Empty, targetObject, ErrorCategory.NotSpecified); ThrowTerminatingError(er); } } return(response); }
private void GetUsageDetails(CollectionUsageDetailsResult detailsUsage) { RemoteAppOperationStatusResult operationResult = null; // The request is async and we have to wait for the usage details to be produced here do { System.Threading.Thread.Sleep(5000); operationResult = CallClient(() => Client.OperationResults.Get(detailsUsage.UsageDetails.OperationTrackingId), Client.OperationResults); }while (operationResult.RemoteAppOperationResult.Status != RemoteAppOperationStatus.Success && operationResult.RemoteAppOperationResult.Status != RemoteAppOperationStatus.Failed); if (operationResult.RemoteAppOperationResult.Status == RemoteAppOperationStatus.Success) { WriteUsageDetails(detailsUsage); } else { ErrorRecord error = RemoteAppCollectionErrorState.CreateErrorRecordFromString( Commands_RemoteApp.DetailedUsageFailureMessage, String.Empty, Client.Collections, ErrorCategory.ResourceUnavailable); WriteError(error); } }
protected void RegisterSubscriptionWithRdfeForRemoteApp() { System.Threading.CancellationToken cancelationToken = new System.Threading.CancellationToken(); // register the subscription with RDFE to use the RemoteApp resource try { AzureOperationResponse azureOperationResponse = MgmtClient.Subscriptions.RegisterResourceAsync(Client.RdfeNamespace, cancelationToken).Result; } catch (Exception e) { // Handle if this or the inner exception is of type CloudException CloudException ce = e as CloudException; if (ce == null) { ce = e.InnerException as CloudException; } if (ce != null) { // ignore the 'ConflictError' which is returned if the subscription is already registered for the resource if (ce.Error.Code != "ConflictError") { HandleCloudException(MgmtClient.Subscriptions, ce); } } else { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromException(e, String.Empty, MgmtClient.Subscriptions, ErrorCategory.NotSpecified); ThrowTerminatingError(er); } } }
public override void ExecuteCmdlet() { NetworkCredential creds = null; CollectionCreationDetails details = null; OperationResultWithTrackingId response = null; Collection collection = null; collection = FindCollection(CollectionName); if (collection == null) { return; } details = new CollectionCreationDetails() { Name = CollectionName, BillingPlanName = String.IsNullOrWhiteSpace(Plan) ? collection.BillingPlanName : Plan, Description = String.IsNullOrWhiteSpace(Description) ? collection.Description : Description, CustomRdpProperty = String.IsNullOrWhiteSpace(CustomRdpProperty) ? collection.CustomRdpProperty : CustomRdpProperty, TemplateImageName = collection.TemplateImageName }; switch (ParameterSetName) { case DomainJoined: { if (collection.AdInfo == null) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( Commands_RemoteApp.AadInfoCanNotBeAddedToCloudOnlyCollectionMessage, String.Empty, Client.Collections, ErrorCategory.InvalidArgument); ThrowTerminatingError(er); } details.AdInfo = new ActiveDirectoryConfig(); details.VnetName = collection.VnetName; details.AdInfo.DomainName = collection.AdInfo.DomainName; details.AdInfo.OrganizationalUnit = collection.AdInfo.OrganizationalUnit; if (Credential != null) { creds = Credential.GetNetworkCredential(); details.AdInfo.UserName = creds.UserName; details.AdInfo.Password = creds.Password; } break; } } response = CallClient(() => Client.Collections.Set(CollectionName, false, false, details), Client.Collections); if (response != null) { TrackingResult trackingId = new TrackingResult(response); WriteObject(trackingId); } }
public override void ExecuteCmdlet() { // register the subscription for this service if it has not been before // sebsequent call to register is redundent RegisterSubscriptionWithRdfeForRemoteApp(); switch (DetermineParameterSetName()) { case UploadLocalVhd: { string scriptBlock = "Test-Path -Path " + Path; Collection <bool> pathValid = CallPowershellWithReturnType <bool>(scriptBlock); TemplateImage image = null; if (pathValid[0] == false) { throw new RemoteAppServiceException(Commands_RemoteApp.FailedToValidateVhdPathError, ErrorCategory.ObjectNotFound); } task = new LongRunningTask <NewAzureRemoteAppTemplateImage>(this, "RemoteAppTemplateImageUpload", Commands_RemoteApp.UploadTemplateImageJobDescriptionMessage); task.ProcessJob(() => { image = VerifyPreconditions(); image = StartTemplateUpload(image); UploadVhd(image); task.SetStatus(Commands_RemoteApp.JobCompletionStatusMessage); }); WriteObject(task); break; } case AzureVmUpload: { if (IsFeatureEnabled(EnabledFeatures.goldImageImport)) { ImportTemplateImage(); } else { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( string.Format(Commands_RemoteApp.ImportImageFeatureNotEnabledError), String.Empty, Client.Account, ErrorCategory.InvalidOperation ); ThrowTerminatingError(er); } break; } } }
private string GetAzureVmSasUri(string vmImageName) { string mediaLinkUri = null; Uri uri = null; StorageManagementClient storageClient = null; string storageAccountName = null; StorageAccountGetKeysResponse getKeysResponse = null; ErrorRecord er = null; StorageCredentials credentials = null; SharedAccessBlobPolicy accessPolicy = null; CloudPageBlob pageBlob = null; string sas = null; mediaLinkUri = GetImageUri(vmImageName); uri = new Uri(mediaLinkUri); storageClient = new StorageManagementClient(this.Client.Credentials, this.Client.BaseUri); storageAccountName = uri.Authority.Split('.')[0]; getKeysResponse = storageClient.StorageAccounts.GetKeys(storageAccountName); if (getKeysResponse.StatusCode != System.Net.HttpStatusCode.OK) { er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( String.Format(Commands_RemoteApp.GettingStorageAccountKeyErrorFormat, getKeysResponse.StatusCode.ToString()), String.Empty, Client.TemplateImages, ErrorCategory.ConnectionError ); ThrowTerminatingError(er); } credentials = new StorageCredentials(storageAccountName, getKeysResponse.SecondaryKey); accessPolicy = new SharedAccessBlobPolicy(); pageBlob = new CloudPageBlob(uri, credentials); accessPolicy.Permissions = SharedAccessBlobPermissions.Read; accessPolicy.SharedAccessStartTime = DateTime.Now; accessPolicy.SharedAccessExpiryTime = DateTime.Now.AddHours(12); sas = pageBlob.GetSharedAccessSignature(accessPolicy); if (sas == null) { er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( Commands_RemoteApp.FailedToGetSasUriError, String.Empty, Client.TemplateImages, ErrorCategory.ConnectionError ); ThrowTerminatingError(er); } return(mediaLinkUri + sas); }
internal static CloudRecordState CreateErrorStateFromCloudException(CloudException e, string errorId, object targetObject) { ErrorRecordState state = CreateErrorStateFromHttpStatusCode(e.Response.StatusCode); ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromException(e, errorId, targetObject, state.Category); CloudRecordState cloudRecord = new CloudRecordState() { state = state, er = er }; return(cloudRecord); }
private void HandleCloudException(object targetObject, CloudException e) { CloudRecordState cloudRecord = RemoteAppCollectionErrorState.CreateErrorStateFromCloudException(e, String.Empty, targetObject); if (cloudRecord.state.type == ExceptionType.NonTerminating) { WriteError(cloudRecord.er); } else { ThrowTerminatingError(cloudRecord.er); } }
private void ValidateImageOsType(string osType) { if (string.Compare(osType, "Windows", true) != 0) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( String.Format(Commands_RemoteApp.InvalidOsTypeErrorFormat, osType), String.Empty, Client.TemplateImages, ErrorCategory.InvalidArgument ); ThrowTerminatingError(er); } }
private void ValidateImageMediaLink(Uri mediaLink) { if (mediaLink == null || string.IsNullOrEmpty(mediaLink.AbsoluteUri)) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( Commands_RemoteApp.InvalidVmImageNameSpecifiedError, String.Empty, Client.TemplateImages, ErrorCategory.InvalidArgument ); ThrowTerminatingError(er); } }
private string GetOsImageUri(string imageName) { ComputeManagementClient computeClient = new ComputeManagementClient(this.Client.Credentials, this.Client.BaseUri); VirtualMachineOSImageGetResponse imageGetResponse = null; ErrorRecord er = null; try { imageGetResponse = computeClient.VirtualMachineOSImages.Get(imageName); } catch (Hyak.Common.CloudException cloudEx) { // If the image was created in azure with Vm capture, GetOsImageUri won't find that. Don't terminate in this case if (cloudEx.Error.Code != "ResourceNotFound") { er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( cloudEx.Message, String.Empty, Client.TemplateImages, ErrorCategory.InvalidArgument ); ThrowTerminatingError(er); } } catch (Exception ex) { er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( ex.Message, String.Empty, Client.TemplateImages, ErrorCategory.InvalidArgument ); ThrowTerminatingError(er); } if (imageGetResponse != null) { ValidateImageOsType(imageGetResponse.OperatingSystemType); ValidateImageMediaLink(imageGetResponse.MediaLinkUri); return(imageGetResponse.MediaLinkUri.AbsoluteUri); } else { return(null); } }
private bool ValidateCustomerVNetParams(string name, string subnet) { NetworkListResponse.VirtualNetworkSite azureVNet = GetAzureVNet(name); bool isValidSubnetName = false; if (azureVNet == null) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( String.Format(Commands_RemoteApp.InvalidArgumentVNetNameNotFoundMessageFormat, name), String.Empty, Client.Collections, ErrorCategory.InvalidArgument ); ThrowTerminatingError(er); } foreach (NetworkListResponse.Subnet azureSubnet in azureVNet.Subnets) { if (string.Compare(azureSubnet.Name, subnet, true) == 0) { isValidSubnetName = true; Location = azureVNet.Location; break; } } if (!isValidSubnetName) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( String.Format(Commands_RemoteApp.InvalidArgumentSubNetNameNotFoundMessageFormat, subnet), String.Empty, Client.Collections, ErrorCategory.InvalidArgument ); ThrowTerminatingError(er); } return(isValidSubnetName); }
public override void ExecuteCmdlet() { bool showAllVirtualNetworks = String.IsNullOrWhiteSpace(VNetName); bool found = false; if (showAllVirtualNetworks == false) { CreateWildcardPattern(VNetName); } if (ExactMatch) { found = GetVNet(VNetName); if (!found) { WriteErrorWithTimestamp("No VNet found matching: " + VNetName); } } else { if (IncludeSharedKey) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( "You must specify an existing unique virtual network name in order to get the shared VPN key.", String.Empty, Client.VNet, ErrorCategory.InvalidOperation ); WriteError(er); } else { found = GetVNetList(showAllVirtualNetworks, VNetName); } } if (!found) { WriteVerboseWithTimestamp(String.Format("Virtual network name: {0} not found.", VNetName)); } }
protected Collection FindCollection(string CollectionName) { CollectionResult response = null; response = CallClient(() => Client.Collections.Get(CollectionName), Client.Collections); if (response != null) { if (response.Collection == null) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( String.Format("Collection {0} does not exist", CollectionName), String.Empty, Client.Collections, ErrorCategory.ObjectNotFound ); WriteError(er); } } return(response.Collection); }
protected Collection FindCollection(string CollectionName) { CollectionResult response = null; response = CallClient(() => Client.Collections.Get(CollectionName), Client.Collections); if (response != null) { if (response.Collection == null) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( String.Format("Collection {0} does not exist", CollectionName), String.Empty, Client.Principals, ErrorCategory.ObjectNotFound ); WriteError(er); } else if (!String.Equals(response.Collection.Status, "Active", StringComparison.OrdinalIgnoreCase)) { ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( String.Format("Collection {0} is not in the Active state", response.Collection.Name), String.Empty, Client.Principals, ErrorCategory.InvalidOperation ); WriteError(er); } } return(response.Collection); }
protected void ProcessResult(SecurityPrincipalOperationsResult result, string collectionName, Operation operation) { ErrorRecord er = null; ErrorCategory category = ErrorCategory.NotImplemented; String errorMessageFormat = String.Empty; if (result.Errors != null) { switch (operation) { case Operation.Add: errorMessageFormat = "Could not add {0} to collection {1} because of error: {2} [{3}]."; break; case Operation.Remove: errorMessageFormat = "Could not remove {0} from collection {1} because of error: {2} [{3}]."; break; default: errorMessageFormat = "Unknown error."; break; } foreach (SecurityPrincipalOperationErrorDetails errorDetails in result.Errors) { switch (errorDetails.Error) { case SecurityPrincipalOperationError.NotSupported: case SecurityPrincipalOperationError.AlreadyExists: case SecurityPrincipalOperationError.AssignedToAnotherCollection: { category = ErrorCategory.InvalidOperation; break; } case SecurityPrincipalOperationError.NotFound: case SecurityPrincipalOperationError.CouldNotBeResolved: case SecurityPrincipalOperationError.NotDirsynced: { category = ErrorCategory.ObjectNotFound; break; } } er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( String.Format(errorMessageFormat, errorDetails.SecurityPrincipal, collectionName, errorDetails.Error.ToString(), errorDetails.ErrorDetails ), String.Empty, Client.Principals, category ); WriteError(er); } } else { WriteObject(result); } }
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); } }
private string GetVmImageUri(string imageName) { ComputeManagementClient computeClient = new ComputeManagementClient(this.Client.Credentials, this.Client.BaseUri); VirtualMachineVMImageListResponse vmList = null; ErrorRecord er = null; string imageUri = null; try { vmList = computeClient.VirtualMachineVMImages.List(); } catch (Exception ex) { er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( ex.Message, String.Empty, Client.TemplateImages, ErrorCategory.InvalidArgument ); ThrowTerminatingError(er); } foreach (VirtualMachineVMImageListResponse.VirtualMachineVMImage image in vmList.VMImages) { if (string.Compare(image.Name, imageName, true) == 0) { if (image.OSDiskConfiguration != null) { ValidateImageOsType(image.OSDiskConfiguration.OperatingSystem); ValidateImageMediaLink(image.OSDiskConfiguration.MediaLink); imageUri = image.OSDiskConfiguration.MediaLink.AbsoluteUri; break; } else { er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( string.Format(Commands_RemoteApp.NoOsDiskFoundErrorFormat, imageName), String.Empty, Client.TemplateImages, ErrorCategory.InvalidArgument ); ThrowTerminatingError(er); } } } if (imageUri == null) { er = RemoteAppCollectionErrorState.CreateErrorRecordFromString( string.Format(Commands_RemoteApp.NoVmImageFoundErrorFormat, imageName), String.Empty, Client.TemplateImages, ErrorCategory.InvalidArgument ); ThrowTerminatingError(er); } return(imageUri); }
public override void ExecuteCmdlet() { DateTime today = DateTime.Now; CollectionUsageDetailsResult detailsUsage = null; string locale = String.Empty; RemoteAppOperationStatusResult operationResult = null; int maxRetryCount = 60; if (String.IsNullOrWhiteSpace(UsageMonth)) { UsageMonth = today.Month.ToString(); } if (String.IsNullOrWhiteSpace(UsageYear)) { UsageYear = today.Year.ToString(); } locale = System.Globalization.CultureInfo.CurrentCulture.ToString(); detailsUsage = CallClient(() => Client.Collections.GetUsageDetails(CollectionName, UsageYear, UsageMonth, locale), Client.Collections); if (detailsUsage == null) { return; } // The request is async and we have to wait for the usage details to be produced here do { System.Threading.Thread.Sleep(5000); operationResult = CallClient(() => Client.OperationResults.Get(detailsUsage.UsageDetails.OperationTrackingId), Client.OperationResults); }while(operationResult.RemoteAppOperationResult.Status != RemoteAppOperationStatus.Success && operationResult.RemoteAppOperationResult.Status != RemoteAppOperationStatus.Failed && --maxRetryCount > 0); if (operationResult.RemoteAppOperationResult.Status == RemoteAppOperationStatus.Success) { WriteUsageDetails(detailsUsage); } else { if (operationResult.RemoteAppOperationResult.Status == RemoteAppOperationStatus.Failed) { ErrorRecord error = RemoteAppCollectionErrorState.CreateErrorRecordFromString( Commands_RemoteApp.DetailedUsageFailureMessage, String.Empty, Client.Collections, ErrorCategory.ResourceUnavailable); WriteError(error); } else if (maxRetryCount <= 0) { ErrorRecord error = RemoteAppCollectionErrorState.CreateErrorRecordFromString( String.Format(System.Globalization.CultureInfo.InvariantCulture, Commands_RemoteApp.RequestTimedOutFormat, detailsUsage.UsageDetails.OperationTrackingId), String.Empty, Client.Collections, ErrorCategory.OperationTimeout); WriteError(error); } } }
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); } }