private string UploadTo(IWebApp webApp, string toResourceGroup)
        {
            string filename = AppSettings.Certificate.Keys.Pfx;
            string password = AppSettings.Certificate.Keys.Password;

            var x509       = new X509Certificate2(filename, password);
            var thumbprint = x509.Thumbprint;
            var allBytes   = System.IO.File.ReadAllBytes(filename);
            var group      = String.IsNullOrEmpty(toResourceGroup) ? webApp.ResourceGroupName : toResourceGroup;

            var appServiceCertificate = _azure.AppServices
                                        .AppServiceCertificates
                                        .ListByResourceGroup(group)
                                        .FirstOrDefault(i => i.Thumbprint == thumbprint);

            // If not existing
            if (appServiceCertificate == null)
            {
                appServiceCertificate = _azure.AppServices
                                        .AppServiceCertificates
                                        .Define(thumbprint)
                                        .WithRegion(webApp.Region)
                                        .WithExistingResourceGroup(group)
                                        .WithPfxByteArray(allBytes)
                                        .WithPfxPassword(password)
                                        .Create();
            }

            return(thumbprint);
        }
        private void Initialize(IWebApp webApp)
        {
            Console.WriteLine("---PAPERS---");
            try
            {
                var factory = new PaperDescriptorFactory(webApp);
                var types   = ExposedTypes.GetTypes <IPaper>().Distinct();
                foreach (var type in types)
                {
                    try
                    {
                        var descriptor = factory.CreatePaperDescriptor(type);
                        var id         = $"{descriptor.Catalog}/{descriptor.Paper}";
                        descriptorMap[id] = descriptor;

                        Console.WriteLine($"/Paper/Api/Catalogs/{descriptor.Catalog}/Papers/{descriptor.Paper}");
                    }
                    catch (Exception ex)
                    {
                        ex.Trace();
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Trace();
            }
            finally
            {
                Console.WriteLine("------");
            }
        }
        public static async Task Deploy(this IWebApp site, WebAppDeploymentKind kind, DirectoryInfo from, TestCommand dotnet, ILogger logger)
        {
            switch (kind)
            {
            case WebAppDeploymentKind.Git:
                await site.GitDeploy(from, logger);

                break;

            case WebAppDeploymentKind.WebDeploy:
                await site.BuildPublishProfileAsync(from.FullName);

                await dotnet.ExecuteAndAssertAsync("publish /p:PublishProfile=Profile");

                break;

            case WebAppDeploymentKind.Ftp:
                var publishDirectory = from.CreateSubdirectory("publish");
                await dotnet.ExecuteAndAssertAsync("restore");

                await dotnet.ExecuteAndAssertAsync("publish -o " + publishDirectory.FullName);

                await site.UploadFilesAsync(publishDirectory, "/", await site.GetPublishingProfileAsync(), logger);

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(kind), kind, null);
            }
        }
        public static async Task BuildPublishProfileAsync(this IWebApp site, string projectDirectory)
        {
            var result = await site.Manager.WebApps.Inner.ListPublishingProfileXmlWithSecretsAsync(
                site.ResourceGroupName,
                site.Name,
                new CsmPublishingProfileOptionsInner());

            var targetDirectory = Path.Combine(projectDirectory, "Properties", "PublishProfiles");

            Directory.CreateDirectory(targetDirectory);

            var publishSettings = XDocument.Load(result);

            foreach (var profile in publishSettings.Root.Elements("publishProfile"))
            {
                if ((string)profile.Attribute("publishMethod") == "MSDeploy")
                {
                    new XDocument(
                        new XElement("Project",
                                     new XElement("PropertyGroup",
                                                  new XElement("WebPublishMethod", "MSDeploy"),
                                                  new XElement("PublishProvider", "AzureWebSite"),
                                                  new XElement("UserName", (string)profile.Attribute("userName")),
                                                  new XElement("Password", (string)profile.Attribute("userPWD")),
                                                  new XElement("MSDeployServiceURL", (string)profile.Attribute("publishUrl")),
                                                  new XElement("DeployIisAppPath", (string)profile.Attribute("msdeploySite"))
                                                  )))
                    .Save(Path.Combine(targetDirectory, "Profile.pubxml"));
                }
            }
        }
        public static async Task UploadFilesAsync(this IWebApp site, DirectoryInfo from, string to, IPublishingProfile publishingProfile, ILogger logger)
        {
            foreach (var info in from.GetFileSystemInfos("*"))
            {
                var address = new Uri(
                    "ftp://" + publishingProfile.FtpUrl + to + info.FullName.Substring(from.FullName.Length + 1).Replace('\\', '/'));

                if (info is FileInfo file)
                {
                    logger.LogInformation($"Uploading {file.FullName} to {address}");

                    var request = CreateRequest(publishingProfile, address, WebRequestMethods.Ftp.UploadFile);
                    using (var fileStream = File.OpenRead(file.FullName))
                    {
                        using (var requestStream = await request.GetRequestStreamAsync())
                        {
                            await fileStream.CopyToAsync(requestStream);
                        }
                    }
                    await request.GetResponseAsync();
                }
                if (info is DirectoryInfo directory)
                {
                    var request = CreateRequest(publishingProfile, address, WebRequestMethods.Ftp.MakeDirectory);
                    await request.GetResponseAsync();
                    await UploadFilesAsync(site, directory, to + directory.Name + '/', publishingProfile, logger);
                }
            }
        }
        public static async Task GitDeploy(this IWebApp site, DirectoryInfo workingDirectory, ILogger logger)
        {
            // Allow site to restart after site extension installation
            await Task.Delay(GitDeployDelay);

            var git = new TestCommand("git")
            {
                Logger           = logger,
                WorkingDirectory = workingDirectory.FullName
            };

            var publishingProfile = await site.GetPublishingProfileAsync();

            await git.ExecuteAndAssertAsync("init");

            await git.ExecuteAndAssertAsync($"remote add origin https://{publishingProfile.GitUsername}:{publishingProfile.GitPassword}@{publishingProfile.GitUrl}");

            await git.ExecuteAndAssertAsync("add .");

            await git.ExecuteAndAssertAsync("commit -am Initial");

            var result = await git.ExecuteAndAssertAsync("push origin master");

            Assert.DoesNotContain("An error has occurred during web site deployment", result.StdErr);
            Assert.DoesNotContain("deployment to website failed", result.StdErr);
        }
        public static HttpClient CreateClient(this IWebApp site)
        {
            var domain = site.GetHostNameBindings().First().Key;

            return(new HttpClient {
                BaseAddress = new Uri("http://" + domain), Timeout = HttpClientTimeout
            });
        }
Example #8
0
 public void AddApp(string name, IWebApp app)
 {
     apps.Add(name, new AppStartup()
     {
         ConfigureServices = app.ConfigureServices,
         Configure         = app.Configure
     });
 }
 private void DefineSslBindingFor(IWebApp webApp, string thumbprint, string forHostname)
 {
     webApp.Update()
     .DefineSslBinding()
     .ForHostname(forHostname)
     .WithExistingCertificate(thumbprint)
     .WithSniBasedSsl()
     .Attach()
     .Apply();
 }
 public static void StopStart(IWebApp app)
 {
     WriteSection("Applying a possible stop/start fix");
     Log("Stopping Web App");
     app.Stop();
     LetsWaitALittle();
     Log("Starting Web App");
     app.Start();
     LetsWaitALittle();
 }
Example #11
0
        static async Task <(IAzure azure, IResourceGroup resourceGroup, IWebApp webApp)> SetUpAzureWebApp()
        {
            var resourceGroupName = SdkContext.RandomResourceName(nameof(AzureWebAppHealthCheckActionHandlerFixtures), 60);
            var clientId          = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId);
            var clientSecret      = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword);
            var tenantId          = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId);
            var subscriptionId    = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId);

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId,
                                                                                      clientSecret,
                                                                                      tenantId,
                                                                                      AzureEnvironment.AzureGlobalCloud);

            var azure = Microsoft.Azure.Management.Fluent.Azure
                        .Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(credentials)
                        .WithSubscription(subscriptionId);

            IResourceGroup resourceGroup = null;
            IWebApp        webApp        = null;

            try
            {
                resourceGroup = await azure.ResourceGroups
                                .Define(resourceGroupName)
                                .WithRegion(Region.USWest)
                                .CreateAsync();

                var appServicePlan = await azure.AppServices.AppServicePlans
                                     .Define(SdkContext.RandomResourceName(nameof(AzureWebAppHealthCheckActionHandlerFixtures), 60))
                                     .WithRegion(resourceGroup.Region)
                                     .WithExistingResourceGroup(resourceGroup)
                                     .WithPricingTier(PricingTier.BasicB1)
                                     .WithOperatingSystem(OperatingSystem.Windows)
                                     .CreateAsync();

                var webAppName = SdkContext.RandomResourceName(nameof(AzureWebAppHealthCheckActionHandlerFixtures), 60);
                webApp = await azure.WebApps
                         .Define(webAppName)
                         .WithExistingWindowsPlan(appServicePlan)
                         .WithExistingResourceGroup(resourceGroup)
                         .WithRuntimeStack(WebAppRuntimeStack.NETCore)
                         .CreateAsync();

                return(azure, resourceGroup, webApp);
            }
            catch
            {
                // When errors encountered in set up, we return the resources that have been set up so far anyway
                // We will clean the resources from the caller
                return(azure, resourceGroup, webApp);
            }
        }
Example #12
0
    protected async Task <IPublishingProfile> GetTargetPublishingProfileAsync(IWebApp app)
    {
        var targetSlot = await FindTargetSlotAndCleanOldSlotsAsync(app);

        if (targetSlot != null)
        {
            Console.WriteLine($"Retrieving publishing profile of slot {targetSlot.Name}.");
            return(await targetSlot.GetPublishingProfileAsync());
        }

        Console.WriteLine($"Retrieving publishing profile of slot production.");
        return(await app.GetPublishingProfileAsync());
    }
Example #13
0
        public IDeploymentSlot CreateSlot(IWebApp webApp, string slotName)
        {
            _logger.LogDebug("Creating a slot " + slotName);

            var slot = ExecuteWithRetry(() => webApp.DeploymentSlots
                                        .Define(slotName)
                                        .WithConfigurationFromParent()
                                        .Create());

            _logger.LogDebug("Created slot " + slot.Name);

            return(slot);
        }
        private static IDeploymentSlot CreateSlot(IAzure azure, String slotName, IWebApp app)
        {
            Utilities.Log("Creating a slot " + slotName + " with auto swap turned on...");

            var slot = app.DeploymentSlots
                       .Define(slotName)
                       .WithConfigurationFromParent()
                       .WithAutoSwapSlotName("production")
                       .Create();

            Utilities.Log("Created slot " + slot.Name);
            Utilities.Print(slot);
            return(slot);
        }
Example #15
0
        private async Task RunCleanupAsync(IWebApp app, IDeploymentSlot slot)
        {
            Console.WriteLine($"Will delete temporary slot {slot.Name} in 2 minutes...");

            await Task.Delay(TimeSpan.FromMinutes(2));

            Console.WriteLine($"Deleting temporary slot {slot.Name}...");

            try
            {
                await app.DeploymentSlots.DeleteByIdAsync(slot.Id);
            }
            catch (CloudException e) when(e.Body.Code == "Conflict")
            {
            }
        }
Example #16
0
    private async Task <IDeploymentSlot> CreateNewTempSlotAsync(IWebApp app)
    {
        var slotName = SlotNamePrefix + Options.TargetSlot + "-" + Guid.NewGuid().ToString().Substring(0, 8);

        Console.WriteLine($"Creating temporary slot {slotName}.");

        var request = app.DeploymentSlots.Define(slotName)
                      .WithConfigurationFromParent()
                      .WithAutoSwapSlotName(Options.TargetSlot);

        if (Options.StopWebjobs)
        {
            request.WithStickyAppSetting("WEBJOBS_STOPPED", "1");
        }

        return(await request.CreateAsync());
    }
Example #17
0
        public IWebApp GetWebsite(string subscriptionId, string resourceGroupName, string name)
        {
            IWebApp webApp = null;

            try
            {
                webApp = ExecuteWithRetry(() => _authenticatedAzure.WithSubscription(subscriptionId).WebApps.GetByResourceGroup(resourceGroupName, name));
            }
            catch (CloudException cex)
            {
                if (cex.Body.Code != "ResourceNotFound")
                {
                    throw;
                }
            }

            return(webApp);
        }
Example #18
0
        public IDeploymentSlot GetSlot(IWebApp webApp, string name)
        {
            IDeploymentSlot slot = null;

            try
            {
                slot = ExecuteWithRetry(() => webApp.DeploymentSlots.GetByName(name));
            }
            catch (CloudException cex)
            {
                if (cex.Body.Code != "ResourceNotFound")
                {
                    throw;
                }
            }

            return(slot);
        }
        public static void RunQuickFix(IAzure azure, string rg, string app)
        {
            IWebApp app1 = azure.WebApps
                           .GetByResourceGroup(rg, app);

            IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);

            WriteSection("APP SERVICE INFO");
            Log("Web App: " + app1.Name);
            Log("App Service Plan: " + plan.Name);
            Log("App Service Plan Tier: " + plan.PricingTier.ToString());

            StopStart(app1);
            ScaleUpDown(plan);

            WriteSection("QUICK FIX COMPLETED! CHECK SITE\n" +
                         "https://" + app1.Name + ".azurewebsites.net/");
        }
Example #20
0
        private async Task <IDeploymentSlot> FindOrCreateSlot(IWebApp client, TargetSite site)
        {
            Log.Verbose($"Checking if slot {site.Slot} exists");

            var slot = await client.DeploymentSlots.GetByNameAsync(site.Slot);

            if (slot != null)
            {
                Log.Verbose($"Found existing slot {site.Slot}");
                return(slot);
            }

            Log.Verbose($"Slot {site.Slot} not found");
            Log.Info($"Creating slot {site.Slot}");
            return(await client.DeploymentSlots
                   .Define(site.Slot)
                   .WithConfigurationFromParent()
                   .CreateAsync());
        }
        public void CreateDeploymentSlot(IWebApp webapp, string slotname)
        {
            if (webapp == null)
            {
                throw new ArgumentNullException(nameof(webapp));
            }
            if (slotname == null)
            {
                throw new ArgumentNullException(nameof(slotname));
            }

            Logger.Info("Deployment Slot - Creating");

            webapp.DeploymentSlots.Define(slotname)
            .WithConfigurationFromWebApp(webapp)
            .WithClientAffinityEnabled(false)
            .Create();

            Logger.Info("Deployment Slot - Created");
        }
Example #22
0
        private async ValueTask ProvisionAsync(
            string projectName,
            CloudAction cloudAction)
        {
            List <string> environments = RetrieveEnvironments(cloudAction);

            foreach (string environmentName in environments)
            {
                IResourceGroup resourceGroup = await this.cloudManagementService
                                               .ProvisionResourceGroupAsync(
                    projectName,
                    environmentName);

                IAppServicePlan appServicePlan = await this.cloudManagementService
                                                 .ProvisionPlanAsync(
                    projectName,
                    environmentName,
                    resourceGroup);

                ISqlServer sqlServer = await this.cloudManagementService
                                       .ProvisionSqlServerAsync(
                    projectName,
                    environmentName,
                    resourceGroup);

                SqlDatabase sqlDatabase = await this.cloudManagementService
                                          .ProvisionSqlDatabaseAsync(
                    projectName,
                    environmentName,
                    sqlServer);

                IWebApp webApp = await this.cloudManagementService
                                 .ProvisionWebAppAsync(
                    projectName,
                    environmentName,
                    sqlDatabase.ConnectionString,
                    resourceGroup,
                    appServicePlan);
            }
        }
        public async ValueTask <IWebApp> ProvisionWebAppAsync(
            string projectName,
            string environment,
            string databaseConnectionString,
            IResourceGroup resourceGroup,
            IAppServicePlan appServicePlan)
        {
            string webAppName = $"{projectName}-{environment}".ToLower();

            this.loggingBroker.LogActivity(message: $"Provisioning {webAppName}");

            IWebApp webApp =
                await this.cloudBroker.CreateWebAppAsync(
                    webAppName,
                    databaseConnectionString,
                    appServicePlan,
                    resourceGroup);

            this.loggingBroker.LogActivity(message: $"{webAppName} Provisioned");

            return(webApp);
        }
        public static void RunSample(IAzure azure)
        {
            string suffix   = ".azurewebsites.net";
            string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
            string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
            string app4Name = SdkContext.RandomResourceName("webapp4-", 20);
            string app1Url  = app1Name + suffix;
            string app2Url  = app2Name + suffix;
            string app3Url  = app3Name + suffix;
            string app4Url  = app4Name + suffix;
            string rgName   = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try
            {
                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + app1Name + " in resource group " + rgName + "...");

                IWebApp app1 = azure.WebApps.Define(app1Name)
                               .WithRegion(Region.USWest)
                               .WithNewResourceGroup(rgName)
                               .WithNewWindowsPlan(PricingTier.StandardS1)
                               .WithJavaVersion(JavaVersion.V8Newest)
                               .WithWebContainer(WebContainer.Tomcat8_0Newest)
                               .Create();

                Utilities.Log("Created web app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Set up active directory authentication

                Utilities.Log("Please create an AD application with redirect URL " + app1Url);
                Utilities.Log("Application ID is:");
                string applicationId = Utilities.ReadLine();
                Utilities.Log("Tenant ID is:");
                string tenantId = Utilities.ReadLine();

                Utilities.Log("Updating web app " + app1Name + " to use active directory login...");

                app1.Update()
                .DefineAuthentication()
                .WithDefaultAuthenticationProvider(BuiltInAuthenticationProvider.AzureActiveDirectory)
                .WithActiveDirectory(applicationId, "https://sts.windows.net/" + tenantId)
                .Attach()
                .Apply();

                Utilities.Log("Added active directory login to " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Create a second web app

                Utilities.Log("Creating another web app " + app2Name + " in resource group " + rgName + "...");
                IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                IWebApp         app2 = azure.WebApps.Define(app2Name)
                                       .WithExistingWindowsPlan(plan)
                                       .WithExistingResourceGroup(rgName)
                                       .WithJavaVersion(JavaVersion.V8Newest)
                                       .WithWebContainer(WebContainer.Tomcat8_0Newest)
                                       .Create();

                Utilities.Log("Created web app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Set up Facebook authentication

                Utilities.Log("Please create a Facebook developer application with whitelisted URL " + app2Url);
                Utilities.Log("App ID is:");
                string fbAppId = Utilities.ReadLine();
                Utilities.Log("App secret is:");
                string fbAppSecret = Utilities.ReadLine();

                Utilities.Log("Updating web app " + app2Name + " to use Facebook login...");

                app2.Update()
                .DefineAuthentication()
                .WithDefaultAuthenticationProvider(BuiltInAuthenticationProvider.Facebook)
                .WithFacebook(fbAppId, fbAppSecret)
                .Attach()
                .Apply();

                Utilities.Log("Added Facebook login to " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Create a 3rd web app with a public GitHub repo in Azure-Samples

                Utilities.Log("Creating another web app " + app3Name + "...");
                IWebApp app3 = azure.WebApps.Define(app3Name)
                               .WithExistingWindowsPlan(plan)
                               .WithNewResourceGroup(rgName)
                               .DefineSourceControl()
                               .WithPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started")
                               .WithBranch("master")
                               .Attach()
                               .Create();

                Utilities.Log("Created web app " + app3.Name);
                Utilities.Print(app3);

                //============================================================
                // Set up Google authentication

                Utilities.Log("Please create a Google developer application with redirect URL " + app3Url);
                Utilities.Log("Client ID is:");
                string gClientId = Utilities.ReadLine();
                Utilities.Log("Client secret is:");
                string gClientSecret = Utilities.ReadLine();

                Utilities.Log("Updating web app " + app3Name + " to use Google login...");

                app3.Update()
                .DefineAuthentication()
                .WithDefaultAuthenticationProvider(BuiltInAuthenticationProvider.Google)
                .WithGoogle(gClientId, gClientSecret)
                .Attach()
                .Apply();

                Utilities.Log("Added Google login to " + app3.Name);
                Utilities.Print(app3);

                //============================================================
                // Create a 4th web app

                Utilities.Log("Creating another web app " + app4Name + "...");
                IWebApp app4 = azure.WebApps
                               .Define(app4Name)
                               .WithExistingWindowsPlan(plan)
                               .WithExistingResourceGroup(rgName)
                               .Create();

                Utilities.Log("Created web app " + app4.Name);
                Utilities.Print(app4);

                //============================================================
                // Set up Google authentication

                Utilities.Log("Please create a Microsoft developer application with redirect URL " + app4Url);
                Utilities.Log("Client ID is:");
                string clientId = Utilities.ReadLine();
                Utilities.Log("Client secret is:");
                string clientSecret = Utilities.ReadLine();

                Utilities.Log("Updating web app " + app3Name + " to use Microsoft login...");

                app4.Update()
                .DefineAuthentication()
                .WithDefaultAuthenticationProvider(BuiltInAuthenticationProvider.MicrosoftAccount)
                .WithMicrosoft(clientId, clientSecret)
                .Attach()
                .Apply();

                Utilities.Log("Added Microsoft login to " + app4.Name);
                Utilities.Print(app4);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
        /**
         * Azure App Service basic sample for managing web apps.
         *  - Create a storage account and upload a couple blobs
         *  - Create a web app that contains the connection string to the storage account
         *  - Deploy a Tomcat application that reads from the storage account
         *  - Clean up
         */
        public static void RunSample(IAzure azure)
        {
            string app1Name      = SdkContext.RandomResourceName("webapp1-", 20);
            string app1Url       = app1Name + SUFFIX;
            string storageName   = SdkContext.RandomResourceName("jsdkstore", 20);
            string containerName = SdkContext.RandomResourceName("jcontainer", 20);
            string rgName        = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try {
                //============================================================
                // Create a storage account for the web app to use

                Utilities.Log("Creating storage account " + storageName + "...");

                IStorageAccount storageAccount = azure.StorageAccounts.Define(storageName)
                                                 .WithRegion(Region.USWest)
                                                 .WithNewResourceGroup(rgName)
                                                 .Create();

                string accountKey = storageAccount.GetKeys()[0].Value;

                string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                                                        storageAccount.Name, accountKey);

                Utilities.Log("Created storage account " + storageAccount.Name);

                //============================================================
                // Upload a few files to the storage account blobs

                Utilities.Log("Uploading 2 blobs to container " + containerName + "...");

                Utilities.UploadFilesToContainer(
                    connectionString,
                    containerName,
                    new[]
                {
                    Path.Combine(Utilities.ProjectPath, "Asset", "helloworld.war"),
                    Path.Combine(Utilities.ProjectPath, "Asset", "install_apache.Sh")
                });

                Utilities.Log("Uploaded 2 blobs to container " + containerName);

                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + app1Name + "...");

                IWebApp app1 = azure.WebApps.Define(app1Name)
                               .WithRegion(Region.USWest)
                               .WithExistingResourceGroup(rgName)
                               .WithNewLinuxPlan(PricingTier.StandardS1)
                               .WithPublicDockerHubImage("tomcat:8-jre8")
                               .WithStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"")
                               .WithConnectionString("storage.connectionString", connectionString, ConnectionStringType.Custom)
                               .WithAppSetting("storage.containerName", containerName)
                               .WithAppSetting("PORT", "8080")
                               .Create();

                Utilities.Log("Created web app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Deploy a web app that connects to the storage account
                // Source code: https://github.com/jianghaolu/azure-samples-blob-explorer

                Utilities.Log("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP...");

                Utilities.UploadFileToWebApp(
                    app1.GetPublishingProfile(),
                    Path.Combine(Utilities.ProjectPath, "Asset", "azure-samples-blob-traverser.war"));

                Utilities.Log("Deployment azure-samples-blob-traverser.war to web app " + app1.Name + " completed");
                Utilities.Print(app1);

                // warm up
                Utilities.Log("Warming up " + app1Url + "/azure-samples-blob-traverser...");
                Utilities.CheckAddress("http://" + app1Url + "/azure-samples-blob-traverser");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app1Url + "/azure-samples-blob-traverser...");
                Utilities.Log(Utilities.CheckAddress("http://" + app1Url + "/azure-samples-blob-traverser"));
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
        /**
         * Azure App Service basic sample for managing web apps.
         * Note: you need to have the Git command line available on your PATH. The sample makes a direct call to 'git'.
         *  - Create 5 web apps under the same new app service plan:
         *    - Deploy to 1 using FTP
         *    - Deploy to 2 using local Git repository
         *    - Deploy to 3 using a publicly available Git repository
         *    - Deploy to 4 using a GitHub repository with continuous integration
         *    - Deploy to 5 using Web Deploy
         */
        public static void RunSample(IAzure azure)
        {
            string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
            string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
            string app4Name = SdkContext.RandomResourceName("webapp4-", 20);
            string app5Name = SdkContext.RandomResourceName("webapp5-", 20);
            string app1Url  = app1Name + Suffix;
            string app2Url  = app2Name + Suffix;
            string app3Url  = app3Name + Suffix;
            string app4Url  = app4Name + Suffix;
            string app5Url  = app5Name + Suffix;
            string rgName   = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try
            {
                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + app1Name + " in resource group " + rgName + "...");

                var app1 = azure.WebApps
                           .Define(app1Name)
                           .WithRegion(Region.USWest)
                           .WithNewResourceGroup(rgName)
                           .WithNewWindowsPlan(PricingTier.StandardS1)
                           .WithJavaVersion(JavaVersion.V8Newest)
                           .WithWebContainer(WebContainer.Tomcat8_0Newest)
                           .Create();

                Utilities.Log("Created web app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Deploy to app 1 through FTP

                Utilities.Log("Deploying helloworld.War to " + app1Name + " through FTP...");

                Utilities.UploadFileToWebApp(
                    app1.GetPublishingProfile(),
                    Path.Combine(Utilities.ProjectPath, "Asset", "helloworld.war"));

                Utilities.Log("Deployment helloworld.War to web app " + app1.Name + " completed");
                Utilities.Print(app1);

                // warm up
                Utilities.Log("Warming up " + app1Url + "/helloworld...");
                Utilities.CheckAddress("http://" + app1Url + "/helloworld");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app1Url + "/helloworld...");
                Utilities.Log(Utilities.CheckAddress("http://" + app1Url + "/helloworld"));

                //============================================================
                // Create a second web app with local git source control

                Utilities.Log("Creating another web app " + app2Name + " in resource group " + rgName + "...");
                var plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                var app2 = azure.WebApps
                           .Define(app2Name)
                           .WithExistingWindowsPlan(plan)
                           .WithExistingResourceGroup(rgName)
                           .WithLocalGitSourceControl()
                           .WithJavaVersion(JavaVersion.V8Newest)
                           .WithWebContainer(WebContainer.Tomcat8_0Newest)
                           .Create();

                Utilities.Log("Created web app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Deploy to app 2 through local Git

                Utilities.Log("Deploying a local Tomcat source to " + app2Name + " through Git...");

                var profile = app2.GetPublishingProfile();
                Utilities.DeployByGit(profile, "azure-samples-appservice-helloworld");

                Utilities.Log("Deployment to web app " + app2.Name + " completed");
                Utilities.Print(app2);

                // warm up
                Utilities.Log("Warming up " + app2Url + "/helloworld...");
                Utilities.CheckAddress("http://" + app2Url + "/helloworld");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app2Url + "/helloworld...");
                Utilities.Log(Utilities.CheckAddress("http://" + app2Url + "/helloworld"));

                //============================================================
                // Create a 3rd web app with a public GitHub repo in Azure-Samples

                Utilities.Log("Creating another web app " + app3Name + "...");
                var app3 = azure.WebApps
                           .Define(app3Name)
                           .WithExistingWindowsPlan(plan)
                           .WithNewResourceGroup(rgName)
                           .DefineSourceControl()
                           .WithPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started")
                           .WithBranch("master")
                           .Attach()
                           .Create();

                Utilities.Log("Created web app " + app3.Name);
                Utilities.Print(app3);

                // warm up
                Utilities.Log("Warming up " + app3Url + "...");
                Utilities.CheckAddress("http://" + app3Url);
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app3Url + "...");
                Utilities.Log(Utilities.CheckAddress("http://" + app3Url));

                //============================================================
                // Create a 4th web app with a personal GitHub repo and turn on continuous integration

                Utilities.Log("Creating another web app " + app4Name + "...");
                var app4 = azure.WebApps
                           .Define(app4Name)
                           .WithExistingWindowsPlan(plan)
                           .WithExistingResourceGroup(rgName)
                           // Uncomment the following lines to turn on 4th scenario
                           //.DefineSourceControl()
                           //    .WithContinuouslyIntegratedGitHubRepository("username", "reponame")
                           //    .WithBranch("master")
                           //    .WithGitHubAccessToken("YOUR GITHUB PERSONAL TOKEN")
                           //    .Attach()
                           .Create();

                Utilities.Log("Created web app " + app4.Name);
                Utilities.Print(app4);

                // warm up
                Utilities.Log("Warming up " + app4Url + "...");
                Utilities.CheckAddress("http://" + app4Url);
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app4Url + "...");
                Utilities.Log(Utilities.CheckAddress("http://" + app4Url));

                //============================================================
                // Create a 5th web app with web deploy

                Utilities.Log("Creating another web app " + app5Name + "...");

                IWebApp app5 = azure.WebApps.Define(app5Name)
                               .WithExistingWindowsPlan(plan)
                               .WithExistingResourceGroup(rgName)
                               .WithNetFrameworkVersion(NetFrameworkVersion.V4_6)
                               .Create();

                Utilities.Log("Created web app " + app5.Name);
                Utilities.Print(app5);

                //============================================================
                // Deploy to the 5th web app through web deploy

                Utilities.Log("Deploying a bakery website to " + app5Name + " through web deploy...");

                app5.Deploy()
                .WithPackageUri("https://github.com/Azure/azure-libraries-for-net/raw/master/Tests/Fluent.Tests/Assets/bakery-webapp.zip")
                .WithExistingDeploymentsDeleted(true)
                .Execute();

                Utilities.Log("Deployment to web app " + app5Name + " completed.");
                Utilities.Print(app5);

                // warm up
                Utilities.Log("Warming up " + app5Url + "...");
                Utilities.CheckAddress("http://" + app5Url);
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app5Url + "...");
                Utilities.Log(Utilities.CheckAddress("http://" + app5Url));
            }
            catch (FileNotFoundException)
            {
                Utilities.Log("Cannot find 'git' command line. Make sure Git is installed and the directory of git.exe is included in your PATH environment variable.");
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
 ///GENMHASH:F529354C5AB0AFD4EE1F8B0AABF34899:D375F18C8B128D8FF0869B061F7CD9E9
 public DeploymentSlotImpl WithConfigurationFromWebApp(IWebApp webApp)
 {
     CopyConfigurations(((WebAppImpl)webApp).SiteConfig, webApp.AppSettings.Values.ToList(), webApp.ConnectionStrings.Values.ToList());
     return(this);
 }
Example #28
0
 public CatalogPipeline(IWebApp webApp, IPaperCatalog paperCatalog, IObjectFactory objectFactory)
 {
     this.defaultCatalog = webApp.Name;
     this.paperCatalog   = paperCatalog;
     this.objectFactory  = objectFactory;
 }
        /**
         * Azure App Service basic sample for managing web apps.
         *  - Create a Cosmos DB with credentials stored in a Key Vault
         *  - Create a web app which interacts with the Cosmos DB by first
         *      reading the secrets from the Key Vault.
         *
         *      The source code of the web app is located at Asset/documentdb-dotnet-todo-app
         */

        public static void RunSample(IAzure azure)
        {
            Region region     = Region.USWest;
            string appName    = SdkContext.RandomResourceName("webapp-", 20);
            string rgName     = SdkContext.RandomResourceName("rg1NEMV_", 24);
            string vaultName  = SdkContext.RandomResourceName("vault", 20);
            string cosmosName = SdkContext.RandomResourceName("cosmosdb", 20);
            string appUrl     = appName + ".azurewebsites.net";

            try
            {
                //============================================================
                // Create a CosmosDB

                Utilities.Log("Creating a CosmosDB...");
                ICosmosDBAccount cosmosDBAccount = azure.CosmosDBAccounts.Define(cosmosName)
                                                   .WithRegion(region)
                                                   .WithNewResourceGroup(rgName)
                                                   .WithKind(DatabaseAccountKind.GlobalDocumentDB)
                                                   .WithEventualConsistency()
                                                   .WithWriteReplication(Region.USEast)
                                                   .WithReadReplication(Region.USCentral)
                                                   .Create();

                Utilities.Log("Created CosmosDB");
                Utilities.Log(cosmosDBAccount);

                //============================================================
                // Create a key vault

                var servicePrincipalInfo = ParseAuthFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                IVault vault = azure.Vaults
                               .Define(vaultName)
                               .WithRegion(region)
                               .WithNewResourceGroup(rgName)
                               .DefineAccessPolicy()
                               .ForServicePrincipal(servicePrincipalInfo.ClientId)
                               .AllowSecretAllPermissions()
                               .Attach()
                               .Create();

                SdkContext.DelayProvider.Delay(10000);

                //============================================================
                // Store Cosmos DB credentials in Key Vault

                IKeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async(authority, resource, scope) =>
                {
                    var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
                    var result  = await context.AcquireTokenAsync(resource, new ClientCredential(servicePrincipalInfo.ClientId, servicePrincipalInfo.ClientSecret));
                    return(result.AccessToken);
                }), ((KeyVaultManagementClient)azure.Vaults.Manager.Inner).HttpClient);
                keyVaultClient.SetSecretAsync(vault.VaultUri, "azure-documentdb-uri", cosmosDBAccount.DocumentEndpoint).GetAwaiter().GetResult();
                keyVaultClient.SetSecretAsync(vault.VaultUri, "azure-documentdb-key", cosmosDBAccount.ListKeys().PrimaryMasterKey).GetAwaiter().GetResult();
                keyVaultClient.SetSecretAsync(vault.VaultUri, "azure-documentdb-database", "tododb").GetAwaiter().GetResult();

                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + appName + " in resource group " + rgName + "...");

                IWebApp app = azure.WebApps
                              .Define(appName)
                              .WithRegion(region)
                              .WithExistingResourceGroup(rgName)
                              .WithNewWindowsPlan(PricingTier.StandardS1)
                              .WithNetFrameworkVersion(NetFrameworkVersion.V4_6)
                              .WithAppSetting("AZURE_KEYVAULT_URI", vault.VaultUri)
                              .WithSystemAssignedManagedServiceIdentity()
                              .Create();

                Utilities.Log("Created web app " + app.Name);
                Utilities.Log(app);

                //============================================================
                // Update vault to allow the web app to access

                vault.Update()
                .DefineAccessPolicy()
                .ForObjectId(app.SystemAssignedManagedServiceIdentityPrincipalId)
                .AllowSecretAllPermissions()
                .Attach()
                .Apply();

                //============================================================
                // Deploy to web app through local Git

                Utilities.Log("Deploying a local asp.net application to " + appName + " through Git...");

                var profile = app.GetPublishingProfile();
                Utilities.DeployByGit(profile, "documentdb-dotnet-todo-app");

                Utilities.Log("Deployment to web app " + app.Name + " completed");
                Utilities.Print(app);

                // warm up
                Utilities.Log("Warming up " + appUrl + "...");
                Utilities.CheckAddress("http://" + appUrl);
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + appUrl + "...");
                Utilities.Log(Utilities.CheckAddress("http://" + appUrl));
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
 public WebAppHandler(IWebApp webapp, string method, params string[] args)
 {
     this.webApp = webapp;
     this.method = method.ToUpper();
     this.args = args;
 }
Example #31
0
        /**
         * Azure App Service basic sample for managing web apps.
         *  - Create a SQL database in a new SQL server
         *  - Create a web app deployed with Project Nami (WordPress's SQL Server variant)
         *      that contains the app settings to connect to the SQL database
         *  - Update the SQL server's firewall rules to allow the web app to access
         *  - Clean up
         */

        public static void RunSample(IAzure azure)
        {
            string appName       = SdkContext.RandomResourceName("webapp1-", 20);
            string appUrl        = appName + Suffix;
            string sqlServerName = SdkContext.RandomResourceName("jsdkserver", 20);
            string sqlDbName     = SdkContext.RandomResourceName("jsdkdb", 20);
            string rgName        = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try
            {
                //============================================================
                // Create a sql server

                Utilities.Log("Creating SQL server " + sqlServerName + "...");

                ISqlServer server = azure.SqlServers.Define(sqlServerName)
                                    .WithRegion(Region.USWest)
                                    .WithNewResourceGroup(rgName)
                                    .WithAdministratorLogin(Admin)
                                    .WithAdministratorPassword(Password)
                                    .Create();

                Utilities.Log("Created SQL server " + server.Name);

                //============================================================
                // Create a sql database for the web app to use

                Utilities.Log("Creating SQL database " + sqlDbName + "...");

                ISqlDatabase db = server.Databases.Define(sqlDbName)
                                  .Create();

                Utilities.Log("Created SQL database " + db.Name);

                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + appName + "...");

                IWebApp app = azure.WebApps
                              .Define(appName)
                              .WithRegion(Region.USWest)
                              .WithExistingResourceGroup(rgName)
                              .WithNewWindowsPlan(PricingTier.StandardS1)
                              .WithPhpVersion(PhpVersion.V5_6)
                              .DefineSourceControl()
                              .WithPublicGitRepository("https://github.com/ProjectNami/projectnami")
                              .WithBranch("master")
                              .Attach()
                              .WithAppSetting("ProjectNami.DBHost", server.FullyQualifiedDomainName)
                              .WithAppSetting("ProjectNami.DBName", db.Name)
                              .WithAppSetting("ProjectNami.DBUser", Admin)
                              .WithAppSetting("ProjectNami.DBPass", Password)
                              .Create();

                Utilities.Log("Created web app " + app.Name);
                Utilities.Print(app);

                //============================================================
                // Allow web app to access the SQL server

                Utilities.Log("Allowing web app " + appName + " to access SQL server...");

                Microsoft.Azure.Management.Sql.Fluent.SqlServer.Update.IUpdate update = server.Update();
                foreach (var ip in app.OutboundIPAddresses)
                {
                    update = update.WithNewFirewallRule(ip);
                }
                server = update.Apply();

                Utilities.Log("Firewall rules added for web app " + appName);
                Utilities.PrintSqlServer(server);

                Utilities.Log("Your WordPress app is ready.");
                Utilities.Log("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit.");
                Utilities.ReadLine();
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
 public WebAppProcessor(IWebApp webapp)
 {
     try
     {
         this.webApp = webapp;
     }
     catch (Exception ex)
     {
         throw new Exception("Could not instantiate WebApp", ex);
     }
 }