The website structure containing details oof the underlying website
 /// <summary>
 /// Constructs a websites list command
 /// </summary>
 internal CreateHDInsightCluster(Website website)
 {
     HttpVerb = HttpVerbGet;
     ServiceType = "services";
     OperationId = "webspaces";
     HttpVerb = HttpVerbPost;
     // keep this in to ensure no 403
 }
 /// <summary>
 /// Constructs a websites list command
 /// </summary>
 internal WebsiteChangeStateCommand(Website site, WebsiteState state)
 {
     HttpVerb = HttpVerbPut;
     ServiceType = "services";
     OperationId = "webspaces";
     // keep this in to ensure no 403
     HttpCommand = String.Format("{0}/sites/{1}", site.Webspace, site.Name);
     Site = site;
     State = state;
 }
 /// <summary>
 /// Constructs a websites list command
 /// </summary>
 internal CreateWebsiteRepositoryCommand(Website website, string uri = null)
 {
     HttpVerb = HttpVerbGet;
     ServiceType = "services";
     OperationId = "webspaces";
     Website = website;
     HttpVerb = HttpVerbPost;
     // keep this in to ensure no 403
     HttpCommand = String.Format("{0}/sites/{1}/repository", Website.Webspace, Website.Name);
     /* propertiesToInclude=repositoryuri%2Cpublishingpassword%2Cpublishingusername */
 }
 /// <summary>
 /// Constructs a websites list command
 /// </summary>
 /// // https://management.core.windows.net/67b7c755-8382-4990-b612-0006cd24e1ba/services/webspaces/northeuropewebspace/serverfarms/DefaultServerFarm
 /// // <ServerFarm xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><CurrentNumberOfWorkers>2</CurrentNumberOfWorkers><CurrentWorkerSize>Small</CurrentWorkerSize><Name>DefaultServerFarm</Name><NumberOfWorkers>2</NumberOfWorkers><Status>Ready</Status><WorkerSize>Small</WorkerSize></ServerFarm>
 internal CreateWebsiteServerFarmCommand(Website website)
 {
     HttpVerb = HttpVerbGet;
     ServiceType = "services";
     OperationId = "webspaces";
     Website = website;
     HttpVerb = HttpVerbPost;
     // keep this in to ensure no 403
     HttpCommand = String.Format("{0}/serverfarms/", Website.Webspace);
     /* propertiesToInclude=repositoryuri%2Cpublishingpassword%2Cpublishingusername */
 }
 /// <summary>
 /// Constructs a websites list command
 /// </summary>
 internal UpdateWebsiteConfigCommand(Website website)
 {
     HttpVerb = HttpVerbGet;
     ServiceType = "services";
     OperationId = "webspaces";
     Website = website;
     HttpVerb = HttpVerbPut;
     AdditionalHeaders["Accept-Encoding"] = "gzip, deflate";
     // keep this in to ensure no 403
     HttpCommand = String.Format("{0}/sites/{1}/config", Website.Webspace, Website.Name);
     /* propertiesToInclude=repositoryuri%2Cpublishingpassword%2Cpublishingusername */
 }
        /// <summary>
        /// Constructs a websites list command
        /// </summary>
        /*
         * GET
         * https://management.core.windows.net:8443/<Subscription-Id>/services/WebSpaces/<WebSpaceName>/sites/<SiteName>/metrics?names=<MetricName>,<MetricName>[...],&StartTime=<2013-01-15T00:00:00>&EndTime=<2013-01-16T12:00:00>
         */
        internal GetWebsiteMetricsCommand(Website website, DateTime startTime, DateTime endTime)
        {
            HttpVerb = HttpVerbGet;
            ServiceType = "services";
            OperationId = "webspaces";
            Website = website;
            HttpVerb = HttpVerbGet;
            IsManagement = true;

            string startTimeText = startTime.ToString(@"yyyy-MM-ddTHH:mm");
            string endTimeText = endTime.ToString(@"yyyy-MM-ddTHH:mm");

            HttpCommand = String.Format("{0}/sites/{1}/metrics?StartTime={2}&EndTime={3}", Website.Webspace, Website.Name, startTimeText, endTimeText);
        }
        public void Execute()
        {
            var site = new Website()
                           {
                               ComputeMode = ComputeMode.Dedicated,
                               Name = "fluentwebtest38",
                               WebsiteParameters = new WebsiteParameters()
                                                       {
                                                           CurrentNumberOfWorkers = 1
                                                       }
                           };
            site.Config.AppSettings.Add("test1", "test2");
            site.Config.HttpLoggingEnabled = true;
            site.Config.RequestTracingEnabled = true;
            site.Config.DetailedErrorLoggingEnabled = true;
            site.Config.ConnectionStrings.Add(new ConnStringInfo(){Name="test", ConnectionString = "test", Type="SQLAzure"});
            System.Console.WriteLine("Creating website");
            System.Console.WriteLine("================");

            var client = new WebsiteClient(_subscriptionId, _certificate);
            client.CreateFromGithub(site, new GitDetails() { Username = "******", Password = "******", RepositoryName = "test-sample-for-azure-deployments" });
        }
        internal override void Parse()
        {
            if (Websites == null)
                Websites = new List<Website>();

            XNamespace serialisationNamespace = SerialisationNamespace;
            XElement rootElements = Document.Element(GetSchema() + RootElement);
            foreach (var element in rootElements.Elements(GetSchema() + "Site"))
            {
                var site = new Website() {Hostname = new List<string>()};
                // get the compute modefrom the instance
                if (element.Element(GetSchema() + "ComputeMode") != null)
                {
                    site.ComputeMode = (ComputeMode)Enum.Parse(typeof(ComputeMode), element.Element(GetSchema() + "ComputeMode").Value, true);
                }
                // get the name of the site as in xxxx.azurewebsites.net
                if (element.Element(GetSchema() + "Name") != null)
                {
                    site.Name = element.Element(GetSchema() + "Name").Value;
                }
                // test to see whether the sitehas been enabled
                if (element.Element(GetSchema() + "Enabled") != null)
                {
                    site.Enabled = bool.Parse(element.Element(GetSchema() + "Enabled").Value);
                }
                // get the underlying webspace that this site is in
                if (element.Element(GetSchema() + "WebSpace") != null)
                {
                    site.Webspace = element.Element(GetSchema() + "WebSpace").Value;
                }
                // get the usage of this website
                if (element.Element(GetSchema() + "UsageState") != null)
                {
                    site.Usage = (WebsiteUsage)Enum.Parse(typeof(WebsiteUsage), element.Element(GetSchema() + "UsageState").Value, true);
                }
                // get the state of the website
                if (element.Element(GetSchema() + "State") != null)
                {
                    site.State = (WebsiteState)Enum.Parse(typeof(WebsiteState), element.Element(GetSchema() + "State").Value, true);
                }
                // get the hostnames using the serialisation namespace
                // EnabledHostNames [ xmlns:a= ]
                if (element.Element(GetSchema() + "EnabledHostNames") != null)
                {
                    foreach (var hostNameElement in element.Element(GetSchema() + "EnabledHostNames").
                        Elements(serialisationNamespace + "string"))
                    {
                        site.Hostname.Add(hostNameElement.Value);
                    }
                }
                // get the state of the website
                if (element.Element(GetSchema() + "SiteMode") != null)
                {
                    site.Mode = (SiteMode)Enum.Parse(typeof(SiteMode), element.Element(GetSchema() + "SiteMode").Value, true);
                }

                // get the state of the website
                if (element.Element(GetSchema() + "ComputeMode") != null)
                {
                    site.ComputeMode = (ComputeMode)Enum.Parse(typeof(ComputeMode), element.Element(GetSchema() + "ComputeMode").Value);
                }
                Websites.Add(site);
            }

            CommandResponse = Websites;
        }
        private void SetScalePotential(Website website)
        {
            // if the type hasn't been defined then set the default to free
            switch (website.ComputeMode)
            {
                case ComputeMode.Free:
                    website.ComputeMode = ComputeMode.Shared;
                    website.Mode = SiteMode.Limited;
                    break;
                case ComputeMode.Shared:
                    website.ComputeMode = ComputeMode.Shared;
                    website.Mode = SiteMode.Basic;
                    break;
                case ComputeMode.Dedicated:
                    {
                        website.ComputeMode = ComputeMode.Dedicated;
                        website.Mode = SiteMode.Basic;
                        // TODO: Create the default server farm here and add to config
                        try
                        {
                            // check to see whether this has been set or not
                            if (website.ServerFarm == null)
                            {
                                website.ServerFarm = new ServerFarm() {Name = "DefaultServerFarm"};
                            }
                            // then use this to get or create the server farm
                            var command = new GetServerFarmCommand(website)
                                {
                                    SubscriptionId = SubscriptionId,
                                    Certificate = ManagementCertificate
                                };
                            command.Execute();
                            WebsiteProperties = command.Website;
                        }
                        catch (Exception)
                        {
                            // if we get the exception here then this will most likely be a 404 - for the time being treat it as such ...
                            try
                            {
                                var command = new CreateWebsiteServerFarmCommand(website)
                                {
                                    SubscriptionId = SubscriptionId,
                                    Certificate = ManagementCertificate
                                };
                                command.Execute();
                            }
                            catch (Exception)
                            {
                                // if this fails we want to halt
                                throw new FluentManagementException(
                                    "Subscription does not support a dedicated server farm", "WebsiteClient");
                            }

                        }
                        break;
                    }
            }
        }
        /// <summary>
        /// Creates a website given github credentials
        /// </summary>
        /// <param name="website"></param>
        /// <param name="gitDetails">the details of the github repo</param>
        public void CreateFromGithub(Website website, GitDetails gitDetails)
        {
            // create the new website
            Create(website);

            // we have the new website properties
            var githubClient = new GithubClient(new WebsiteRequestHelper())
                                   {
                                       Username = gitDetails.Username,
                                       Password = gitDetails.Password,
                                   };
            var repoList = githubClient.GetRepositories();
            if(!repoList.ContainsKey(gitDetails.RepositoryName))
                throw new FluentManagementException("git repository not found", "WebsiteClient");
            // add the service hook in place
            string setServiceHook = githubClient.SetServiceHook(WebsiteProperties.Config.PublishingUsername,
                                        WebsiteProperties.Config.PublishingPassword, website.Name + ".scm.azurewebsites.net",
                                        repoList[gitDetails.RepositoryName], gitDetails.RepositoryName);

            // get all of the auth token values
            githubClient.GetOAuthToken(repoList[gitDetails.RepositoryName], gitDetails.RepositoryName);
            // add the metadata from the service hook
            WebsiteProperties.Config.Metadata.Add("ScmUri", githubClient.ScmUri);
            WebsiteProperties.Config.Metadata.Add("CloneUri", githubClient.CloneUri);
            WebsiteProperties.Config.Metadata.Add("RepoApiUri", githubClient.RepoApiUri);
            WebsiteProperties.Config.Metadata.Add("OAuthToken", githubClient.OAuthToken);
            WebsiteProperties.Config.ScmType = ScmType.GitHub;
            // update windows azure
            Update();
            // call the service hook
            //githubClient.TestServiceHook(setServiceHook);
            if (!String.IsNullOrEmpty(setServiceHook)) return;
            Delete();
            throw new FluentManagementException(
                "website created but unable to set service hook in github rolled back deployment", "WebsiteClient");
        }
 /// <summary>
 /// As above but using BitBucket instead
 /// </summary>
 public void CreateFromBitBucket(Website website, GitDetails gitDetails)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Creates a default website with nothing deployed
        /// </summary>
        /// <param name="website">the website which will be created</param>
        /// <param name="scm"></param>
        public void Create(Website website, ScmType scm = ScmType.LocalGit)
        {
            website.WebsiteParameters.CurrentNumberOfWorkers = website.WebsiteParameters.CurrentNumberOfWorkers != 0 ?
                website.WebsiteParameters.CurrentNumberOfWorkers : 1;

            website.Enabled = true;
            website.State = WebsiteState.Ready;
            website.Webspace = website.Webspace ?? WebspaceLocationConstants.NorthEuropeWebSpace;
            if (!String.IsNullOrEmpty(website.Webspace))
            {
                ValidateWebSpace(website.Webspace);
            }
            SetScalePotential(website);
            // check to see whether this is dedicate first
               // if((website.ServerFarm != null && website.ServerFarm.InstanceCount))

            // create the website
            var command = new CreateWebsiteCommand(website)
                              {
                                  SubscriptionId = SubscriptionId,
                                  Certificate = ManagementCertificate
                              };
            command.Execute();
            // create the website repo
            // do this only if local git is selected
            var repoCommand = new CreateWebsiteRepositoryCommand(website)
                                    {
                                        SubscriptionId = SubscriptionId,
                                        Certificate = ManagementCertificate
                                    };
            repoCommand.Execute();
            WebsiteProperties = website;

            // TODO: fix this value in code!!!!
            website.WebsiteParameters.NumberOfWorkers = website.WebsiteParameters.NumberOfWorkers == 0
                                                            ? website.WebsiteParameters.CurrentNumberOfWorkers
                                                            : website.WebsiteParameters.NumberOfWorkers;
            WebsiteProperties = GetWebsiteIfExists();

            var command2 = new UpdateWebsiteConfigCommand(WebsiteProperties)
            {
                SubscriptionId = SubscriptionId,
                Certificate = ManagementCertificate
            };
            command2.Execute();
            WebsiteProperties = GetWebsiteIfExists();
        }