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 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); } } }
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); }
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; // Sometimes the clocks are 2-3 seconds fast and the SAS is not yet valid when the service tries to use it. accessPolicy.SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5); accessPolicy.SharedAccessExpiryTime = DateTime.UtcNow.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 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 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 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); }
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(); if (response == null) { ErrorRecord error = RemoteAppCollectionErrorState.CreateErrorRecordFromString( "Unable to retrieve Usage data", String.Empty, null, ErrorCategory.InvalidResult); WriteError(error); return; } } catch (Exception e) { ErrorRecord error = RemoteAppCollectionErrorState.CreateErrorRecordFromException(e, String.Empty, Client.Collections, ErrorCategory.InvalidResult); WriteError(error); return; } using (Stream dataStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { String csvContent = reader.ReadToEnd(); WriteObject(csvContent); } } }
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 = (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); } }
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); } }
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); }
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); } }