public void SetUp()
        {
            if (!IntegrationTestOptions.SqlServerCe.IsEnabled)
            {
                Assert.Ignore();
            }

            if (!HostUtilities.ProbeSqlServerCeBehavior())
            {
                Assert.Ignore("SQL Server CE binaries not found");
            }

            _tempDataDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
            Directory.CreateDirectory(_tempDataDirectory);
            AppDomain.CurrentDomain.SetData("DataDirectory", _tempDataDirectory);

            var csb = new SqlCeConnectionStringBuilder(IntegrationTestOptions.SqlServerCe.ConnectionString);

            DatabaseFilename = HostUtilities.ReplaceDataDirectory(csb.DataSource);
            RecreateDatabase();
            Connection = new SqlCeConnection(IntegrationTestOptions.SqlServerCe.ConnectionString);
            Processor  = new SqlServerCeProcessor(Connection, new SqlServerCeGenerator(), new TextWriterAnnouncer(TestContext.Out), new ProcessorOptions(), new SqlServerCeDbFactory());
            Connection.Open();
            Processor.BeginTransaction();
        }
Example #2
0
        /// <summary>
        /// Auxiliar used in GetValue methods since the list does not deal well with unlimited sized lines.
        /// </summary>
        /// <param name="src">Source string.</param>
        /// <returns>The source string limited in the number of lines.</returns>
        internal static object LimitString(object src)
        {
            if (!(src is string srcString))
            {
                return(src);
            }

            return(HostUtilities.GetMaxLines(srcString, 10));
        }
Example #3
0
        private void LoadProfile()
        {
            var profileCommand = HostUtilities.GetProfileCommands(ShellId);

            foreach (var pc in profileCommand)
            {
                InvokeCommand(pc);
            }
        }
Example #4
0
        internal static object LimitString(object src)
        {
            string source = src as string;

            if (source == null)
            {
                return(src);
            }
            return(HostUtilities.GetMaxLines(source, 10));
        }
Example #5
0
        private static void LoadProfilesIntoRunspace(Runspace runspace)
        {
            using (var powerShell = System.Management.Automation.PowerShell.Create()) {
                powerShell.Runspace = runspace;

                PSCommand[] profileCommands = HostUtilities.GetProfileCommands(ProfilePrefix);
                foreach (PSCommand command in profileCommands)
                {
                    powerShell.Commands = command;
                    powerShell.AddCommand("out-default");
                    powerShell.Invoke();
                }
            }
        }
        public void SetUp()
        {
            _tempDataDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
            Directory.CreateDirectory(_tempDataDirectory);
            AppDomain.CurrentDomain.SetData("DataDirectory", _tempDataDirectory);

            var csb = new SqlCeConnectionStringBuilder(IntegrationTestOptions.SqlServerCe.ConnectionString);

            DatabaseFilename = HostUtilities.ReplaceDataDirectory(csb.DataSource);
            RecreateDatabase();

            ServiceScope = ServiceProvider.CreateScope();
            Processor    = ServiceScope.ServiceProvider.GetRequiredService <SqlServerCeProcessor>();
        }
        public void ClassSetUp()
        {
            if (!IntegrationTestOptions.SqlServerCe.IsEnabled)
            {
                Assert.Ignore();
            }

            if (!HostUtilities.ProbeSqlServerCeBehavior())
            {
                Assert.Ignore("SQL Server CE binaries not found");
            }

            var serivces = ServiceCollectionExtensions.CreateServices()
                           .ConfigureRunner(r => r.AddSqlServerCe())
                           .AddScoped <IConnectionStringReader>(
                _ => new PassThroughConnectionStringReader(IntegrationTestOptions.SqlServerCe.ConnectionString));

            ServiceProvider = serivces.BuildServiceProvider();
        }
        private void Init(JetProcessor processor, IEnumerable <string> columnDefinitions)
        {
            Connection  = processor.Connection;
            Transaction = processor.Transaction;

            var csb        = new OleDbConnectionStringBuilder(Connection.ConnectionString);
            var dbFileName = HostUtilities.ReplaceDataDirectory(csb.DataSource);

            csb.DataSource = dbFileName;

            if (!File.Exists(dbFileName))
            {
                var connString = csb.ConnectionString;
                var type       = Type.GetTypeFromProgID("ADOX.Catalog");
                if (type != null)
                {
                    dynamic cat = Activator.CreateInstance(type);
                    cat.Create(connString);
                }
            }

            Create(columnDefinitions);
        }
Example #9
0
        public void SetUp()
        {
            if (!HostUtilities.TryGetJetCatalogType(out var jetCatalogType))
            {
                Assert.Ignore("ADOX.Catalog could not be found - running from .NET Core?");
            }

            _tempDataDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
            Directory.CreateDirectory(_tempDataDirectory);
            AppDomain.CurrentDomain.SetData("DataDirectory", _tempDataDirectory);

            var csb = new OleDbConnectionStringBuilder(IntegrationTestOptions.Jet.ConnectionString);

            csb.DataSource = DatabaseFilename = HostUtilities.ReplaceDataDirectory(csb.DataSource);

            try
            {
                RecreateDatabase(jetCatalogType, csb.ConnectionString);
            }
            catch (Exception ex)
            {
                try
                {
                    Directory.Delete(_tempDataDirectory);
                }
                catch
                {
                    // Ignore errors
                }

                TestContext.Error.WriteLine(ex.ToString());
                Assert.Ignore(ex.Message);
            }

            ServiceScope = ServiceProvider.CreateScope();
            Processor    = ServiceScope.ServiceProvider.GetRequiredService <JetProcessor>();
        }
Example #10
0
 private static void LoadProfilesIntoRunspace(RunspaceDispatcher runspace)
 {
     PSCommand[] profileCommands = HostUtilities.GetProfileCommands(ProfilePrefix);
     runspace.InvokeCommands(profileCommands);
 }
Example #11
0
        static async Task Main(string[] args)
        {
            var host = HostUtilities.BuildAndRunHost(args, x => x.AddSingleton <IProcessUtility, ProcessUtility>().AddSingleton <IComparer <string>, WinStringComparer>());

            var logger     = host.Services.GetService <ILogger <Program> >();
            var sourcePath = args?.Length == 1 ? Path.GetFullPath(args[0]) : AppDomain.CurrentDomain.BaseDirectory;

            _ = sourcePath ?? throw new InvalidOperationException("sourcePath is null");
            if (!Directory.Exists(sourcePath))
            {
                throw new InvalidOperationException($"Directory does not exist: {sourcePath}");
            }

            var destinationPath = Path.Combine(sourcePath, ProjectBuiltinNugetDirectoryName);

            if (!Directory.Exists(destinationPath))
            {
                Directory.CreateDirectory(destinationPath);
            }

            var csprojFiles        = Directory.EnumerateFiles(sourcePath, "*.csproj", SearchOption.AllDirectories);
            var packages           = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            var nugetCacheRootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages");
            var processUtility     = host.Services.GetService <IProcessUtility>();
            var tempPath           = PathExtensions.CreateTempDirectory();

            logger.LogTrace("Using temp path {TempPath}...", tempPath);

            async Task CopyAllPackageDependenciesAsync(string packageFilePath)
            {
                await NugetUtilities.ExtractPackageAndApplyActionAsync(
                    packageFilePath,
                    processUtility ?? throw new InvalidOperationException("processUtility is null"),
                    tempPath ?? throw new InvalidOperationException("tempPath is null"),
                    async (dllFilePath, nuspecFilePath) =>
                {
                    var dependencies = await GetScarPackageReferencesFromNuspecFileAsync(nuspecFilePath).ConfigureAwait(false);
                    foreach (var nugetPackageInfo in dependencies)
                    {
                        logger.LogTrace("Trying to clone {PackageName} which is a dependency of {DependentPackageName}...", nugetPackageInfo.ToString(), NugetUtilities.ParseNugetPackageInfoForPath(packageFilePath)?.ToString());
                        await ClonePackageIfExistsInCacheAsync(
                            logger ?? throw new InvalidOperationException("logger is null"),
                            packages ?? throw new InvalidOperationException("packages is null"),
                            nugetPackageInfo,
                            nugetCacheRootPath ?? throw new InvalidOperationException("nugetCacheRootPath is null"),
                            destinationPath ?? throw new InvalidOperationException("destinationPath is null"),
                            CopyAllPackageDependenciesAsync)
                        .ConfigureAwait(false);
                    }
                })
                .ConfigureAwait(false);
            }

            var tasks = csprojFiles.Select(
                async csprojFilePath =>
            {
                var scarPackageReferences = await GetScarPackageReferencesFromProjectFileAsync(csprojFilePath).ConfigureAwait(false);
                foreach (var nugetPackageInfo in scarPackageReferences)
                {
                    logger.LogTrace("Trying to clone {PackageName}...", nugetPackageInfo.ToString());
                    await ClonePackageIfExistsInCacheAsync(logger, packages, nugetPackageInfo, nugetCacheRootPath, destinationPath, CopyAllPackageDependenciesAsync).ConfigureAwait(false);
                }
            });

            await Task.WhenAll(tasks).ConfigureAwait(false);

            DeleteNonExistingPackages(logger, packages, destinationPath);

            var fileNameComparer = host.Services.GetService <IComparer <string> >();

            DeleteOutdatedPackagesFromCache(logger, nugetCacheRootPath, fileNameComparer);
            DeleteOutdatedPackagesFromCache(logger, ScarLocalNugetPath, fileNameComparer);
            Directory.Delete(tempPath, true);
            logger.LogInformation("Deleted {TempPath}", tempPath);
        }
Example #12
0
        /// <summary>
        /// Implements the BeginProcessing() method for get-help command.
        /// </summary>
        protected override void BeginProcessing()
        {
            _timer.Start();

            if (!Online.IsPresent && UpdatableHelpSystem.ShouldPromptToUpdateHelp() && HostUtilities.IsProcessInteractive(MyInvocation) && HasInternetConnection())
            {
                if (ShouldContinue(HelpDisplayStrings.UpdateHelpPromptBody, HelpDisplayStrings.UpdateHelpPromptTitle))
                {
                    System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand("Update-Help").Invoke();
#if LEGACYTELEMETRY
                    _updatedHelp = true;
#endif
                }

                UpdatableHelpSystem.SetDisablePromptToUpdateHelp();
            }
        }
Example #13
0
        static async Task Main(string[] args)
        {
            var host = HostUtilities.BuildAndRunHost(
                args,
                x => x.AddSingleton <IProcessUtility, ProcessUtility>().AddSingleton <IFileHasher, FileHasher>().AddSingleton <IComparer <string>, WinStringComparer>());

            var sourceDirectoryPath = args?.Length == 1 ? args[0] : AppDomain.CurrentDomain.BaseDirectory;
            var logger = host.Services.GetService <ILogger <Program> >();

            logger.LogTrace("Processing packages in {SourceDirectoryPath}...", sourceDirectoryPath);
            _ = sourceDirectoryPath ?? throw new InvalidOperationException("sourcePath is null");
            if (!Directory.Exists(sourceDirectoryPath))
            {
                throw new InvalidOperationException($"Directory {sourceDirectoryPath} does not exist");
            }

            var orderedNupkgFiles = Directory.GetFiles(sourceDirectoryPath, "*.nupkg", SearchOption.AllDirectories).OrderByDescending(x => x, host.Services.GetService <IComparer <string> >()).ToArray();

            if (orderedNupkgFiles.Length >= 2)
            {
                var    lastTwoPackages = orderedNupkgFiles.Take(2).ToArray();
                var    lastPackagePath = lastTwoPackages[0];
                var    previousPackagePath = lastTwoPackages[1];
                var    processUtility = host.Services.GetService <IProcessUtility>();
                var    fileHasher = host.Services.GetService <IFileHasher>();
                string?previousPackageNuspecText = null, lastPackageNuspecText = null;
                byte[]? lastPackageDllHash = null, previousPackageDllHash = null;

                async Task ExtractLastPackageDetails(string dllFilePath, string nuspecFilePath)
                {
                    var(dllHash, nuspecText) = await ExtractPackageHashAndNuspecTextWithoutVersionAsync(
                        fileHasher ?? throw new InvalidOperationException(nameof(fileHasher)),
                        dllFilePath,
                        nuspecFilePath)
                                               .ConfigureAwait(false);

                    lastPackageDllHash    = dllHash;
                    lastPackageNuspecText = nuspecText;
                }

                async Task ExtractPreviousPackageDetails(string dllFilePath, string nuspecFilePath)
                {
                    var(dllHash, nuspecText) = await ExtractPackageHashAndNuspecTextWithoutVersionAsync(
                        fileHasher ?? throw new InvalidOperationException(nameof(fileHasher)),
                        dllFilePath,
                        nuspecFilePath)
                                               .ConfigureAwait(false);

                    previousPackageDllHash    = dllHash;
                    previousPackageNuspecText = nuspecText;
                }

                await Task.WhenAll(
                    NugetUtilities.ExtractPackageAndApplyActionAsync(lastPackagePath, processUtility, sourceDirectoryPath, ExtractLastPackageDetails),
                    NugetUtilities.ExtractPackageAndApplyActionAsync(previousPackagePath, processUtility, sourceDirectoryPath, ExtractPreviousPackageDetails))
                .ConfigureAwait(false);

                var lastPackageName     = NugetUtilities.ParseNugetPackageInfoForPath(lastPackagePath)?.ToString();
                var previousPackageName = NugetUtilities.ParseNugetPackageInfoForPath(previousPackagePath)?.ToString();

                var dllHashesAreEqual = lastPackageDllHash.SequenceEqual(previousPackageDllHash);
                var nuspecDifference  = CompareStrings(lastPackageNuspecText, previousPackageNuspecText);

                var packagesAreEqual = dllHashesAreEqual && nuspecDifference == 0;
                if (!packagesAreEqual)
                {
                    logger.LogInformation(
                        @"Nuget packages {LastPackageName} is different from previous {PreviousPackageName} Nuspec: {NuspecDifference}, Dll: {DllsAreEqual}
Current dll hash: {CurrentDllHash}
Previous dll hash: {PreviousDllHash}
Current nuspec: {CurrentNuspec}
Previous nuspec: {PreviousNuspec}",
                        lastPackageName,
                        previousPackageName,
                        nuspecDifference,
                        !dllHashesAreEqual,
                        lastPackageDllHash?.GetHashString(),
                        previousPackageDllHash?.GetHashString(),
                        lastPackageNuspecText,
                        previousPackageNuspecText);
                    await PushNugetAsync(logger, processUtility, lastPackagePath).ConfigureAwait(false);
                }
                else
                {
                    logger.LogInformation("Nuget package {LastPackageName} is identical to previous {PreviousPackageName}. Push is skipped", lastPackageName, previousPackageName);
                }

                // Leave 2 last files
                DeleteFiles(orderedNupkgFiles.Skip(2), logger);
            }
            else if (orderedNupkgFiles.Length == 1)
            {
                var lastPackagePath = orderedNupkgFiles.Single();
                logger.LogInformation("There is only one nuget package {LastPackageName}", NugetUtilities.ParseNugetPackageInfoForPath(lastPackagePath)?.ToString());
                var processUtility = host.Services.GetService <IProcessUtility>();
                await PushNugetAsync(logger, processUtility, lastPackagePath).ConfigureAwait(false);
            }
            else
            {
                logger.LogInformation("Nothing to compare");
            }
        }
Example #14
0
 protected override void BeginProcessing()
 {
     if ((!this.Online.IsPresent && UpdatableHelpSystem.ShouldPromptToUpdateHelp()) && (HostUtilities.IsProcessInteractive(base.MyInvocation) && this.HasInternetConnection()))
     {
         if (base.ShouldContinue(HelpDisplayStrings.UpdateHelpPromptBody, HelpDisplayStrings.UpdateHelpPromptTitle))
         {
             PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand("Update-Help").Invoke();
         }
         UpdatableHelpSystem.SetDisablePromptToUpdateHelp();
     }
 }
        /// <summary>
        /// Prompt for credentials.
        /// </summary>
        /// <param name="userName"> name of the user whose creds are to be prompted for. If set to null or empty string, the function will prompt for user name first. </param>
        ///
        /// <param name="targetName"> name of the target for which creds are being collected </param>
        ///
        /// <param name="message"> message to be displayed. </param>
        ///
        /// <param name="caption"> caption for the message. </param>
        ///
        /// <param name="allowedCredentialTypes"> what type of creds can be supplied by the user </param>
        ///
        /// <param name="options"> options that control the cred gathering UI behavior </param>
        ///
        /// <returns> PSCredential object, or null if input was cancelled (or if reading from stdin and stdin at EOF)</returns>
        ///

        public override PSCredential PromptForCredential(
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options)
        {
            if (!PromptUsingConsole())
            {
                IntPtr mainWindowHandle = GetMainWindowHandle();
                return(HostUtilities.CredUIPromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options, mainWindowHandle));
            }
            else
            {
                PSCredential cred           = null;
                SecureString password       = null;
                string       userPrompt     = null;
                string       passwordPrompt = null;

                if (!string.IsNullOrEmpty(caption))
                {
                    // Should be a skin lookup

                    WriteLineToConsole();
                    WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption));
                    WriteLineToConsole();
                }

                if (!string.IsNullOrEmpty(message))
                {
                    WriteLineToConsole(WrapToCurrentWindowWidth(message));
                }

                if (string.IsNullOrEmpty(userName))
                {
                    userPrompt = ConsoleHostUserInterfaceSecurityResources.PromptForCredential_User;

                    //
                    // need to prompt for user name first
                    //
                    do
                    {
                        WriteToConsole(userPrompt, true);
                        userName = ReadLine();
                        if (userName == null)
                        {
                            return(null);
                        }
                    }while (userName.Length == 0);
                }

                passwordPrompt = StringUtil.Format(ConsoleHostUserInterfaceSecurityResources.PromptForCredential_Password, userName
                                                   );

                //
                // now, prompt for the password
                //
                WriteToConsole(passwordPrompt, true);
                password = ReadLineAsSecureString();
                if (password == null)
                {
                    return(null);
                }
                WriteLineToConsole();

                cred = new PSCredential(userName, password);

                return(cred);
            }
        }