public override void ExecuteCmdlet() { if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName)) { var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, SlotName)); SiteConfig siteConfig = webApp.SiteConfig; var accessRestrictionList = TargetScmSite ? siteConfig.ScmIpSecurityRestrictions : siteConfig.IpSecurityRestrictions; IpSecurityRestriction ipSecurityRestriction = null; IDictionary <string, IList <string> > httpHeader = null; if (HttpHeader != null) { httpHeader = ConvertHeaderHashtable(HttpHeader); } int intPriority = checked ((int)Priority); switch (ParameterSetName) { case IpAddressParameterSet: ipSecurityRestriction = new IpSecurityRestriction(IpAddress, null, null, null, null, Action, null, intPriority, Name, Description, httpHeader); accessRestrictionList.Add(ipSecurityRestriction); break; case ServiceTagParameterSet: ipSecurityRestriction = new IpSecurityRestriction(ServiceTag, null, null, null, null, Action, "ServiceTag", intPriority, Name, Description, httpHeader); accessRestrictionList.Add(ipSecurityRestriction); break; case SubnetNameParameterSet: case SubnetIdParameterSet: var Subnet = ParameterSetName == SubnetNameParameterSet ? SubnetName : SubnetId; //Fetch RG of given SubNet var subNetResourceGroupName = CmdletHelpers.GetSubnetResourceGroupName(DefaultContext, Subnet, VirtualNetworkName); //If unble to fetch SubNet rg from above step, use the input RG to get validation error from api call. subNetResourceGroupName = !String.IsNullOrEmpty(subNetResourceGroupName) ? subNetResourceGroupName : ResourceGroupName; var subnetResourceId = CmdletHelpers.ValidateSubnet(Subnet, VirtualNetworkName, subNetResourceGroupName, DefaultContext.Subscription.Id); if (!IgnoreMissingServiceEndpoint) { CmdletHelpers.VerifySubnetDelegation(subnetResourceId); } ipSecurityRestriction = new IpSecurityRestriction(null, null, subnetResourceId, null, null, Action, null, intPriority, Name, Description, httpHeader); accessRestrictionList.Add(ipSecurityRestriction); break; } if (ShouldProcess(WebAppName, $"Adding Access Restriction Rule for Web App '{WebAppName}'")) { // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, webApp.Location, WebAppName, SlotName, siteConfig); if (PassThru) { // Refresh object to get the final state webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, SlotName)); var accessRestrictionSettings = new PSAccessRestrictionConfig(ResourceGroupName, WebAppName, webApp.SiteConfig, SlotName); WriteObject(accessRestrictionSettings); } } } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); User user = WebsitesClient.GetPublishingCredentials(ResourceGroupName, Name, Slot); HttpResponseMessage r; string deployUrl; string deploymentStatusUrl = user.ScmUri + "/api/deployments/latest"; if (ArchivePath.ToLower().EndsWith("war")) { deployUrl = user.ScmUri + "/api/wardeploy?isAsync=true"; } else if (ArchivePath.ToLower().EndsWith("zip") || ArchivePath.ToLower().EndsWith("jar")) { deployUrl = user.ScmUri + "/api/zipdeploy?isAsync=true"; } else { throw new Exception("Unknown archive type."); } Action zipDeployAction = () => { using (var s = File.OpenRead(ArchivePath)) { HttpClient client = new HttpClient(); var byteArray = Encoding.ASCII.GetBytes(user.PublishingUserName + ":" + user.PublishingPassword); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); HttpContent fileContent = new StreamContent(s); fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"); r = client.PostAsync(deployUrl, fileContent).Result; int numChecks = 0; do { Thread.Sleep(TimeSpan.FromSeconds(2)); r = client.GetAsync(deploymentStatusUrl).Result; numChecks++; } while (r.StatusCode == HttpStatusCode.Accepted && numChecks < NumStatusChecks); if (r.StatusCode == HttpStatusCode.Accepted && numChecks >= NumStatusChecks) { var rec = new ErrorRecord(new Exception("Maximum status polling time exceeded. Deployment is still in progress."), string.Empty, ErrorCategory.OperationTimeout, null); WriteError(rec); } else if (r.StatusCode != HttpStatusCode.OK) { var rec = new ErrorRecord(new Exception("Deployment failed with status code " + r.StatusCode), string.Empty, ErrorCategory.InvalidResult, null); WriteError(rec); } } }; ConfirmAction(this.Force.IsPresent, $"Contents of {ArchivePath} will be deployed to the web app {Name}.", "The web app has been deployed.", Name, zipDeployAction); PSSite app = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, Slot)); WriteObject(app); }
public override void ExecuteCmdlet() { if (string.Equals(ParameterSetName, ParameterSet2Name)) { string rg, name, slot; if (!CmdletHelpers.TryParseWebAppMetadataFromResourceId(WebApp.Id, out rg, out name, out slot, true)) { throw new ValidationMetadataException("Input object is a deployment slot but should be a production web app"); } ResourceGroupName = rg; Name = name; } if (string.IsNullOrWhiteSpace(Slot)) { var output = WebsitesClient.ListWebApps(ResourceGroupName, Name); var slots = new List <PSSite>(); foreach (var slot in output) { slots.Add(new PSSite(slot)); } WriteObject(slots, true); } else { WriteObject(new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, Slot))); } }
public override void ExecuteCmdlet() { if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName)) { var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, null)); SiteConfig siteConfig = webApp.SiteConfig; //Check for Rule existance with the given name. var givenRampUpRuleObj = siteConfig.Experiments.RampUpRules.FirstOrDefault(item => item.Name == RuleName); if (givenRampUpRuleObj != null) { if (this.ShouldProcess(this.RuleName, string.Format("Deleting Routing Rule for slot - '{0}' from Web Application - {1}", this.RuleName, this.WebAppName))) { //Remove the rule siteConfig.Experiments.RampUpRules.Remove(givenRampUpRuleObj); // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, webApp.Location, WebAppName, null, siteConfig, null, null, null); if (PassThru.IsPresent) { WriteObject(true); } } } else { throw new ValidationMetadataException(string.Format(Properties.Resources.UpdateAndGetRoutingRuleErrorMessage, RuleName, WebAppName)); } } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); CloningInfo cloningInfo = null; if (SourceWebApp != null) { cloningInfo = new CloningInfo { SourceWebAppId = SourceWebApp.Id, SourceWebAppLocation = SourceWebApp.Location, CloneCustomHostNames = !IgnoreCustomHostNames.IsPresent, CloneSourceControl = !IgnoreSourceControl.IsPresent, ConfigureLoadBalancing = false, AppSettingsOverrides = AppSettingsOverrides == null ? null : AppSettingsOverrides.Cast <DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString(), StringComparer.Ordinal) }; cloningInfo = new PSCloningInfo(cloningInfo); } var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, null)); var site = new PSSite(WebsitesClient.CreateWebApp(ResourceGroupName, Name, Slot, webApp.Location, AppServicePlan == null?webApp.ServerFarmId : AppServicePlan, cloningInfo, AseName, AseResourceGroupName)); UpdateConfigIfNeeded(site); }
protected override void ProcessRecord() { base.ProcessRecord(); var webapp = new PSSite(WebsitesClient.GetWebApp(resourceGroupName, webAppName, slot)); WriteObject(CmdletHelpers.GetHostNameSslStatesFromSiteResponse(webapp, Name)); }
public override void ExecuteCmdlet() { switch (ParameterSetName) { case ParameterSet1: if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(Name)) { WriteObject(new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, null))); } else if (!string.IsNullOrWhiteSpace(ResourceGroupName)) { GetByResourceGroup(); } else if (!string.IsNullOrWhiteSpace(Name)) { GetByWebAppName(); } else { GetBySubscription(); } break; case ParameterSet2: GetByAppServicePlan(); break; case ParameterSet3: GetByLocation(); break; } }
private void GetByWebAppName() { const string progressDescriptionFormat = "Progress: {0}/{1} web apps processed."; var progressRecord = new ProgressRecord(1, string.Format("Get web apps with name '{0}'", Name), "Progress:"); WriteProgress(progressRecord); var sites = ResourcesClient.ResourceManagementClient.FilterResources(new FilterResourcesOptions { ResourceType = "Microsoft.Web/Sites" }).Where(s => string.Equals(s.Name, Name, StringComparison.OrdinalIgnoreCase)).ToArray(); var list = new List <PSSite>(); for (var i = 0; i < sites.Length; i++) { var s = sites[i]; var result = WebsitesClient.GetWebApp(s.ResourceGroupName, s.Name, null); if (result != null) { list.Add(new PSSite(result)); } progressRecord.StatusDescription = string.Format(progressDescriptionFormat, i + 1, sites.Length); progressRecord.PercentComplete = (100 * (i + 1)) / sites.Length; WriteProgress(progressRecord); } WriteObject(list, true); }
protected override void ProcessRecord() { switch (ParameterSetName) { case ParameterSet1: if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(Name)) { WriteObject(WebsitesClient.GetWebApp(ResourceGroupName, Name, null)); } else if (!string.IsNullOrWhiteSpace(ResourceGroupName)) { GetByResourceGroup(); } else if (!string.IsNullOrWhiteSpace(Name)) { GetByWebAppName(); } else { GetBySubscription(); } break; case ParameterSet2: GetByAppServicePlan(); break; case ParameterSet3: GetByLocation(); break; } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); string deletedSiteId = string.IsNullOrEmpty(DeletedId) ? GetDeletedSiteResourceId() : DeletedId; ResolveTargetParameters(); DeletedAppRestoreRequest restoreReq = new DeletedAppRestoreRequest() { DeletedSiteId = deletedSiteId, RecoverConfiguration = !this.RestoreContentOnly, UseDRSecondary = UseDisasterRecovery }; Action restoreAction = () => WebsitesClient.RestoreDeletedWebApp(TargetResourceGroupName, TargetName, TargetSlot, restoreReq); if (WebsitesClient.WebAppExists(TargetResourceGroupName, TargetName, TargetSlot)) { ConfirmAction(this.Force.IsPresent, "Target web app contents will be overwritten with the contents of the deleted app.", "The deleted app has been restored.", TargetName, restoreAction); } else { if (string.IsNullOrEmpty(TargetAppServicePlanName)) { throw new Exception("Target app " + TargetName + " does not exist. Specify TargetAppServicePlanName for it to be created automatically."); } AppServicePlan plan = WebsitesClient.GetAppServicePlan(TargetResourceGroupName, TargetAppServicePlanName); if (plan == null) { throw new Exception("Target App Service Plan " + TargetAppServicePlanName + " not found in target Resource Group " + TargetResourceGroupName); } try { Action createRestoreAction = () => { WebsitesClient.CreateWebApp(TargetResourceGroupName, TargetName, TargetSlot, plan.Location, TargetAppServicePlanName, null, string.Empty, string.Empty); restoreAction(); }; string confirmMsg = string.Format("This web app will be created. App Name: {0}, Resource Group: {1}", TargetName, TargetResourceGroupName); if (!string.IsNullOrEmpty(TargetSlot)) { confirmMsg += ", Slot: " + TargetSlot; } ConfirmAction(this.Force.IsPresent, confirmMsg, "The deleted app has been restored.", TargetName, createRestoreAction); } catch (Exception e) { WebsitesClient.RemoveWebApp(TargetResourceGroupName, TargetName, TargetSlot, true, true, false); throw e; } } PSSite restoredApp = new PSSite(WebsitesClient.GetWebApp(TargetResourceGroupName, TargetName, TargetSlot)); WriteObject(restoredApp); }
public override void ExecuteCmdlet() { if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(Name)) { var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, SlotName)); var accessRestrictionConfig = new PSAccessRestrictionConfig(ResourceGroupName, Name, webApp.SiteConfig, SlotName); WriteObject(accessRestrictionConfig); } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); bool inheritConfig = false; switch (ParameterSetName) { case InputValuesParameterSet: inheritConfig = ScmSiteUseMainSiteRestrictionConfig; break; case InputObjectParameterSet: inheritConfig = InputObject.ScmSiteUseMainSiteRestrictionConfig; ResourceGroupName = InputObject.ResourceGroupName; Name = InputObject.WebAppName; SlotName = InputObject.SlotName; break; } string updateActionText = inheritConfig ? "" : "not "; if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(Name)) { if (ShouldProcess(Name, $"Update Scm Site of WebApp '{Name}' to {updateActionText}use Main Site Access Restriction Config")) { var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, SlotName)); SiteConfig siteConfig = webApp.SiteConfig; if (siteConfig.ScmIpSecurityRestrictionsUseMain != inheritConfig) { siteConfig.ScmIpSecurityRestrictionsUseMain = inheritConfig; // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, webApp.Location, Name, SlotName, siteConfig); } if (PassThru) { var accessRestrictionConfig = new PSAccessRestrictionConfig(ResourceGroupName, Name, webApp.SiteConfig, SlotName); WriteObject(accessRestrictionConfig); } } } }
public override void ExecuteCmdlet() { if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName)) { var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, null)); SiteConfig siteConfig = webApp.SiteConfig; //Check for Rule existance with the given name. var givenRampUpRuleObj = siteConfig.Experiments.RampUpRules.FirstOrDefault(item => item.Name == RuleName); if (givenRampUpRuleObj != null) { WriteObject(givenRampUpRuleObj); } else { throw new ValidationMetadataException(string.Format(Properties.Resources.UpdateAndGetRoutingRuleErrorMessage, RuleName, WebAppName)); } } }
protected override void ProcessRecord() { base.ProcessRecord(); CloningInfo cloningInfo = null; if (SourceWebApp != null) { cloningInfo = new CloningInfo { SourceWebAppId = SourceWebApp.Id, CloneCustomHostNames = !IgnoreCustomHostNames.IsPresent, CloneSourceControl = !IgnoreSourceControl.IsPresent, ConfigureLoadBalancing = false, AppSettingsOverrides = AppSettingsOverrides == null ? null : AppSettingsOverrides.Cast <DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString(), StringComparer.Ordinal) }; } var webApp = WebsitesClient.GetWebApp(ResourceGroupName, Name, null); WriteObject(WebsitesClient.CreateWebApp(ResourceGroupName, Name, Slot, webApp.Location, AppServicePlan, cloningInfo)); }
private void UpdateConfigIfNeeded(Site site) { SiteConfig siteConfig = site.SiteConfig; bool configUpdateRequired = false; if (ContainerImageName != null) { if (site.IsXenon.GetValueOrDefault()) { siteConfig.WindowsFxVersion = CmdletHelpers.DockerImagePrefix + ContainerImageName; configUpdateRequired = true; } } Hashtable appSettings = GetAppSettingsToUpdate(); if (appSettings.Count > 0) { configUpdateRequired = true; } if (configUpdateRequired && siteConfig.AppSettings != null) { foreach (NameValuePair nameValuePair in siteConfig.AppSettings) { if (!appSettings.ContainsKey(nameValuePair.Name)) { appSettings[nameValuePair.Name] = nameValuePair.Value; } } } if (configUpdateRequired) { WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, site.Location, Name, Slot, siteConfig, appSettings.ConvertToStringDictionary()); site = WebsitesClient.GetWebApp(ResourceGroupName, Name, Slot); } WriteObject(site); }
protected override void ProcessRecord() { base.ProcessRecord(); ConfirmAction( Force.IsPresent, string.Format(Properties.Resources.RemovingWebAppSSLBinding, Name), Properties.Resources.RemoveWebAppSSLBinding, Name, () => { var webapp = WebsitesClient.GetWebApp(resourceGroupName, webAppName, slot); var hostNameSslStates = CmdletHelpers.GetHostNameSslStatesFromSiteResponse(webapp, Name).ToList(); if (hostNameSslStates.Count > 0) { var thumbprint = hostNameSslStates[0].Thumbprint; WebsitesClient.UpdateHostNameSslState(resourceGroupName, webAppName, slot, webapp.Location, Name, SslState.Disabled, null); if (!DeleteCertificate.HasValue || DeleteCertificate.Value) { var certificateResourceGroup = CmdletHelpers.GetResourceGroupFromResourceId(webapp.ServerFarmId); var certificates = CmdletHelpers.GetCertificates(this.ResourcesClient, this.WebsitesClient, certificateResourceGroup, thumbprint); if (certificates.Length > 0) { try { WebsitesClient.RemoveCertificate(certificateResourceGroup, certificates[0].Name); } catch (CloudException e) { // This exception is thrown when there are other Ssl bindings using this certificate. Let's swallow it and continue. if (e.Response.StatusCode != HttpStatusCode.Conflict) { throw; } } } } } }); }
public override void ExecuteCmdlet() { if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName)) { if (ShouldProcess(WebAppName, $"Removing Access Restriction Rule '{Name}' from Web App '{WebAppName}'")) { var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, SlotName)); SiteConfig siteConfig = webApp.SiteConfig; var accessRestrictionList = TargetScmSite ? siteConfig.ScmIpSecurityRestrictions : siteConfig.IpSecurityRestrictions; IpSecurityRestriction ipSecurityRestriction = null; bool accessRestrictionExists = false; foreach (var accessRestriction in accessRestrictionList) { if (accessRestriction.Name.ToLowerInvariant() == Name.ToLowerInvariant()) { ipSecurityRestriction = accessRestriction; accessRestrictionExists = true; break; } } if (accessRestrictionExists) { accessRestrictionList.Remove(ipSecurityRestriction); } // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, webApp.Location, WebAppName, SlotName, siteConfig); if (PassThru) { // Refresh object to get the final state webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, SlotName)); var accessRestrictionConfig = new PSAccessRestrictionConfig(ResourceGroupName, WebAppName, webApp.SiteConfig, SlotName); WriteObject(accessRestrictionConfig); } } } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); Site targetApp = WebsitesClient.GetWebApp(ResourceGroupName, Name, Slot); SnapshotRecoveryTarget target = new SnapshotRecoveryTarget() { Location = targetApp.Location, Id = targetApp.Id }; SnapshotRecoveryRequest recoveryReq = new SnapshotRecoveryRequest() { Overwrite = true, SnapshotTime = this.InputObject.SnapshotTime.ToString("o"), RecoverConfiguration = this.RecoverConfiguration, IgnoreConflictingHostNames = true, RecoveryTarget = target }; Action recoverAction = () => WebsitesClient.RecoverSite(InputObject.ResourceGroupName, InputObject.Name, InputObject.Slot, recoveryReq); ConfirmAction(this.Force.IsPresent, "Web app contents will be overwritten with the contents of the snapshot.", "The snapshot has been restored.", InputObject.Name, recoverAction); }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); var sourceApp = new PSSite(WebsitesClient.GetWebApp(InputObject.ResourceGroupName, InputObject.Name, InputObject.Slot)); SnapshotRecoverySource source = new SnapshotRecoverySource() { Location = sourceApp.Location, Id = sourceApp.Id }; SnapshotRestoreRequest recoveryReq = new SnapshotRestoreRequest() { Overwrite = true, SnapshotTime = this.InputObject.SnapshotTime.ToString("o"), RecoverConfiguration = this.RecoverConfiguration, IgnoreConflictingHostNames = true, RecoverySource = source, UseDRSecondary = UseDisasterRecovery }; Action recoverAction = () => WebsitesClient.RestoreSnapshot(ResourceGroupName, Name, Slot, recoveryReq); ConfirmAction(this.Force.IsPresent, "Web app contents will be overwritten with the contents of the snapshot.", "The snapshot has been restored.", Name, recoverAction); }
private void GetByLocation() { const string progressDescriptionFormat = "Progress: {0}/{1} web apps processed."; var progressRecord = new ProgressRecord(1, string.Format("Get web apps at location '{0}'", Location), "Progress:"); WriteProgress(progressRecord); var sites = this.ResourcesClient.ResourceManagementClient.FilterResources(new FilterResourcesOptions() { ResourceType = "Microsoft.Web/Sites" }).Where(s => string.Equals(s.Location, Location.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)).ToArray(); var list = new List <PSSite>(); for (var i = 0; i < sites.Length; i++) { try { var sf = sites[i]; var result = WebsitesClient.GetWebApp(sf.ResourceGroupName, sf.Name, null); if (result != null) { list.Add(new PSSite(result)); } } catch (Exception e) { WriteExceptionError(e); } progressRecord.StatusDescription = string.Format(progressDescriptionFormat, i + 1, sites.Length); progressRecord.PercentComplete = (100 * (i + 1)) / sites.Length; WriteProgress(progressRecord); } WriteObject(list, true); }
protected override void ProcessRecord() { if (string.Equals(ParameterSetName, ParameterSet2Name)) { string rg, name, slot; if (!CmdletHelpers.TryParseWebAppMetadataFromResourceId(WebApp.Id, out rg, out name, out slot, true)) { throw new ValidationMetadataException("Input object is a deployment slot but should be a production web app"); } ResourceGroupName = rg; Name = name; } if (string.IsNullOrWhiteSpace(Slot)) { WriteObject(WebsitesClient.ListWebApps(ResourceGroupName, Name)); } else { WriteObject(WebsitesClient.GetWebApp(ResourceGroupName, Name, Slot)); } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); if (string.IsNullOrEmpty(AppServicePlan)) { Site app = WebsitesClient.GetWebApp(ResourceGroupName, Name, Slot); this.AppServicePlan = app.ServerFarmId.Split('/').Last(); } RestoreRequest request = new RestoreRequest() { StorageAccountUrl = this.StorageAccountUrl, BlobName = this.BlobName, SiteName = CmdletHelpers.GenerateSiteWithSlotName(Name, Slot), Overwrite = this.Overwrite.IsPresent, AppServicePlan = this.AppServicePlan, IgnoreConflictingHostNames = this.IgnoreConflictingHostNames.IsPresent, Databases = this.Databases, OperationType = BackupRestoreOperationType.Default }; // The id here does not actually matter. It is an artifact of the CSM API requirements. It should be possible // to restore from a backup that is no longer stored in our Backups table. WebsitesClient.RestoreSite(ResourceGroupName, Name, Slot, "1", request); }
public override void ExecuteCmdlet() { if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName)) { var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, null)); SiteConfig siteConfig = webApp.SiteConfig; if (RoutingRule != null) { var routingRule = CmdletHelpers.ConvertToStringDictionary(RoutingRule); RampUpRule rampUpRule = new RampUpRule(); foreach (var item in routingRule) { CmdletHelpers.SetObjectProperty(rampUpRule, item.Key, item.Value); } //Check for Rule existance with the given name. var givenRampUpRuleObj = siteConfig.Experiments.RampUpRules.FirstOrDefault(item => item.Name == rampUpRule.Name); if (givenRampUpRuleObj == null) { if (this.ShouldProcess(this.WebAppName, string.Format("Creating a new Routing Rule for slot '{0}' in Web Application - {1}.", rampUpRule.Name, this.WebAppName))) { //Add the given rule to the existing config siteConfig.Experiments.RampUpRules.Add(rampUpRule); // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, webApp.Location, WebAppName, null, siteConfig, null, null, null); //var app = WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, null); //WriteObject(app.SiteConfig.Experiments.RampUpRules.FirstOrDefault(rule => rule.Name == rampUpRule.Name)); WriteObject(rampUpRule); } } else { throw new ValidationMetadataException(string.Format(Properties.Resources.AddRoutingRuleErrorMessage, rampUpRule.Name, WebAppName)); } } } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); WebsitesClient.StartWebApp(ResourceGroupName, Name, null); WriteObject(WebsitesClient.GetWebApp(ResourceGroupName, Name, null)); }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); SiteConfig siteConfig = null; string location = null; switch (ParameterSetName) { case ParameterSet1Name: WebApp = WebsitesClient.GetWebApp(ResourceGroupName, Name, null); location = WebApp.Location; var parameters = new HashSet <string>(MyInvocation.BoundParameters.Keys, StringComparer.OrdinalIgnoreCase); if (parameters.Any(p => CmdletHelpers.SiteConfigParameters.Contains(p))) { siteConfig = new SiteConfig { DefaultDocuments = parameters.Contains("DefaultDocuments") ? DefaultDocuments : null, NetFrameworkVersion = parameters.Contains("NetFrameworkVersion") ? NetFrameworkVersion : null, PhpVersion = parameters.Contains("PhpVersion") ? PhpVersion : null, RequestTracingEnabled = parameters.Contains("RequestTracingEnabled") ? (bool?)RequestTracingEnabled : null, HttpLoggingEnabled = parameters.Contains("HttpLoggingEnabled") ? (bool?)HttpLoggingEnabled : null, DetailedErrorLoggingEnabled = parameters.Contains("DetailedErrorLoggingEnabled") ? (bool?)DetailedErrorLoggingEnabled : null, HandlerMappings = parameters.Contains("HandlerMappings") ? HandlerMappings : null, ManagedPipelineMode = parameters.Contains("ManagedPipelineMode") ? (ManagedPipelineMode?)Enum.Parse(typeof(ManagedPipelineMode), ManagedPipelineMode) : null, WebSocketsEnabled = parameters.Contains("WebSocketsEnabled") ? (bool?)WebSocketsEnabled : null, Use32BitWorkerProcess = parameters.Contains("Use32BitWorkerProcess") ? (bool?)Use32BitWorkerProcess : null }; } // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, location, Name, null, siteConfig, AppSettings.ConvertToStringDictionary(), ConnectionStrings.ConvertToConnectionStringDictionary()); if (parameters.Contains("AppServicePlan")) { WebsitesClient.UpdateWebApp(ResourceGroupName, location, Name, null, AppServicePlan); } if (parameters.Contains("HostNames")) { WebsitesClient.AddCustomHostNames(ResourceGroupName, location, Name, HostNames); } break; case ParameterSet2Name: // Web app is direct or pipeline input string servicePlanName; string rg; location = WebApp.Location; siteConfig = WebApp.SiteConfig; // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, location, Name, null, siteConfig, WebApp.SiteConfig == null ? null : WebApp.SiteConfig.AppSettings.ToDictionary(nvp => nvp.Name, nvp => nvp.Value, StringComparer.OrdinalIgnoreCase), WebApp.SiteConfig == null ? null : WebApp.SiteConfig.ConnectionStrings.ToDictionary(nvp => nvp.Name, nvp => new ConnStringValueTypePair { Type = nvp.Type, Value = nvp.ConnectionString }, StringComparer.OrdinalIgnoreCase)); CmdletHelpers.TryParseAppServicePlanMetadataFromResourceId(WebApp.ServerFarmId, out rg, out servicePlanName); WebsitesClient.UpdateWebApp(ResourceGroupName, location, Name, null, servicePlanName); WebsitesClient.AddCustomHostNames(ResourceGroupName, location, Name, WebApp.HostNames.ToArray()); break; } WriteObject(WebsitesClient.GetWebApp(ResourceGroupName, Name, null)); }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); WebsitesClient.StopWebApp(ResourceGroupName, Name, Slot); WriteObject(new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, Slot))); }
public override void ExecuteCmdlet() { if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName)) { var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, SlotName)); SiteConfig siteConfig = webApp.SiteConfig; var accessRestrictionList = TargetScmSite ? siteConfig.ScmIpSecurityRestrictions : siteConfig.IpSecurityRestrictions; IpSecurityRestriction ipSecurityRestriction = null; bool accessRestrictionExists = false; int intPriority = checked ((int)Priority); switch (ParameterSetName) { case IpAddressParameterSet: foreach (var accessRestriction in accessRestrictionList) { if (accessRestriction.IpAddress != null && accessRestriction.IpAddress == IpAddress && accessRestriction.Action.ToLowerInvariant() == Action.ToLowerInvariant()) { accessRestrictionExists = true; accessRestriction.Name = Name; accessRestriction.Priority = intPriority; accessRestriction.Description = Description; break; } } if (!accessRestrictionExists) { ipSecurityRestriction = new IpSecurityRestriction(IpAddress, null, null, null, null, Action, null, intPriority, Name, Description); accessRestrictionList.Add(ipSecurityRestriction); } break; case SubnetNameParameterSet: case SubnetIdParameterSet: var Subnet = ParameterSetName == SubnetNameParameterSet ? SubnetName : SubnetId; //Fetch RG of given SubNet var subNetResourceGroupName = CmdletHelpers.GetSubnetResourceGroupName(DefaultContext, Subnet, VirtualNetworkName); //If unble to fetch SubNet rg from above step, use the input RG to get validation error from api call. subNetResourceGroupName = !String.IsNullOrEmpty(subNetResourceGroupName) ? subNetResourceGroupName : ResourceGroupName; var subnetResourceId = CmdletHelpers.ValidateSubnet(Subnet, VirtualNetworkName, subNetResourceGroupName, DefaultContext.Subscription.Id); if (!IgnoreMissingServiceEndpoint) { CmdletHelpers.VerifySubnetDelegation(subnetResourceId); } foreach (var accessRestriction in accessRestrictionList) { if (accessRestriction.VnetSubnetResourceId != null && accessRestriction.VnetSubnetResourceId.ToLowerInvariant() == subnetResourceId.ToLowerInvariant() && accessRestriction.Action.ToLowerInvariant() == Action.ToLowerInvariant()) { accessRestrictionExists = true; accessRestriction.Name = Name; accessRestriction.Priority = intPriority; accessRestriction.Description = Description; break; } } if (!accessRestrictionExists) { ipSecurityRestriction = new IpSecurityRestriction(null, null, subnetResourceId, null, null, Action, null, intPriority, Name, Description); accessRestrictionList.Add(ipSecurityRestriction); } break; } string updateAction = accessRestrictionExists ? "Updating" : "Adding"; if (ShouldProcess(WebAppName, $"{updateAction} Access Restriction Rule '{Name}' for Web App '{WebAppName}'")) { // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, webApp.Location, WebAppName, SlotName, siteConfig); if (PassThru) { // Refresh object to get the final state webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, SlotName)); var accessRestrictionSettings = new PSAccessRestrictionConfig(ResourceGroupName, WebAppName, webApp.SiteConfig, SlotName); WriteObject(accessRestrictionSettings); } } } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); SiteConfig siteConfig = null; Site site = null; string location = null; IDictionary <string, string> tags = null; switch (ParameterSetName) { case ParameterSet1Name: WebApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, null)); location = WebApp.Location; tags = WebApp.Tags; var parameters = new HashSet <string>(MyInvocation.BoundParameters.Keys, StringComparer.OrdinalIgnoreCase); if (parameters.Any(p => CmdletHelpers.SiteConfigParameters.Contains(p))) { siteConfig = new SiteConfig { DefaultDocuments = parameters.Contains("DefaultDocuments") ? DefaultDocuments : null, NetFrameworkVersion = parameters.Contains("NetFrameworkVersion") ? NetFrameworkVersion : null, PhpVersion = parameters.Contains("PhpVersion") ? PhpVersion.ToLower() == "off" ? "" : PhpVersion : null, RequestTracingEnabled = parameters.Contains("RequestTracingEnabled") ? (bool?)RequestTracingEnabled : null, HttpLoggingEnabled = parameters.Contains("HttpLoggingEnabled") ? (bool?)HttpLoggingEnabled : null, DetailedErrorLoggingEnabled = parameters.Contains("DetailedErrorLoggingEnabled") ? (bool?)DetailedErrorLoggingEnabled : null, HandlerMappings = parameters.Contains("HandlerMappings") ? HandlerMappings : null, ManagedPipelineMode = parameters.Contains("ManagedPipelineMode") ? (ManagedPipelineMode?)Enum.Parse(typeof(ManagedPipelineMode), ManagedPipelineMode) : null, WebSocketsEnabled = parameters.Contains("WebSocketsEnabled") ? (bool?)WebSocketsEnabled : null, Use32BitWorkerProcess = parameters.Contains("Use32BitWorkerProcess") ? (bool?)Use32BitWorkerProcess : null, AutoSwapSlotName = parameters.Contains("AutoSwapSlotName") ? AutoSwapSlotName : null, NumberOfWorkers = parameters.Contains("NumberOfWorkers") ? NumberOfWorkers : WebApp.SiteConfig.NumberOfWorkers }; } Hashtable appSettings = AppSettings ?? new Hashtable(); if (siteConfig == null) { siteConfig = WebApp.SiteConfig; } //According to current implementation if AppSettings parameter is provided we are overriding existing AppSettings if (WebApp.SiteConfig.AppSettings != null && AppSettings == null) { foreach (var setting in WebApp.SiteConfig.AppSettings) { appSettings[setting.Name] = setting.Value; } } if (ContainerImageName != null) { string dockerImage = CmdletHelpers.DockerImagePrefix + ContainerImageName; if (WebApp.IsXenon.GetValueOrDefault()) { siteConfig.WindowsFxVersion = dockerImage; } else if (WebApp.Reserved.GetValueOrDefault()) { siteConfig.LinuxFxVersion = dockerImage; } } if (ContainerRegistryUrl != null) { appSettings[CmdletHelpers.DocerRegistryServerUrl] = ContainerRegistryUrl; } if (ContainerRegistryUser != null) { appSettings[CmdletHelpers.DocerRegistryServerUserName] = ContainerRegistryUser; } if (ContainerRegistryPassword != null) { appSettings[CmdletHelpers.DocerRegistryServerPassword] = ContainerRegistryPassword.ConvertToString(); } if (parameters.Contains("EnableContainerContinuousDeployment")) { if (EnableContainerContinuousDeployment) { appSettings[CmdletHelpers.DockerEnableCI] = "true"; } else { appSettings.Remove(CmdletHelpers.DockerEnableCI); } } // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, location, Name, null, siteConfig, appSettings.ConvertToStringDictionary(), ConnectionStrings.ConvertToConnectionStringDictionary(), AzureStoragePath.ConvertToAzureStorageAccountPathPropertyDictionary()); //Update WebApp object after configuration update WebApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, null)); if (parameters.Any(p => CmdletHelpers.SiteParameters.Contains(p))) { site = new Site { Location = location, Tags = tags, ServerFarmId = WebApp.ServerFarmId, Identity = parameters.Contains("AssignIdentity") ? AssignIdentity ? new ManagedServiceIdentity("SystemAssigned", null, null) : new ManagedServiceIdentity("None", null, null) : WebApp.Identity, HttpsOnly = parameters.Contains("HttpsOnly") ? HttpsOnly : WebApp.HttpsOnly }; WebsitesClient.UpdateWebApp(ResourceGroupName, location, Name, null, WebApp.ServerFarmId, new PSSite(site)); } if (parameters.Contains("AppServicePlan")) { // AzureStorage path is not a part of the back end siteObject, but if the PSSite Object is given as an input, so simply set this to null WebApp.AzureStoragePath = null; WebsitesClient.UpdateWebApp(ResourceGroupName, location, Name, null, AppServicePlan, WebApp); } if (parameters.Contains("HostNames")) { WebsitesClient.AddCustomHostNames(ResourceGroupName, location, Name, HostNames); } break; case ParameterSet2Name: // Web app is direct or pipeline input string servicePlanName; string rg; location = WebApp.Location; siteConfig = WebApp.SiteConfig; // Update web app configuration WebsitesClient.UpdateWebAppConfiguration( ResourceGroupName, location, Name, null, siteConfig, WebApp.SiteConfig == null ? null : WebApp.SiteConfig .AppSettings .ToDictionary( nvp => nvp.Name, nvp => nvp.Value, StringComparer.OrdinalIgnoreCase), WebApp.SiteConfig?.ConnectionStrings .ToDictionary( nvp => nvp.Name, nvp => new ConnStringValueTypePair { Type = nvp.Type.Value, Value = nvp.ConnectionString }, StringComparer.OrdinalIgnoreCase)); CmdletHelpers.TryParseAppServicePlanMetadataFromResourceId(WebApp.ServerFarmId, out rg, out servicePlanName); // AzureStorage path is not a part of the back end siteObject, but if the PSSite Object is given as an input, we will some value for this WebApp.AzureStoragePath = null; WebsitesClient.UpdateWebApp(ResourceGroupName, location, Name, null, servicePlanName, WebApp); WebsitesClient.AddCustomHostNames(ResourceGroupName, location, Name, WebApp.HostNames.ToArray()); break; } WriteObject(new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, null))); }
protected override void ProcessRecord() { if (ParameterSetName != ParameterSet1Name && ParameterSetName != ParameterSet2Name && ParameterSetName != ParameterSet3Name && ParameterSetName != ParameterSet4Name) { throw new ValidationMetadataException("Please input web app and certificate."); } if (ParameterSetName == ParameterSet3Name || ParameterSetName == ParameterSet4Name) { CmdletHelpers.ExtractWebAppPropertiesFromWebApp(WebApp, out resourceGroupName, out webAppName, out slot); } else { resourceGroupName = ResourceGroupName; webAppName = WebAppName; slot = Slot; } string thumbPrint = null; var webapp = WebsitesClient.GetWebApp(resourceGroupName, webAppName, slot); switch (ParameterSetName) { case ParameterSet1Name: case ParameterSet3Name: var certificateBytes = File.ReadAllBytes(CertificateFilePath); var certificateDetails = new X509Certificate2(certificateBytes, CertificatePassword); var certificateName = GenerateCertName(certificateDetails.Thumbprint, webapp.HostingEnvironmentProfile != null ? webapp.HostingEnvironmentProfile.Name : null, webapp.Location, resourceGroupName); var certificate = new Certificate { PfxBlob = Convert.ToBase64String(certificateBytes), Password = CertificatePassword, Location = webapp.Location }; if (webapp.HostingEnvironmentProfile != null) { certificate.HostingEnvironmentProfile = webapp.HostingEnvironmentProfile; } var certificateResourceGroup = CmdletHelpers.GetResourceGroupFromResourceId(webapp.ServerFarmId); try { WebsitesClient.CreateCertificate(certificateResourceGroup, certificateName, certificate); } catch (CloudException e) { // This exception is thrown when certificate already exists. Let's swallow it and continue. if (e.Response.StatusCode != HttpStatusCode.Conflict) { throw; } } thumbPrint = certificateDetails.Thumbprint; break; case ParameterSet2Name: case ParameterSet4Name: thumbPrint = Thumbprint; break; } WriteObject(CmdletHelpers.GetHostNameSslStatesFromSiteResponse( WebsitesClient.UpdateHostNameSslState( resourceGroupName, webAppName, slot, webapp.Location, Name, SslState.HasValue ? SslState.Value : Management.WebSites.Models.SslState.SniEnabled, thumbPrint), Name)); }
public override void ExecuteCmdlet() { if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName)) { var webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, SlotName)); SiteConfig siteConfig = webApp.SiteConfig; var accessRestrictionList = TargetScmSite ? siteConfig.ScmIpSecurityRestrictions : siteConfig.IpSecurityRestrictions; IpSecurityRestriction ipSecurityRestriction = null; IDictionary <string, IList <string> > httpHeader = null; if (HttpHeader != null) { httpHeader = ConvertHeaderHashtable(HttpHeader); } int intPriority = checked ((int)Priority); switch (ParameterSetName) { case IpAddressParameterSet: CheckDuplicateIPRestriction(IpAddress, accessRestrictionList); ipSecurityRestriction = new IpSecurityRestriction(IpAddress, null, null, null, null, Action, null, intPriority, Name, Description, httpHeader); accessRestrictionList.Add(ipSecurityRestriction); break; case ServiceTagParameterSet: CheckDuplicateIPRestriction(ServiceTag, accessRestrictionList); ipSecurityRestriction = new IpSecurityRestriction(ServiceTag, null, null, null, null, Action, "ServiceTag", intPriority, Name, Description, httpHeader); accessRestrictionList.Add(ipSecurityRestriction); break; case SubnetNameParameterSet: case SubnetIdParameterSet: var subnet = ParameterSetName == SubnetNameParameterSet ? SubnetName : SubnetId; //Fetch RG of given SubNet var subNetResourceGroupName = NetworkClient.GetSubnetResourceGroupName(subnet, VirtualNetworkName); //If unble to fetch SubNet rg from above step, use the input RG to get validation error from api call. subNetResourceGroupName = !String.IsNullOrEmpty(subNetResourceGroupName) ? subNetResourceGroupName : ResourceGroupName; var subnetResourceId = NetworkClient.ValidateSubnet(subnet, VirtualNetworkName, subNetResourceGroupName, DefaultContext.Subscription.Id); CheckDuplicateServiceEndpointRestriction(subnetResourceId, accessRestrictionList); if (!IgnoreMissingServiceEndpoint) { var subnetSubcriptionId = CmdletHelpers.GetSubscriptionIdFromResourceId(subnetResourceId); if (subnetSubcriptionId != DefaultContext.Subscription.Id) { throw new Exception("Service endpoint cannot be validated. Subnet is in another subscription. Use -IgnoreMissingServiceEndpoint and manually verify that 'Microsoft.Web' service endpoint is enabled on the subnet."); } var serviceEndpointServiceName = "Microsoft.Web"; var serviceEndpointLocations = new List <string>() { "*" }; NetworkClient.EnsureSubnetServiceEndpoint(subnetResourceId, serviceEndpointServiceName, serviceEndpointLocations); } ipSecurityRestriction = new IpSecurityRestriction(null, null, subnetResourceId, null, null, Action, null, intPriority, Name, Description, httpHeader); accessRestrictionList.Add(ipSecurityRestriction); break; } if (ShouldProcess(WebAppName, $"Adding Access Restriction Rule for Web App '{WebAppName}'")) { // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, webApp.Location, WebAppName, SlotName, siteConfig); if (PassThru) { // Refresh object to get the final state webApp = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, SlotName)); var accessRestrictionSettings = new PSAccessRestrictionConfig(ResourceGroupName, WebAppName, webApp.SiteConfig, SlotName); WriteObject(accessRestrictionSettings); } } } }