/// <summary>
        /// Publishes the ASP.NET Core project to App Engine Flex.
        /// </summary>
        /// <param name="projectPath">The full path to the project.json for the ASP.NET Core project.</param>
        /// <param name="options">The <seealso cref="DeploymentOptions"/> to use.</param>
        /// <param name="progress">The progress indicator.</param>
        /// <param name="outputAction">The action to call with lines from the command output.</param>
        /// <returns></returns>
        public static async Task<NetCorePublishResult> PublishProjectAsync(
            string projectPath,
            DeploymentOptions options,
            IProgress<double> progress,
            Action<string> outputAction)
        {
            if (!File.Exists(projectPath))
            {
                Debug.WriteLine($"Cannot find {projectPath}, not a valid project.");
                return null;
            }

            var stageDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(stageDirectory);
            progress.Report(0.1);

            using (var cleanup = new Disposable(() => Cleanup(stageDirectory)))
            {
                // Wait for the bundle creation operation to finish, updating progress as it goes.
                if (!await ProgressHelper.UpdateProgress(
                        CreateAppBundleAsync(projectPath, stageDirectory, outputAction),
                        progress,
                        from: 0.1, to: 0.3))
                {
                    Debug.WriteLine("Failed to create app bundle.");
                    return null;
                }

                CopyOrCreateDockerfile(projectPath, stageDirectory);
                CopyOrCreateAppYaml(projectPath, stageDirectory);
                progress.Report(0.4);

                // Deploy to app engine, this is where most of the time is going to be spent. Wait for
                // the operation to finish, update the progress as it goes.
                var effectiveVersion = options.Version ?? GetDefaultVersion();
                var deployTask = DeployAppBundleAsync(
                    stageDirectory: stageDirectory,
                    version: effectiveVersion,
                    promote: options.Promote,
                    context: options.Context,
                    outputAction: outputAction);
                if (!await ProgressHelper.UpdateProgress(deployTask, progress, 0.6, 0.9))
                {
                    Debug.WriteLine("Failed to deploy bundle.");
                    return null;
                }
                progress.Report(1.0);

                var service = GetAppEngineService(projectPath);
                return new NetCorePublishResult(
                    projectId: options.Context.ProjectId,
                    service: service,
                    version: effectiveVersion,
                    promoted: options.Promote);
            }
        }
        private static void DeployApplication(
            DeployAppMode mode, 
            DeviceInfo deviceInfo, 
            IAppManifestInfo manifestInfo, 
            DeploymentOptions deploymentOptions, 
            string packageFile, 
            bool disconnect = true)
        {
            if (PackageType.Framework != manifestInfo.PackageType && WinTrust.VerifyEmbeddedSignature(packageFile))
            {
                throw new Exception(
                    string.Format(
                        CultureInfo.CurrentUICulture, 
                        Resources.InvalidPackaging, 
                        new object[0]));
            }

            var connectableDevice =
                new MultiTargetingConnectivity(CultureInfo.CurrentUICulture.LCID).GetConnectableDevice(
                    deviceInfo.DeviceId);
            var device = connectableDevice.Connect(true);
            var systemInfo = device.GetSystemInfo();
            var deviceVersion = new Version(systemInfo.OSMajor, systemInfo.OSMinor);
            if (manifestInfo.PlatformVersion.CompareTo(deviceVersion) > 0)
            {
                device.Disconnect();
                throw new Exception(
                    string.Format(
                        CultureInfo.CurrentUICulture, 
                        Resources.XapNotSupportedOnDevice, 
                        new object[0]));
            }

            var flag = IsTargetApplicableforMdilGeneration(
                connectableDevice, 
                deviceVersion, 
                manifestInfo, 
                packageFile);
            ApplySideloadFlags(manifestInfo, ref deploymentOptions);
            if (mode == DeployAppMode.Install)
            {
                if (device.IsApplicationInstalled(manifestInfo.ProductId))
                {
                    if (manifestInfo.PackageType == PackageType.Framework)
                    {
                        return;
                    }

                    device.GetApplication(manifestInfo.ProductId).Uninstall();
                }

                foreach (var str in DependencyFinder.GetAppDependencyPackages(packageFile))
                {
                    var manifestInfo1 = ReadAppManifestInfoFromPackage(str);
                    DeployApplication(
                        DeployAppMode.Install, 
                        deviceInfo, 
                        manifestInfo1, 
                        DeploymentOptions.OptOutSD, 
                        str, 
                        false);
                }
            }

            var app = (IRemoteApplication)null;
            if (mode == DeployAppMode.Update)
            {
                app = device.GetApplication(manifestInfo.ProductId);
            }

            var typeOfApp = DetermineAppType(packageFile);
            var applicationGenre = ((int)deploymentOptions).ToString(CultureInfo.InvariantCulture);
            var iconPath = ((int)manifestInfo.PackageType).ToString(CultureInfo.InvariantCulture);
            switch (mode)
            {
                case DeployAppMode.Install:
                    break;
                case DeployAppMode.Update:
                    break;
            }

            var path = (string)null;
            try
            {
                if (IsMdilFirst(typeOfApp, manifestInfo))
                {
                    if (flag)
                    {
                        path = GenerateNDeployMdil(packageFile, null, typeOfApp, manifestInfo);
                        packageFile = path;
                    }

                    switch (mode)
                    {
                        case DeployAppMode.Install:
                            app = device.InstallApplication(
                                manifestInfo.ProductId, 
                                manifestInfo.ProductId, 
                                applicationGenre, 
                                iconPath, 
                                packageFile);
                            break;
                        case DeployAppMode.Update:
                            app.UpdateApplication(applicationGenre, iconPath, packageFile);
                            break;
                    }
                }
                else
                {
                    switch (mode)
                    {
                        case DeployAppMode.Install:
                            app = device.InstallApplication(
                                manifestInfo.ProductId, 
                                manifestInfo.ProductId, 
                                applicationGenre, 
                                iconPath, 
                                packageFile);
                            break;
                        case DeployAppMode.Update:
                            app.UpdateApplication(applicationGenre, iconPath, packageFile);
                            break;
                    }

                    if (flag)
                    {
                        path = GenerateNDeployMdil(packageFile, app, typeOfApp, manifestInfo);
                    }
                }
            }
            finally
            {
                if (!GlobalOptions.LeaveBehindOptimized && !string.IsNullOrWhiteSpace(path) && File.Exists(path))
                {
                    File.Delete(path);
                }
            }

            if (GlobalOptions.LaunchAfterInstall && app != null)
            {
                app.Launch();
            }

            if (!disconnect)
            {
                return;
            }

            device.Disconnect();
        }
 public static void InstallApplication(
     DeviceInfo deviceInfo, 
     IAppManifestInfo manifestInfo, 
     DeploymentOptions deploymentOptions, 
     string packageFile)
 {
     DeployApplication(DeployAppMode.Install, deviceInfo, manifestInfo, deploymentOptions, packageFile);
 }
        private async Task SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(string sourceScript, string targetScript, DeploymentOptions nodiffOption, DeploymentOptions shouldDiffOption)
        {
            var       result   = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, sourceScript, "SchemaCompareSource");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, targetScript, "SchemaCompareTarget");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SchemaCompareTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
                SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();

                sourceInfo.EndpointType = SchemaCompareEndpointType.Database;
                sourceInfo.DatabaseName = sourceDb.DatabaseName;
                targetInfo.EndpointType = SchemaCompareEndpointType.Database;
                targetInfo.DatabaseName = targetDb.DatabaseName;

                var schemaCompareParams1 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = nodiffOption
                };

                SchemaCompareOperation schemaCompareOperation1 = new SchemaCompareOperation(schemaCompareParams1, result.ConnectionInfo, result.ConnectionInfo);
                schemaCompareOperation1.Execute(TaskExecutionMode.Execute);

                Assert.True(schemaCompareOperation1.ComparisonResult.IsValid);
                Assert.True(schemaCompareOperation1.ComparisonResult.IsEqual);
                Assert.NotNull(schemaCompareOperation1.ComparisonResult.Differences);

                var schemaCompareParams2 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = shouldDiffOption,
                };

                SchemaCompareOperation schemaCompareOperation2 = new SchemaCompareOperation(schemaCompareParams2, result.ConnectionInfo, result.ConnectionInfo);
                schemaCompareOperation2.Execute(TaskExecutionMode.Execute);
                Assert.False(schemaCompareOperation2.ComparisonResult.IsEqual);
                Assert.NotNull(schemaCompareOperation2.ComparisonResult.Differences);
            }
            finally
            {
                // cleanup
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }
        }
        internal static void ApplySideloadFlags(IAppManifestInfo manifestInfo, ref DeploymentOptions deploymentOptions)
        {
            if (manifestInfo.PackageType == PackageType.Main || manifestInfo.PackageType == PackageType.Bundle
                || manifestInfo.PackageType == PackageType.UnknownAppx)
            {
                deploymentOptions |= DeploymentOptions.Sideload;
            }
            else
            {
                if (manifestInfo.PackageType != PackageType.Framework)
                {
                    return;
                }

                deploymentOptions &= ~DeploymentOptions.Sideload;
            }
        }
Esempio n. 6
0
        private static void DeployApplication(
            DeployAppMode mode,
            DeviceInfo deviceInfo,
            IAppManifestInfo manifestInfo,
            DeploymentOptions deploymentOptions,
            string packageFile,
            bool disconnect = true)
        {
            if (PackageType.Framework != manifestInfo.PackageType && WinTrust.VerifyEmbeddedSignature(packageFile))
            {
                throw new Exception(
                          string.Format(
                              CultureInfo.CurrentUICulture,
                              Resources.InvalidPackaging,
                              new object[0]));
            }

            var connectableDevice =
                new MultiTargetingConnectivity(CultureInfo.CurrentUICulture.LCID).GetConnectableDevice(
                    deviceInfo.DeviceId);
            var device        = connectableDevice.Connect(true);
            var systemInfo    = device.GetSystemInfo();
            var deviceVersion = new Version(systemInfo.OSMajor, systemInfo.OSMinor);

            if (manifestInfo.PlatformVersion.CompareTo(deviceVersion) > 0)
            {
                device.Disconnect();
                throw new Exception(
                          string.Format(
                              CultureInfo.CurrentUICulture,
                              Resources.XapNotSupportedOnDevice,
                              new object[0]));
            }

            var flag = IsTargetApplicableforMdilGeneration(
                connectableDevice,
                deviceVersion,
                manifestInfo,
                packageFile);

            ApplySideloadFlags(manifestInfo, ref deploymentOptions);
            if (mode == DeployAppMode.Install)
            {
                if (device.IsApplicationInstalled(manifestInfo.ProductId))
                {
                    if (manifestInfo.PackageType == PackageType.Framework)
                    {
                        return;
                    }

                    device.GetApplication(manifestInfo.ProductId).Uninstall();
                }

                foreach (var str in DependencyFinder.GetAppDependencyPackages(packageFile))
                {
                    var manifestInfo1 = ReadAppManifestInfoFromPackage(str);
                    DeployApplication(
                        DeployAppMode.Install,
                        deviceInfo,
                        manifestInfo1,
                        DeploymentOptions.OptOutSD,
                        str,
                        false);
                }
            }

            var app = (IRemoteApplication)null;

            if (mode == DeployAppMode.Update)
            {
                app = device.GetApplication(manifestInfo.ProductId);
            }

            var typeOfApp        = DetermineAppType(packageFile);
            var applicationGenre = ((int)deploymentOptions).ToString(CultureInfo.InvariantCulture);
            var iconPath         = ((int)manifestInfo.PackageType).ToString(CultureInfo.InvariantCulture);

            switch (mode)
            {
            case DeployAppMode.Install:
                break;

            case DeployAppMode.Update:
                break;
            }

            var path = (string)null;

            try
            {
                if (IsMdilFirst(typeOfApp, manifestInfo))
                {
                    if (flag)
                    {
                        path        = GenerateNDeployMdil(packageFile, null, typeOfApp, manifestInfo);
                        packageFile = path;
                    }

                    switch (mode)
                    {
                    case DeployAppMode.Install:
                        app = device.InstallApplication(
                            manifestInfo.ProductId,
                            manifestInfo.ProductId,
                            applicationGenre,
                            iconPath,
                            packageFile);
                        break;

                    case DeployAppMode.Update:
                        app.UpdateApplication(applicationGenre, iconPath, packageFile);
                        break;
                    }
                }
                else
                {
                    switch (mode)
                    {
                    case DeployAppMode.Install:
                        app = device.InstallApplication(
                            manifestInfo.ProductId,
                            manifestInfo.ProductId,
                            applicationGenre,
                            iconPath,
                            packageFile);
                        break;

                    case DeployAppMode.Update:
                        app.UpdateApplication(applicationGenre, iconPath, packageFile);
                        break;
                    }

                    if (flag)
                    {
                        path = GenerateNDeployMdil(packageFile, app, typeOfApp, manifestInfo);
                    }
                }
            }
            finally
            {
                if (!GlobalOptions.LeaveBehindOptimized && !string.IsNullOrWhiteSpace(path) && File.Exists(path))
                {
                    File.Delete(path);
                }
            }

            if (GlobalOptions.LaunchAfterInstall && app != null)
            {
                app.Launch();
            }

            if (!disconnect)
            {
                return;
            }

            device.Disconnect();
        }
        private async Task SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(string sourceScript, string targetScript, DeploymentOptions nodiffOption, DeploymentOptions shouldDiffOption)
        {
            var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();

            // create dacpacs from databases
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, sourceScript, "SchemaCompareSource");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, targetScript, "SchemaCompareTarget");

            try
            {
                string sourceDacpacFilePath = SchemaCompareTestUtils.CreateDacpac(sourceDb);
                string targetDacpacFilePath = SchemaCompareTestUtils.CreateDacpac(targetDb);

                SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
                SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();

                sourceInfo.EndpointType    = SchemaCompareEndpointType.Dacpac;
                sourceInfo.PackageFilePath = sourceDacpacFilePath;
                targetInfo.EndpointType    = SchemaCompareEndpointType.Dacpac;
                targetInfo.PackageFilePath = targetDacpacFilePath;

                var schemaCompareParams1 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = nodiffOption
                };

                SchemaCompareOperation schemaCompareOperation1 = new SchemaCompareOperation(schemaCompareParams1, null, null);
                schemaCompareOperation1.Execute(TaskExecutionMode.Execute);
                Assert.True(schemaCompareOperation1.ComparisonResult.IsEqual);

                var schemaCompareParams2 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = shouldDiffOption,
                };

                SchemaCompareOperation schemaCompareOperation2 = new SchemaCompareOperation(schemaCompareParams2, null, null);
                schemaCompareOperation2.Execute(TaskExecutionMode.Execute);
                Assert.False(schemaCompareOperation2.ComparisonResult.IsEqual);
                Assert.NotNull(schemaCompareOperation2.ComparisonResult.Differences);

                // cleanup
                SchemaCompareTestUtils.VerifyAndCleanup(sourceDacpacFilePath);
                SchemaCompareTestUtils.VerifyAndCleanup(targetDacpacFilePath);
            }
            finally
            {
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Publishes the ASP.NET Core app using the <paramref name="options"/> to produce the right deployment
        /// and service (if needed).
        /// </summary>
        /// <param name="projectPath">The full path to the project.json file of the startup project.</param>
        /// <param name="options">The options to use for the deployment.</param>
        /// <param name="progress">The progress interface for progress notifications.</param>
        /// <param name="outputAction">The output callback to invoke for output from the process.</param>
        /// <returns>Returns a <seealso cref="GkeDeploymentResult"/> if the deployment succeeded null otherwise.</returns>
        public static async Task <GkeDeploymentResult> PublishProjectAsync(
            string projectPath,
            DeploymentOptions options,
            IProgress <double> progress,
            Action <string> outputAction)
        {
            if (!File.Exists(projectPath))
            {
                Debug.WriteLine($"Cannot find {projectPath}, not a valid project.");
                return(null);
            }

            var stageDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(stageDirectory);
            progress.Report(0.1);

            using (var cleanup = new Disposable(() => CommonUtils.Cleanup(stageDirectory)))
            {
                var appRootPath   = Path.Combine(stageDirectory, "app");
                var buildFilePath = Path.Combine(stageDirectory, "cloudbuild.yaml");

                if (!await ProgressHelper.UpdateProgress(
                        NetCoreAppUtils.CreateAppBundleAsync(projectPath, appRootPath, outputAction),
                        progress,
                        from: 0.1, to: 0.3))
                {
                    Debug.WriteLine("Failed to create app bundle.");
                    return(null);
                }

                NetCoreAppUtils.CopyOrCreateDockerfile(projectPath, appRootPath);
                var image = CloudBuilderUtils.CreateBuildFile(
                    project: options.GCloudContext.ProjectId,
                    imageName: options.DeploymentName,
                    imageVersion: options.DeploymentVersion,
                    buildFilePath: buildFilePath);

                if (!await ProgressHelper.UpdateProgress(
                        GCloudWrapper.BuildContainerAsync(buildFilePath, appRootPath, outputAction, options.GCloudContext),
                        progress,
                        from: 0.4, to: 0.7))
                {
                    Debug.WriteLine("Failed to build container.");
                    return(null);
                }
                progress.Report(0.7);

                string publicIpAddress   = null;
                string clusterIpAddress  = null;
                bool   deploymentUpdated = false;
                bool   deploymentScaled  = false;
                bool   serviceExposed    = false;
                bool   serviceUpdated    = false;
                bool   serviceDeleted    = false;

                // Create or update the deployment.
                var deployments = await KubectlWrapper.GetDeploymentsAsync(options.KubectlContext);

                var deployment = deployments?.FirstOrDefault(x => x.Metadata.Name == options.DeploymentName);
                if (deployment == null)
                {
                    Debug.WriteLine($"Creating new deployment {options.DeploymentName}");
                    if (!await KubectlWrapper.CreateDeploymentAsync(
                            name: options.DeploymentName,
                            imageTag: image,
                            replicas: options.Replicas,
                            outputAction: outputAction,
                            context: options.KubectlContext))
                    {
                        Debug.WriteLine($"Failed to create deployment {options.DeploymentName}");
                        return(null);
                    }
                    progress.Report(0.8);
                }
                else
                {
                    Debug.WriteLine($"Updating existing deployment {options.DeploymentName}");
                    if (!await KubectlWrapper.UpdateDeploymentImageAsync(
                            options.DeploymentName,
                            image,
                            outputAction,
                            options.KubectlContext))
                    {
                        Debug.WriteLine($"Failed to update deployemnt {options.DeploymentName}");
                        return(null);
                    }
                    deploymentUpdated = true;

                    // If the deployment already exists but the replicas number requested is not the
                    // same as the existing number we will scale up/down the deployment.
                    if (deployment.Spec.Replicas != options.Replicas)
                    {
                        Debug.WriteLine($"Updating the replicas for the deployment.");
                        if (!await KubectlWrapper.ScaleDeploymentAsync(
                                options.DeploymentName,
                                options.Replicas,
                                outputAction,
                                options.KubectlContext))
                        {
                            Debug.WriteLine($"Failed to scale up deployment {options.DeploymentName}");
                            return(null);
                        }
                        deploymentScaled = true;
                    }
                }

                // Expose the service if requested and it is not already exposed.
                var services = await KubectlWrapper.GetServicesAsync(options.KubectlContext);

                var service = services?.FirstOrDefault(x => x.Metadata.Name == options.DeploymentName);
                if (options.ExposeService)
                {
                    var requestedType = options.ExposePublicService ?
                                        GkeServiceSpec.LoadBalancerType : GkeServiceSpec.ClusterIpType;
                    if (service != null && service?.Spec?.Type != requestedType)
                    {
                        Debug.WriteLine($"The existing service is {service?.Spec?.Type} the requested is {requestedType}");
                        if (!await KubectlWrapper.DeleteServiceAsync(options.DeploymentName, outputAction, options.KubectlContext))
                        {
                            Debug.WriteLine($"Failed to delete serive {options.DeploymentName}");
                        }
                        service = null; // Now the service is gone, needs to be re-created with the new options.

                        serviceUpdated = true;
                    }

                    if (service == null)
                    {
                        // The service needs to be exposed but it wasn't. Expose a new service here.
                        if (!await KubectlWrapper.ExposeServiceAsync(
                                options.DeploymentName,
                                options.ExposePublicService,
                                outputAction,
                                options.KubectlContext))
                        {
                            Debug.WriteLine($"Failed to expose service {options.DeploymentName}");
                            return(null);
                        }
                        clusterIpAddress = await WaitForServiceClusterIpAddressAsync(options.DeploymentName, options.KubectlContext);

                        if (options.ExposePublicService)
                        {
                            publicIpAddress = await WaitForServicePublicIpAddressAsync(
                                options.DeploymentName,
                                options.WaitingForServiceIpCallback,
                                options.KubectlContext);
                        }

                        serviceExposed = true;
                    }
                }
                else
                {
                    // The user doesn't want a service exposed.
                    if (service != null)
                    {
                        if (!await KubectlWrapper.DeleteServiceAsync(options.DeploymentName, outputAction, options.KubectlContext))
                        {
                            Debug.WriteLine($"Failed to delete service {options.DeploymentName}");
                            return(null);
                        }
                    }

                    serviceDeleted = true;
                }

                return(new GkeDeploymentResult(
                           publicIpAddress: publicIpAddress,
                           privateIpAddress: clusterIpAddress,
                           serviceExposed: serviceExposed,
                           serviceUpdated: serviceUpdated,
                           serviceDeleted: serviceDeleted,
                           deploymentUpdated: deploymentUpdated,
                           deploymentScaled: deploymentScaled));
            }
        }
        /// <summary>
        /// Publishes the ASP.NET Core project to App Engine Flex.
        /// </summary>
        /// <param name="project">The project to deploy.</param>
        /// <param name="options">The <seealso cref="DeploymentOptions"/> to use.</param>
        /// <param name="progress">The progress indicator.</param>
        /// <param name="toolsPathProvider">The tools path provider to use.</param>
        /// <param name="outputAction">The action to call with lines from the command output.</param>
        public static async Task <AppEngineFlexDeploymentResult> PublishProjectAsync(
            IParsedProject project,
            DeploymentOptions options,
            IProgress <double> progress,
            IToolsPathProvider toolsPathProvider,
            Action <string> outputAction)
        {
            var stageDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(stageDirectory);
            progress.Report(0.1);

            using (var cleanup = new Disposable(() => CommonUtils.Cleanup(stageDirectory)))
            {
                // Wait for the bundle creation operation to finish, updating progress as it goes.
                if (!await ProgressHelper.UpdateProgress(
                        NetCoreAppUtils.CreateAppBundleAsync(project, stageDirectory, toolsPathProvider, outputAction),
                        progress,
                        from: 0.1, to: 0.3))
                {
                    Debug.WriteLine("Failed to create app bundle.");
                    return(null);
                }

                var runtime = GetAppEngineRuntime(project);
                CopyOrCreateAppYaml(project, stageDirectory);
                if (runtime == CustomRuntime)
                {
                    Debug.WriteLine($"Copying Docker file to {stageDirectory} with custom runtime.");
                    NetCoreAppUtils.CopyOrCreateDockerfile(project, stageDirectory);
                }
                else
                {
                    Debug.WriteLine($"Detected runtime {runtime}");
                }
                progress.Report(0.4);

                // Deploy to app engine, this is where most of the time is going to be spent. Wait for
                // the operation to finish, update the progress as it goes.
                var effectiveVersion = options.Version ?? GetDefaultVersion();
                var deployTask       = DeployAppBundleAsync(
                    stageDirectory: stageDirectory,
                    version: effectiveVersion,
                    promote: options.Promote,
                    context: options.Context,
                    outputAction: outputAction);
                if (!await ProgressHelper.UpdateProgress(deployTask, progress, 0.6, 0.9))
                {
                    Debug.WriteLine("Failed to deploy bundle.");
                    return(null);
                }
                progress.Report(1.0);

                var service = GetAppEngineService(project);
                return(new AppEngineFlexDeploymentResult(
                           projectId: options.Context.ProjectId,
                           service: service,
                           version: effectiveVersion,
                           promoted: options.Promote));
            }
        }
Esempio n. 10
0
        private DeploymentResult DeployInternalLockTaken(
            Module module,
            DeploymentOptions options,
            string deploymentId,
            DateTimeEx addedDate)
        {
            if (Log.IsDebugEnabled)
            {
                Log.Debug("Deploying module " + module);
            }
            IList <string> imports;

            if (module.Imports != null)
            {
                foreach (string imported in module.Imports)
                {
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug("Adding import " + imported);
                    }
                    _epService.Configuration.AddImport(imported);
                }
                imports = new List <string>(module.Imports);
            }
            else
            {
                imports = Collections.GetEmptyList <string>();
            }

            if (options.IsCompile)
            {
                var exceptionsX = new List <DeploymentItemException>();
                foreach (ModuleItem item in module.Items)
                {
                    if (item.IsCommentOnly)
                    {
                        continue;
                    }

                    try
                    {
                        _epService.CompileEPL(item.Expression);
                    }
                    catch (Exception ex)
                    {
                        exceptionsX.Add(new DeploymentItemException(ex.Message, item.Expression, ex, item.LineNumber));
                    }
                }

                if (!exceptionsX.IsEmpty())
                {
                    throw BuildException("Compilation failed", module, exceptionsX);
                }
            }

            if (options.IsCompileOnly)
            {
                return(null);
            }

            var exceptions           = new List <DeploymentItemException>();
            var statementNames       = new List <DeploymentInformationItem>();
            var statements           = new List <EPStatement>();
            var eventTypesReferenced = new HashSet <string>();

            foreach (ModuleItem item in module.Items)
            {
                if (item.IsCommentOnly)
                {
                    continue;
                }

                string statementName = null;
                Object userObject    = null;
                if (options.StatementNameResolver != null || options.StatementUserObjectResolver != null)
                {
                    var ctx = new StatementDeploymentContext(item.Expression, module, item, deploymentId);
                    statementName = options.StatementNameResolver != null
                        ? options.StatementNameResolver.GetStatementName(ctx)
                        : null;

                    userObject = options.StatementUserObjectResolver != null
                        ? options.StatementUserObjectResolver.GetUserObject(ctx)
                        : null;
                }

                try
                {
                    EPStatement stmt;
                    if (options.IsolatedServiceProvider == null)
                    {
                        stmt = _epService.CreateEPL(item.Expression, statementName, userObject);
                    }
                    else
                    {
                        EPServiceProviderIsolated unit =
                            _statementIsolationService.GetIsolationUnit(options.IsolatedServiceProvider, -1);
                        stmt = unit.EPAdministrator.CreateEPL(item.Expression, statementName, userObject);
                    }
                    statementNames.Add(new DeploymentInformationItem(stmt.Name, stmt.Text));
                    statements.Add(stmt);

                    string[] types = _statementEventTypeRef.GetTypesForStatementName(stmt.Name);
                    if (types != null)
                    {
                        eventTypesReferenced.AddAll(types);
                    }
                }
                catch (EPException ex)
                {
                    exceptions.Add(new DeploymentItemException(ex.Message, item.Expression, ex, item.LineNumber));
                    if (options.IsFailFast)
                    {
                        break;
                    }
                }
            }

            if (!exceptions.IsEmpty())
            {
                if (options.IsRollbackOnFail)
                {
                    Log.Debug("Rolling back intermediate statements for deployment");
                    foreach (EPStatement stmt in statements)
                    {
                        try
                        {
                            stmt.Dispose();
                        }
                        catch (Exception ex)
                        {
                            Log.Debug("Failed to destroy created statement during rollback: " + ex.Message, ex);
                        }
                    }
                    EPLModuleUtil.UndeployTypes(
                        eventTypesReferenced, _statementEventTypeRef, _eventAdapterService, _filterService);
                }
                string text = "Deployment failed";
                if (options.IsValidateOnly)
                {
                    text = "Validation failed";
                }
                throw BuildException(text, module, exceptions);
            }

            if (options.IsValidateOnly)
            {
                Log.Debug("Rolling back created statements for validate-only");
                foreach (EPStatement stmt in statements)
                {
                    try
                    {
                        stmt.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Log.Debug("Failed to destroy created statement during rollback: " + ex.Message, ex);
                    }
                }
                EPLModuleUtil.UndeployTypes(
                    eventTypesReferenced, _statementEventTypeRef, _eventAdapterService, _filterService);
                return(null);
            }

            DeploymentInformationItem[] deploymentInfoArr = statementNames.ToArray();
            var desc = new DeploymentInformation(
                deploymentId, module, addedDate, DateTimeEx.GetInstance(_timeZone), deploymentInfoArr,
                DeploymentState.DEPLOYED);

            _deploymentStateService.AddUpdateDeployment(desc);

            if (Log.IsDebugEnabled)
            {
                Log.Debug("Module " + module + " was successfully deployed.");
            }
            return(new DeploymentResult(desc.DeploymentId, statements.AsReadOnlyList(), imports));
        }
Esempio n. 11
0
        private async Task SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabaseWithOptions(string sourceScript, string targetScript, DeploymentOptions nodiffOption, DeploymentOptions shouldDiffOption)
        {
            var       result   = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, sourceScript, "SchemaCompareSource");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, targetScript, "SchemaCompareTarget");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SchemaCompareTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                string sourceDacpacFilePath = SchemaCompareTestUtils.CreateDacpac(sourceDb);

                SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
                SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();

                sourceInfo.EndpointType    = SchemaCompareEndpointType.Dacpac;
                sourceInfo.PackageFilePath = sourceDacpacFilePath;
                targetInfo.EndpointType    = SchemaCompareEndpointType.Database;
                targetInfo.DatabaseName    = targetDb.DatabaseName;

                var schemaCompareParams1 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = nodiffOption,
                };

                SchemaCompareOperation schemaCompareOperation1 = new SchemaCompareOperation(schemaCompareParams1, result.ConnectionInfo, result.ConnectionInfo);
                schemaCompareOperation1.Execute(TaskExecutionMode.Execute);

                Assert.True(schemaCompareOperation1.ComparisonResult.IsValid);
                Assert.True(schemaCompareOperation1.ComparisonResult.IsEqual);
                Assert.NotNull(schemaCompareOperation1.ComparisonResult.Differences);

                // generate script
                var generateScriptParams1 = new SchemaCompareGenerateScriptParams
                {
                    TargetDatabaseName = targetDb.DatabaseName,
                    OperationId        = schemaCompareOperation1.OperationId,
                };

                SchemaCompareGenerateScriptOperation generateScriptOperation1 = new SchemaCompareGenerateScriptOperation(generateScriptParams1, schemaCompareOperation1.ComparisonResult);

                try
                {
                    generateScriptOperation1.Execute(TaskExecutionMode.Script);
                    Assert.True(false); //fail if it reaches here
                }
                catch (Exception ex)
                {
                    // validate script generation failed because there were no differences
                    Assert.False(generateScriptOperation1.ScriptGenerationResult.Success);
                    Assert.Equal("Performing script generation is not possible for this comparison result.", generateScriptOperation1.ScriptGenerationResult.Message);
                    Assert.Equal("Performing script generation is not possible for this comparison result.", ex.Message);
                }

                var schemaCompareParams2 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = shouldDiffOption,
                };

                SchemaCompareOperation schemaCompareOperation2 = new SchemaCompareOperation(schemaCompareParams2, result.ConnectionInfo, result.ConnectionInfo);
                schemaCompareOperation2.Execute(TaskExecutionMode.Execute);

                Assert.True(schemaCompareOperation2.ComparisonResult.IsValid);
                Assert.False(schemaCompareOperation2.ComparisonResult.IsEqual);
                Assert.NotNull(schemaCompareOperation2.ComparisonResult.Differences);

                // generate script
                var generateScriptParams2 = new SchemaCompareGenerateScriptParams
                {
                    TargetDatabaseName = targetDb.DatabaseName,
                    OperationId        = schemaCompareOperation1.OperationId,
                };

                SchemaCompareGenerateScriptOperation generateScriptOperation2 = new SchemaCompareGenerateScriptOperation(generateScriptParams2, schemaCompareOperation2.ComparisonResult);
                generateScriptOperation2.Execute(TaskExecutionMode.Script);

                // validate script generation succeeded
                Assert.True(generateScriptOperation2.ScriptGenerationResult.Success);
                Assert.True(!string.IsNullOrEmpty(generateScriptOperation2.ScriptGenerationResult.Script), "Should have differences");
                // cleanup
                SchemaCompareTestUtils.VerifyAndCleanup(sourceDacpacFilePath);
            }
            finally
            {
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Starts the controller.
        /// </summary>
        public void Start()
        {
            if (!string.IsNullOrEmpty(this.address) && !string.IsNullOrEmpty(this.port))
            {
                return;
            }

            Device device = this.FindDevice();

            if (device == null)
            {
                throw new WindowsPhoneDriverException(string.Format(CultureInfo.InvariantCulture, "Found no matching devices for name '{0}'", this.deviceName));
            }
            else
            {
                this.SendStatusUpdate("Connecting to device {0}.", device.Name);

                List <string> fileNames = new List <string>();
                if (!this.appPath.Equals(string.Empty))
                {
                    this.assemblyDirectory = Path.GetDirectoryName(this.appPath);
                    fileNames.Add(Path.GetFileName(this.appPath));
                }
                else
                {
                    this.assemblyDirectory = Path.GetDirectoryName(this.GetType().Assembly.Location);
                    fileNames.Add("WindowsPhoneDriverBrowser.xap");
                }
                string path = GetPackagePath(this.assemblyDirectory, fileNames);

                this.SendStatusUpdate("path: " + path);
                ApplicationArchiveInfo appInfo = ApplicationArchiveInfo.ReadApplicationInfo(path);

                Guid   applicationId = appInfo.ApplicationId.Value;
                string iconPath      = appInfo.ExtractIconFile();

                bool isConnectedToDevice = false;
                try
                {
                    device.Connect();
                    isConnectedToDevice = device.IsConnected();
                }
                catch (SmartDeviceException ex)
                {
                    this.SendStatusUpdate("WARNING! Exception encountered when connecting to device. HRESULT: {0:X}, message: {1}", ex.HResult, ex.Message);
                    System.Threading.Thread.Sleep(500);
                }

                if (!isConnectedToDevice)
                {
                    // TODO: Create connection mitigation routine.
                    this.SendStatusUpdate("WARNING! Was unable to connect to device!");
                }
                else
                {
                    if (path.EndsWith("xap"))
                    {
                        if (device.IsApplicationInstalled(applicationId))
                        {
                            this.SendStatusUpdate("Application already installed. Uninstalling..");
                            device.GetApplication(applicationId).Uninstall();
                        }
                        this.SendStatusUpdate("Installing application {0}.", path);
                        this.browserApplication = device.InstallApplication(applicationId, applicationId, "WindowsPhoneDriverBrowser", iconPath, path);
                    }
                    else
                    {
                        if (device.IsApplicationInstalled(applicationId))
                        {
                            this.SendStatusUpdate("Application already installed. Uninstalling..");
                            device.GetApplication(applicationId).Uninstall();
                        }
                        this.SendStatusUpdate("Installing application {0}.", path);
                        IAppManifestInfo  manifestInfo      = Utils.ReadAppManifestInfoFromPackage(this.appPath);
                        DeploymentOptions deploymentOptions = DeploymentOptions.None;
                        var devices    = Utils.GetDevices();
                        var utilDevice = devices.FirstOrDefault(d => d.ToString() == "Device");
                        Utils.InstallApplication(utilDevice, manifestInfo, deploymentOptions, this.appPath);
                    }
                }

                File.Delete(iconPath);
            }
        }