/// <summary>
 ///     Create a website
 /// </summary>
 /// <param name="name"></param>
 /// <param name="connectionStringInfo"></param>
 /// <returns></returns>
 public WebSite CreateWebSite(string name = "", WebSiteUpdateConfigurationParameters.ConnectionStringInfo connectionStringInfo = null)
 {
     return CreateWebSite(_webSpace, new WebSiteCreateParameters
     {
         Name = name
     }, connectionStringInfo);
 }
        /// <summary>
        ///     Create a website
        /// </summary>
        /// <param name="webSpaceName"></param>
        /// <param name="siteSettings"></param>
        /// <param name="connectionStringInfo"></param>
        /// <returns></returns>
        public WebSite CreateWebSite(string webSpaceName, WebSiteCreateParameters siteSettings,
            WebSiteUpdateConfigurationParameters.ConnectionStringInfo connectionStringInfo = null)
        {
            if (siteSettings == null)
            {
                throw new ArgumentNullException("siteSettings");
            }

            siteSettings.Name = string.IsNullOrEmpty(siteSettings.Name) 
                ? Dependencies.TestResourcesCollector.GetUniqueWebSiteName() 
                : siteSettings.Name.ToLowerInvariant();
            
            if (siteSettings.HostNames == null || siteSettings.HostNames.Count == 0)
            {
                siteSettings.HostNames = new [] {siteSettings.Name + Dependencies.Subscription.DefaultWebSitesDomainName };
            }

            if (string.IsNullOrEmpty(siteSettings.WebSpaceName))
            {
                siteSettings.WebSpaceName = webSpaceName;
            }

            TestEasyLog.Instance.Info(string.Format("Creating web site '{0}'", siteSettings.Name));

            var createWebsiteResult = WebSiteManagementClient.WebSites.CreateAsync(webSpaceName,
                siteSettings,
                new CancellationToken()).Result;

            var newSite = createWebsiteResult.WebSite;
            Dependencies.TestResourcesCollector.Remember(AzureResourceType.WebSite, newSite.Name, newSite);

            if(connectionStringInfo != null)
            {
                var existingConfig = CreateWebSiteUpdateParameters(newSite.Name);
                var existingConnectionStrings = existingConfig.ConnectionStrings;
                if(existingConnectionStrings.All(cs => cs.Name != connectionStringInfo.Name))
                {
                    existingConnectionStrings.Add(connectionStringInfo);
                    UpdateWebSiteConfig(webSpaceName, newSite.Name, existingConfig);
                }
            }

            return newSite;
        }
        internal static WebSiteUpdateConfigurationParameters ToUpdate(this WebSiteGetConfigurationResponse getConfigResponse)
        {
            var update = new WebSiteUpdateConfigurationParameters
            {
                DetailedErrorLoggingEnabled = getConfigResponse.DetailedErrorLoggingEnabled,
                HttpLoggingEnabled = getConfigResponse.HttpLoggingEnabled,
                NetFrameworkVersion = getConfigResponse.NetFrameworkVersion,
                NumberOfWorkers = getConfigResponse.NumberOfWorkers,
                PhpVersion = getConfigResponse.PhpVersion,
                PublishingPassword = getConfigResponse.PublishingPassword,
                PublishingUserName = getConfigResponse.PublishingUserName,
                RequestTracingEnabled = getConfigResponse.RequestTracingEnabled,
                RequestTracingExpirationTime = getConfigResponse.RequestTracingExpirationTime,
                ScmType = getConfigResponse.ScmType,
                Use32BitWorkerProcess = getConfigResponse.Use32BitWorkerProcess,
                ManagedPipelineMode = getConfigResponse.ManagedPipelineMode,
                WebSocketsEnabled = getConfigResponse.WebSocketsEnabled,
                RemoteDebuggingEnabled = getConfigResponse.RemoteDebuggingEnabled,
                RemoteDebuggingVersion = getConfigResponse.RemoteDebuggingVersion.GetValueOrDefault(),
            };

            getConfigResponse.AppSettings.ForEach(kvp => update.AppSettings.Add(kvp.Key, kvp.Value));
            getConfigResponse.ConnectionStrings.ForEach(cs => update.ConnectionStrings.Add(new WebSiteUpdateConfigurationParameters.ConnectionStringInfo
            {
                ConnectionString = cs.ConnectionString,
                Name = cs.Name,
                Type = cs.Type
            }));
            getConfigResponse.DefaultDocuments.ForEach(dd => update.DefaultDocuments.Add(dd));
            getConfigResponse.HandlerMappings.ForEach(hm => update.HandlerMappings.Add(new WebSiteUpdateConfigurationParameters.HandlerMapping
            {
                Arguments = hm.Arguments,
                Extension = hm.Extension,
                ScriptProcessor = hm.ScriptProcessor
            }));
            getConfigResponse.Metadata.ForEach(kvp => update.Metadata.Add(kvp.Key, kvp.Value));

            return update;
        }
 /// <summary>
 /// You can update the config settings for a web site by issuing an
 /// HTTP PUT with a request body containing the updated settings.
 /// (see http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.WebSites.IWebSiteOperations.
 /// </param>
 /// <param name='webSpaceName'>
 /// Required. The name of the web space.
 /// </param>
 /// <param name='webSiteName'>
 /// Required. The name of the web site.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the Update Configuration Web Site
 /// operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task<AzureOperationResponse> UpdateConfigurationAsync(this IWebSiteOperations operations, string webSpaceName, string webSiteName, WebSiteUpdateConfigurationParameters parameters)
 {
     return operations.UpdateConfigurationAsync(webSpaceName, webSiteName, parameters, CancellationToken.None);
 }
 /// <summary>
 /// You can update the config settings for a web site by issuing an
 /// HTTP PUT with a request body containing the updated settings.
 /// (see http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.WebSites.IWebSiteOperations.
 /// </param>
 /// <param name='webSpaceName'>
 /// Required. The name of the web space.
 /// </param>
 /// <param name='webSiteName'>
 /// Required. The name of the web site.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the Update Configuration Web Site
 /// operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static AzureOperationResponse UpdateConfiguration(this IWebSiteOperations operations, string webSpaceName, string webSiteName, WebSiteUpdateConfigurationParameters parameters)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IWebSiteOperations)s).UpdateConfigurationAsync(webSpaceName, webSiteName, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 ///     Update website configuration
 /// </summary>
 /// <param name="webSpaceName"></param>
 /// <param name="siteName"></param>
 /// <param name="updateConfigParams"></param>
 public void UpdateWebSiteConfig(string webSpaceName, string siteName, WebSiteUpdateConfigurationParameters updateConfigParams)
 {
     TestEasyLog.Instance.Info(string.Format("Updating web site config '{0}'", siteName));
     WebSiteManagementClient.WebSites.UpdateConfigurationAsync(webSpaceName, siteName, updateConfigParams, new CancellationToken()).Wait();
 }
 /// <summary>
 ///     Update web site configuration
 /// </summary>
 /// <param name="siteName"></param>
 /// <param name="updateConfigParams"></param>
 public void UpdateWebSiteConfig(string siteName, WebSiteUpdateConfigurationParameters updateConfigParams)
 {
     UpdateWebSiteConfig(_webSpace, siteName, updateConfigParams);
 }
        public void UpdateSiteConfig()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
            var client = GetWebSiteManagementClient(handler);

            string expectedClientId = Guid.NewGuid().ToString();
            string expectedIssuer = "https://sts.microsoft.net/" + Guid.NewGuid() + "/";

            var expectedLimits = new WebSiteUpdateConfigurationParameters.SiteLimits()
            {
                MaxDiskSizeInMb = 1024,
                MaxMemoryInMb = 512,
                MaxPercentageCpu = 70.5
            };

            var parameters = new WebSiteUpdateConfigurationParameters
            {
                SiteAuthEnabled = true,
                SiteAuthSettings = new SiteAuthSettings
                {
                    AADClientId = expectedClientId,
                    OpenIdIssuer = expectedIssuer,
                },
                Limits = expectedLimits 
            };

            // Simulate a PUT request to update the config
            client.WebSites.UpdateConfiguration("webspace", "website", parameters);

            // Check the payload of the previous request to see if it matches our expectations
            Assert.Equal(handler.Method, HttpMethod.Put);
            Assert.NotEmpty(handler.Request);
            JObject requestJson = JObject.Parse(handler.Request);

            JToken token;
            Assert.True(requestJson.TryGetValue("SiteAuthEnabled", out token));
            Assert.Equal(JTokenType.Boolean, token.Type);
            Assert.True(token.Value<bool>());

            Assert.True(requestJson.TryGetValue("SiteAuthSettings", out token));
            Assert.Equal(JTokenType.Object, token.Type);

            JObject siteAuthSettingsJson = (JObject)token;
            Assert.True(siteAuthSettingsJson.TryGetValue("AADClientId", out token));
            Assert.Equal(JTokenType.String, token.Type);
            Assert.Equal(expectedClientId, token.Value<string>());

            Assert.True(siteAuthSettingsJson.TryGetValue("OpenIdIssuer", out token));
            Assert.Equal(JTokenType.String, token.Type);
            Assert.Equal(expectedIssuer, token.Value<string>());

            Assert.True(requestJson.TryGetValue("limits", out token));
            Assert.Equal(JTokenType.Object, token.Type);
            JObject limitsJson = (JObject)token;

            Assert.True(limitsJson.TryGetValue("maxDiskSizeInMb", out token));
            Assert.Equal(JTokenType.Integer, token.Type);
            Assert.Equal(expectedLimits.MaxDiskSizeInMb, token.Value<long>());

            Assert.True(limitsJson.TryGetValue("maxMemoryInMb", out token));
            Assert.Equal(JTokenType.Integer, token.Type);
            Assert.Equal(expectedLimits.MaxMemoryInMb, token.Value<long>());

            Assert.True(limitsJson.TryGetValue("maxPercentageCpu", out token));
            Assert.Equal(JTokenType.Float, token.Type);
            Assert.Equal(expectedLimits.MaxPercentageCpu, token.Value<double>());
        }
        internal static WebSiteUpdateConfigurationParameters ToConfigUpdateParameters(this Utilities.SiteConfig config)
        {
            var parameters = new WebSiteUpdateConfigurationParameters
            {
                DetailedErrorLoggingEnabled = config.DetailedErrorLoggingEnabled,
                HttpLoggingEnabled = config.HttpLoggingEnabled,
                NetFrameworkVersion = config.NetFrameworkVersion,
                NumberOfWorkers = config.NumberOfWorkers,
                PhpVersion = config.PhpVersion,
                PublishingPassword = config.PublishingPassword,
                PublishingUserName = config.PublishingUsername,
                RequestTracingEnabled = config.RequestTracingEnabled,
                ManagedPipelineMode = config.ManagedPipelineMode,
                WebSocketsEnabled = config.WebSocketsEnabled,
                RemoteDebuggingEnabled = config.RemoteDebuggingEnabled,
                RemoteDebuggingVersion = config.RemoteDebuggingVersion,
                RoutingRules = config.RoutingRules.Select(r => r.ToRoutingRule()).ToArray(),
                Use32BitWorkerProcess = config.Use32BitWorkerProcess,
            };
            if (config.AppSettings != null)
                config.AppSettings.ForEach(nvp => parameters.AppSettings.Add(ToKeyValuePair(nvp)));

            if (config.ConnectionStrings != null)
                config.ConnectionStrings.ForEach(
                csi => parameters.ConnectionStrings.Add(new WebSiteUpdateConfigurationParameters.ConnectionStringInfo
                {
                    Name = csi.Name,
                    ConnectionString = csi.ConnectionString,
                    Type = (Management.WebSites.Models.ConnectionStringType)Enum.Parse(typeof(Management.WebSites.Models.ConnectionStringType), csi.Type.ToString(), ignoreCase: true)
                }));

            if (config.DefaultDocuments != null)
                config.DefaultDocuments.ForEach(d => parameters.DefaultDocuments.Add(d));

            if (config.HandlerMappings != null)
                config.HandlerMappings.ForEach(
                hm => parameters.HandlerMappings.Add(new WebSiteUpdateConfigurationParameters.HandlerMapping
                {
                    Arguments = hm.Arguments,
                    Extension = hm.Extension,
                    ScriptProcessor = hm.ScriptProcessor
                }));

            if (config.Metadata != null)
                config.Metadata.ForEach(nvp => parameters.Metadata.Add(ToKeyValuePair(nvp)));

            return parameters;
        }
 /// <summary>
 /// You can retrieve the config settings for a web site by issuing an
 /// HTTP GET request, or update them by using HTTP PUT with a request
 /// body that contains the settings to be updated.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.WebSites.IWebSiteOperations.
 /// </param>
 /// <param name='webSpaceName'>
 /// The name of the web space.
 /// </param>
 /// <param name='webSiteName'>
 /// The name of the web site.
 /// </param>
 /// <param name='parameters'>
 /// The Update Web Site Configuration parameters.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static OperationResponse UpdateConfiguration(this IWebSiteOperations operations, string webSpaceName, string webSiteName, WebSiteUpdateConfigurationParameters parameters)
 {
     try
     {
         return operations.UpdateConfigurationAsync(webSpaceName, webSiteName, parameters).Result;
     }
     catch (AggregateException ex)
     {
         if (ex.InnerExceptions.Count > 1)
         {
             throw;
         }
         else
         {
             throw ex.InnerException;
         }
     }
 }