public override int GetHashCode() { return((Resource?.GetHashCode() ?? 0) * 31 ^ (BaseAddress?.GetHashCode() ?? 0) ^ (ResourceUri?.GetHashCode() ?? 0) ^ TypeNameHandling.GetHashCode()); }
/// <summary> /// Delete the web app /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="appUri">ResourceUri to the web app</param> /// <param name="alsoDeleteMetrics">Set TRUE to also delete the web app metrics</param> /// <param name="alsoDeleteAppServicePlanIfEmpty">Set TRUE to also delete the App Service Plan if there are no more apps left in the plan</param> /// <returns>True if the app was accepted for deletion, false if it failed validation/etc, NULL if there was an exception</returns> public static async Task <bool?> Delete(string bearerToken, ResourceUri appUri, bool alsoDeleteMetrics = false, bool alsoDeleteAppServicePlanIfEmpty = false) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } RestApiResponse response = await RestApiClient.DELETE( bearerToken, $"https://management.azure.com/{appUri.ToAbsoluteAzureRMEndpointUri()}", CLIENT_API_VERSION, new Dictionary <string, string>() { { "deleteMetrics", (alsoDeleteMetrics ? "true" : "false") }, { "deleteEmptyServerFarm", (alsoDeleteAppServicePlanIfEmpty ? "true" : "false") } }, new int[] { 200, 204, 404 } ); if ((!response.IsExpectedSuccess) || response.WasException) { return(null); } return(response.IsExpectedSuccess); }
/// <summary> /// Remove a virtual machine from the availability set /// </summary> /// <param name="virtualMachine">ResourceUri of the VM to remove</param> public void RemoveVirtualMachine(ResourceUri virtualMachine) { if ((!virtualMachine.Is(ResourceUriCompareLevel.Provider, "Microsoft.Compute")) || (!virtualMachine.Is(ResourceUriCompareLevel.Type, "virtualMachines"))) { throw new ArgumentException($"{nameof(virtualMachine)} does not represent a virtual machine."); } if ((VirtualMachines == null) || (VirtualMachines.Count == 0)) { return; } string resourceUri = virtualMachine.ToString(); SubResource?toRemove = null; foreach (SubResource resource in VirtualMachines) { if (resource.ResourceId.Equals(resourceUri, StringComparison.InvariantCultureIgnoreCase)) { toRemove = resource; break; } } if (toRemove != null) { VirtualMachines.Remove(toRemove); } }
/// <summary> /// Add a virtual machine to the availability set /// </summary> /// <param name="virtualMachine">ResourceUri of the VM to add</param> public void AddVirtualMachine(ResourceUri virtualMachine) { if ((!virtualMachine.Is(ResourceUriCompareLevel.Provider, "Microsoft.Compute")) || (!virtualMachine.Is(ResourceUriCompareLevel.Type, "virtualMachines"))) { throw new ArgumentException($"{nameof(virtualMachine)} does not represent a virtual machine."); } string resourceUri = virtualMachine.ToString(); if (VirtualMachines == null) { VirtualMachines = new List <SubResource>(); } if (VirtualMachines.Count > 0) { foreach (SubResource resource in VirtualMachines) { if (resource.ResourceId.Equals(resourceUri, StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentException($"A virtual machine with the resource Id '{resourceUri}' is already added to this availability set."); } } } VirtualMachines.Add(new SubResource(resourceUri)); }
public async Task <Product> GetProductAsync(ResourceUri productUri) { using (var log = RequestLogger.Current.BeginJungoLog(this)) { try { var uri = Billboard.ResolveExpandAll(productUri.Uri); var productResponse = await Client.GetCacheableAsync <ProductResponse>(uri).ConfigureAwait(false); if (productResponse == null) { return(null); } var prod = productResponse.Product; await SupplyRecentInventoryStatusAsync(new[] { prod }).ConfigureAwait(false); return(prod); } catch (Exception exc) { throw log.LogException(exc); } } }
public override int GetHashCode() { int hash = 1; if (ResourceUri.Length != 0) { hash ^= ResourceUri.GetHashCode(); } if (Severity != global::Grafeas.V1.Severity.Unspecified) { hash ^= Severity.GetHashCode(); } if (FixableCount != 0L) { hash ^= FixableCount.GetHashCode(); } if (TotalCount != 0L) { hash ^= TotalCount.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
/// <summary> /// Set source VM /// </summary> /// <param name="virtualMachine">Source VM resource Uri</param> /// <returns>DiskImage</returns> public DiskImage WithVirtualMachine(ResourceUri virtualMachine) { EnsureProperties(); Properties !.WithVirtualMachine(virtualMachine); return(this); }
/// <summary> /// Inject certificates intot he VM /// </summary> /// <param name="keyVault">Resource Uri to the Azure KeyVault store containing the secrets to inject into the VM</param> public void InjectCertificates(ResourceUri keyVault) { if ((keyVault == null) || (!keyVault.IsValid) || (!keyVault.Is(ResourceUriCompareLevel.Provider, "Microsoft.KeyVault")) || (!keyVault.Is(ResourceUriCompareLevel.Type, "vaults"))) { throw new ArgumentException(nameof(keyVault)); } if (Certificates == null) { Certificates = new List <VMCertificates>(); } // validate if Keyvault is already added string vaultId = keyVault.ToString(); foreach (VMCertificates vault in Certificates) { if (vault.Vault?.ResourceId == vaultId) { throw new ArgumentException($"The vault '{vaultId}' is already injected into this VM."); } } Certificates.Add(new VMCertificates(keyVault)); }
/// <summary> /// Check if a resource exists /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="resourceUri">Absolute resource Id</param> /// <returns>True if exists, False if not, NULL if there was a problem</returns> public static async Task <bool?> Exists(string bearerToken, ResourceUri resourceUri) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((resourceUri == null) || (!resourceUri.IsValid)) { throw new ArgumentNullException(nameof(resourceUri)); } RestApiResponse response = await RestApiClient.HEAD( bearerToken, resourceUri.ToAbsoluteAzureRMEndpointUri(string.Empty), CLIENT_API_VERSION, null, new int[] { 204, 404 } ); if ((!response.IsExpectedSuccess) || response.WasException) { return(null); } return(response.HttpStatus == 204); }
/// <summary> /// Create a data disk by attaching an unmanaged Vhd /// </summary> /// <param name="name">Name of the disk</param> /// <param name="unmanagedVhdFile">URI to the existing unmanaged Vhd on a Storage Account</param> /// <param name="caching">Type of caching to enable</param> /// <param name="enableWriteAcceleration">Flag indicating whether to enable write acceleration on the disk</param> public static VMOSDisk FromUmanagedVhd(string name, ResourceUri unmanagedVhdFile, CachingTypeNamesEnum caching = CachingTypeNamesEnum.None, bool enableWriteAcceleration = false) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } if (!Enum.IsDefined(typeof(CachingTypeNamesEnum), caching)) { throw new ArgumentOutOfRangeException(nameof(caching)); } if ((unmanagedVhdFile == null) || (!unmanagedVhdFile.IsValid) || (!unmanagedVhdFile.Is(ResourceUriCompareLevel.Provider, "Microsoft.Storage")) || (!unmanagedVhdFile.Is(ResourceUriCompareLevel.Type, "storageAccounts"))) { throw new ArgumentException(nameof(unmanagedVhdFile)); } VMOSDisk disk = new VMOSDisk() { Name = name, CreateUsing = DiskCreationOptionsEnum.Copy, VhdFile = new UriResource(unmanagedVhdFile.ToString()), Caching = caching, IsWriteAccelerationEnabled = enableWriteAcceleration }; return(disk); }
/// <summary> /// Get an instance of a web app /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="appServiceUri">Resource Uri to the app service</param> /// <param name="slotName">(Optional) Name of the slot to fetch</param> /// <returns>App service or NULL</returns> public static async Task <AppServiceWebApp?> Get(string bearerToken, ResourceUri appServiceUri, string?slotName = null) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((!appServiceUri.IsValid) || (!appServiceUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Web")) || (!appServiceUri.Is(ResourceUriCompareLevel.Type, "sites"))) { throw new ArgumentException(nameof(appServiceUri)); } string endpoint = string.Empty; if (!string.IsNullOrWhiteSpace(slotName)) { endpoint = $"slots/{slotName}"; } RestApiResponse response = await RestApiClient.GET( bearerToken, appServiceUri.ToAbsoluteAzureRMEndpointUri(endpoint), CLIENT_API_VERSION, null, null, new int[] { 200, 404 } ); if ((!response.IsExpectedSuccess) || (response.HttpStatus == 404) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <AppServiceWebApp>(response.Body)); }
/// <summary> /// Stop a web app, or optionally a specific slot of the app /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="appServiceUri">Resource Uri to the app service</param> /// <param name="slotName">(Optional) Name of the slot to stop -- if unspecified, the entire app is stopped</param> /// <returns>True if the operation was accepted, FALSE if not, NULL if there was a problem</returns> public static async Task <bool?> Stop(string bearerToken, ResourceUri appServiceUri, string?slotName = null) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((!appServiceUri.IsValid) || (!appServiceUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Web")) || (!appServiceUri.Is(ResourceUriCompareLevel.Type, "sites"))) { throw new ArgumentException(nameof(appServiceUri)); } string endpoint = "stop"; if (!string.IsNullOrWhiteSpace(slotName)) { endpoint = $"slots/{slotName}/stop"; } RestApiResponse response = await RestApiClient.POST( bearerToken, appServiceUri.ToAbsoluteAzureRMEndpointUri(endpoint), CLIENT_API_VERSION, null, null, new int[] { 200 } ); if (response.WasException) { return(null); } return(response.IsExpectedSuccess); }
/// <summary> /// Delete a resource. Resources are queued for async deletion and status will be available only later. /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="resourceUri">Absolute resource Id</param> /// <returns>True if accepted for deletion, false if not or there was a problem</returns> public static async Task <bool> Delete(string bearerToken, ResourceUri resourceUri) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((resourceUri == null) || (!resourceUri.IsValid)) { throw new ArgumentNullException(nameof(resourceUri)); } RestApiResponse response = await RestApiClient.DELETE( bearerToken, resourceUri.ToAbsoluteAzureRMEndpointUri(string.Empty), CLIENT_API_VERSION, null, new int[] { 200, 202, 204 } ); if ((!response.IsExpectedSuccess) || response.WasException) { return(false); } return(true); }
public IActionResult GetCuisinesV2(ResourceParameter parameters) { var response = new ListModelResponse <MainMenuDto>() as IListModelResponse <MainMenuDto>; //throw new InvalidOperationException("This is an unhandled exception"); //throw new ECafeException("error occured"); if (!_propertyMappingService.ValidMappingExistsFor <MainMenuDto, MainMenu>(parameters.OrderBy)) { logger.LogError($"Invalid mapping requested in {this.GetType().Name} Method Name"); return(response.ToErrorResponse("Invalid mapping requested", HttpStatusCode.BadRequest)); } if (!typeHelperService.TypeHasProperties <MainMenuDto>(parameters.Fields)) { return(response.ToErrorResponse("Invalid properties name requested", HttpStatusCode.BadRequest)); } var results = _mainMenuGetService.GetAll(parameters); //***Create pagination header var paginationMetadata = ResourceUri <MainMenu> .CreatePaginationHeader(parameters, results, urlHelper, "GetCuisines"); Response.Headers.Add("X-Pagination", Newtonsoft.Json.JsonConvert.SerializeObject(paginationMetadata)); //***Mapping Entity to Dto var medicineTypes = AutoMapper.Mapper.Map <IEnumerable <MainMenuDto> >(results); response.ShapeModel = medicineTypes.ShapeData(parameters.Fields); response.Model = new List <MainMenuDto>(); response.Message = $"Total of records: {response.ShapeModel.Count()}"; response.PageSize = parameters.PageSize; response.PageNumber = parameters.PageNumber; return(response.ToHttpResponse()); }
public void Normalizes(string uri, string expected) { DesignerProperties.SetIsInDesignMode(SharedResourceDictionary.Dummy, true); var actual = new ResourceUri(uri); Assert.IsFalse(actual.Uri.IsAbsoluteUri); Assert.AreEqual(expected, actual.ToString()); Assert.AreEqual(expected, actual.Uri.ToString()); }
protected void Run(ClientPipelineArgs args) { Item itemNotNull = Sitecore.Client.GetItemNotNull(args.Parameters["itemid"], Language.Parse(args.Parameters["language"]), new Sitecore.Data.Version(args.Parameters["version"]), Database.GetDatabase(args.Parameters["database"])); UrlString urlString = ResourceUri.Parse("Control:EditPageProperties").ToUrlString(); itemNotNull.Uri.AddToUrlString(urlString); SheerResponse.ShowModalDialog(urlString.ToString(), false); }
private CookiesForCannedPolicy CreateSignedCookiesForCannedPolicy() { var privateKeyFileInfo = new FileInfo(PrivateKeyFile); return(AmazonCloudFrontCookieSigner.GetCookiesForCannedPolicy(ResourceUri.ToString(), KeyPairId, privateKeyFileInfo, ExpiresOn)); }
/// <summary> /// Add a virtual machine to the availability set /// </summary> /// <param name="virtualMachine">ResourceUri of the VM to add</param> public void AddVirtualMachine(ResourceUri virtualMachine) { if (Properties == null) { Properties = new AvailabilitySetProperties(); } Properties.AddVirtualMachine(virtualMachine); }
/// <summary> /// Initialize a new reference /// </summary> /// <param name="vaultUri">ResourceUri to the KeyVault</param> /// <param name="secretUrl">Absolute URL to the secret or key in the KeyVault</param> public KeyVaultAndSecretReference(ResourceUri vaultUri, string secretUrl) { if (string.IsNullOrWhiteSpace(secretUrl)) { throw new ArgumentNullException(nameof(secretUrl)); } Vault = new SourceVault(vaultUri); SecretUrl = secretUrl; }
/// <summary> /// Create reference to a source KeyVault /// </summary> /// <param name="vaultUri">ResourceUri to an Azure KeyVault</param> public SourceVault(ResourceUri vaultUri) { if ((vaultUri == null) || (!vaultUri.IsValid) || (!vaultUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.KeyVault")) || (!vaultUri.Is(ResourceUriCompareLevel.Type, "vaults"))) { throw new ArgumentException(nameof(vaultUri)); } KeyVaultResourceId = vaultUri.ToString(); }
/// <summary> /// Initialize a new reference /// </summary> /// <param name="vaultUri">ResourceUri to the KeyVault</param> /// <param name="keyUrl">Absolute URL to the key in the KeyVault</param> public KeyVaultAndKeyReference(ResourceUri vaultUri, string keyUrl) { if (string.IsNullOrWhiteSpace(keyUrl)) { throw new ArgumentNullException(nameof(keyUrl)); } Vault = new SourceVault(vaultUri); KeyUrl = keyUrl; }
/// <summary> /// Initialize the VM certificate store /// </summary> /// <param name="keyVault">Resource Uri to the Azure KeyVault store containing the secrets to inject into the VM</param> public VMCertificates(ResourceUri keyVault) { if ((keyVault == null) || (!keyVault.IsValid) || (!keyVault.Is(ResourceUriCompareLevel.Provider, "Microsoft.KeyVault")) || (!keyVault.Is(ResourceUriCompareLevel.Type, "vaults"))) { throw new ArgumentException(nameof(keyVault)); } Vault = new SubResource(keyVault); Certificates = new List <VMCertificateStoreCertificate>(); }
/// <summary> /// Enable boot diagnostics /// </summary> /// <param name="storageAccountBlobUri">Uri to a Azure Storage Blob account where the diagnostics information should be stored.</param> public VMBootDiagnostics(ResourceUri storageAccountBlobUri) { if ((storageAccountBlobUri == null) || (!storageAccountBlobUri.IsValid) || (!storageAccountBlobUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Storage")) || (!storageAccountBlobUri.Is(ResourceUriCompareLevel.Type, "storageAccounts"))) { throw new ArgumentException(nameof(storageAccountBlobUri)); } IsEnabled = true; StorageUri = storageAccountBlobUri.ToString(); }
/// <summary> /// Remove a virtual machine from the availability set /// </summary> /// <param name="virtualMachine">ResourceUri of the VM to remove</param> public void RemoveVirtualMachine(ResourceUri virtualMachine) { if (Properties != null) { if ((Properties.VirtualMachines == null) || (Properties.VirtualMachines.Count == 0)) { return; } Properties.RemoveVirtualMachine(virtualMachine); } }
// Additional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if (Namespace.Expression != null) { targetCommand.AddParameter("Namespace", Namespace.Get(context)); } if (OperationTimeoutSec.Expression != null) { targetCommand.AddParameter("OperationTimeoutSec", OperationTimeoutSec.Get(context)); } if (InputObject.Expression != null) { targetCommand.AddParameter("InputObject", InputObject.Get(context)); } if (Query.Expression != null) { targetCommand.AddParameter("Query", Query.Get(context)); } if (QueryDialect.Expression != null) { targetCommand.AddParameter("QueryDialect", QueryDialect.Get(context)); } if (Property.Expression != null) { targetCommand.AddParameter("Property", Property.Get(context)); } if (PassThru.Expression != null) { targetCommand.AddParameter("PassThru", PassThru.Get(context)); } if (ResourceUri != null) { targetCommand.AddParameter("ResourceUri", ResourceUri.Get(context)); } return(new ActivityImplementationContext() { PowerShellInstance = invoker }); }
private string CreateSignedUrlForCannedPolicy() { // coreclr StreamReader does not have ctor that takes filename using (var fs = File.OpenRead(PrivateKeyFile)) using (var reader = new StreamReader(fs)) { var signedUrl = AmazonCloudFrontUrlSigner.GetCannedSignedURL(ResourceUri.ToString(), reader, KeyPairId, ExpiresOn); return(signedUrl); } }
protected virtual void Run(ClientPipelineArgs args) { var uri = ItemUri.Parse(args.Parameters["uri"]); Item item = Database.GetItem(uri); Error.AssertItemFound(item); if (!args.IsPostBack) { UrlString urlString = ResourceUri.Parse("control:ExportMedia").ToUrlString(); uri.AddToUrlString(urlString); SheerResponse.ShowModalDialog(urlString.ToString(), "280", "220", "", true); args.WaitForPostBack(); return; } if (string.IsNullOrEmpty(args.Result) || args.Result == "undefined") { return; } string[] paramsArray = args.Result.Split('|'); string exportFileName = paramsArray[0]; if (string.IsNullOrWhiteSpace(exportFileName)) { return; } bool recursive = extractRecursiveParam(paramsArray); string exportfolderName = Settings.DataFolder + "/" + Settings.GetSetting("SharedSource.MediaExporterModule.ExportFolderName", "MediaExports"); string exportFileNameWithExtension = exportFileName.EndsWith(".zip") ? exportFileName : exportFileName + ".zip"; FileUtil.CreateFolder(FileUtil.MapPath(exportfolderName)); string zipPath = FileUtil.MapPath(FileUtil.MakePath(exportfolderName, exportFileNameWithExtension, '/')); Log.Info("Starting export of media items to: " + zipPath, this); Sitecore.Shell.Applications.Dialogs.ProgressBoxes.ProgressBox.Execute( "Export Media Items...", "Export Media Items", new Sitecore.Shell.Applications.Dialogs.ProgressBoxes.ProgressBoxMethod(StartProcess), new[] { item as object, zipPath, recursive }); Context.ClientPage.ClientResponse.Download(zipPath); }
/// <summary> /// Create a disk by copying from a VM snapshot /// </summary> /// <param name="sourceSnapshotUri">ResourceUri to the VM's snapshot that is to be copied as a new disk</param> /// <returns>Disk creation metadata</returns> public static DiskCreationMetadata ViaCopy(ResourceUri sourceSnapshotUri) { if ((sourceSnapshotUri == null) || (!sourceSnapshotUri.IsValid) || (!sourceSnapshotUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Compute")) || (!sourceSnapshotUri.Is(ResourceUriCompareLevel.Type, "snapshots"))) { throw new ArgumentException(nameof(sourceSnapshotUri)); } return(new DiskCreationMetadata() { CreationMode = DiskCreationOptionsEnum.Copy, SourceSnapshotOrDiskResourceId = sourceSnapshotUri.ToString() }); }
public void ResourceUriTest() { ResourceUri uri = new ResourceUri("b://hostName/parent/child"); Expect.AreEqual("b://", uri.Scheme); Expect.AreEqual("hostName", uri.Host); Expect.AreEqual("/parent/child", uri.Path); ResourceUri uri2 = new ResourceUri("b://hostName/parent/child?param1=baloney&monkey=true"); Expect.AreEqual("param1=baloney&monkey=true", uri2.QueryString); Expect.AreEqual("baloney", uri2.QueryParams["param1"]); Expect.AreEqual("true", uri2.QueryParams["monkey"]); }
/// <summary> /// /// </summary> /// <param name="diskUri"></param> /// <param name="type"></param> public VMManagedDisk(ResourceUri diskUri, DiskSkuNamesEnum type = DiskSkuNamesEnum.Standard_LRS) { if ((diskUri == null) || (!diskUri.IsValid)) { throw new ArgumentException(nameof(diskUri)); } if (!Enum.IsDefined(typeof(DiskSkuNamesEnum), type)) { throw new ArgumentOutOfRangeException(nameof(type)); } Id = diskUri.ToString(); Type = type; }
private CookiesForCustomPolicy CreateSignedCookiesForCustomPolicy() { // coreclr StreamReader does not have ctor that takes filename using (var fs = File.OpenRead(PrivateKeyFile)) using (var reader = new StreamReader(fs)) { return(AmazonCloudFrontCookieSigner.GetCookiesForCustomPolicy(ResourceUri.ToString(), reader, KeyPairId, ExpiresOn, ActiveFrom, IpRange)); } }