Exemplo n.º 1
0
        public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args)
        {
            switch (level)
            {
            case LogLevel.Error:
            case LogLevel.Fatal:
                _cmdlet.WriteWarning(string.Format(format, args));
                return;

            case LogLevel.Warning:
                _cmdlet.WriteWarning(string.Format(format, args));
                return;

            case LogLevel.Information:
                _cmdlet.WriteObject(string.Format(format, args));
                return;

            case LogLevel.Verbose:
                _cmdlet.WriteVerbose(string.Format(format, args));
                return;

            case LogLevel.Debug:
                _cmdlet.WriteDebug(string.Format(format, args));
                return;

            default:
                throw new InvalidOperationException("Invalid log level.");
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Execute the given cmdlet in powershell with the given parameters after injecting the given exception.  It is expected that the cmdlet has a runtime that can be used for receiving output
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cmdlet">The cmdlet to execute</param>
        /// <param name="name">The name of the cmdlet</param>
        /// <param name="exception">The exception to inject into the error stream</param>
        /// <param name="cmdletParameters">The parameters to pass to the cmdlet on the pipeline</param>
        public static void ExecuteCmdletWithExceptionInPipeline <T>(this PSCmdlet cmdlet, string name, Exception exception, params KeyValuePair <string, object>[] cmdletParameters)
        {
            List <T> output = new List <T>();

            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace))
            {
                var info = new CmdletInfo(name, cmdlet.GetType());
                powershell.AddCommand("Write-Error");
                powershell.AddParameter("Exception", exception);
                powershell.Invoke();
                powershell.Commands.Clear();
                powershell.AddCommand(info);
                foreach (var pair in cmdletParameters)
                {
                    if (pair.Value == null)
                    {
                        powershell.AddParameter(pair.Key);
                    }
                    else
                    {
                        powershell.AddParameter(pair.Key, pair.Value);
                    }
                }
                Collection <T> result = powershell.Invoke <T>();
                powershell.Streams.Error.ForEach(cmdlet.WriteError);
                powershell.Streams.Debug.ForEach(d => cmdlet.WriteDebug(d.Message));
                powershell.Streams.Verbose.ForEach(v => cmdlet.WriteWarning(v.Message));
                powershell.Streams.Warning.ForEach(w => cmdlet.WriteWarning(w.Message));

                if (result != null && result.Count > 0)
                {
                    result.ForEach(r => cmdlet.WriteObject(r));
                }
            }
        }
Exemplo n.º 3
0
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            if (Domain == null)
            {
                callingCmdlet.WriteWarning("No valid domain has been provided.");

                return;
            }

            if (!Domain.CheckIsValid())
            {
                callingCmdlet.WriteWarning("An invalid domain object has been provided.");

                return;
            }

            Model.IDatabaseInfo dbInfo = Domain;

            using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(dbInfo.ConnectionString))
            {
                dataContext.CommandTimeout = 180;
                if (MapId != Guid.Empty)
                {
                    /// Find maps by ID.
                    ///

                    Model.Map map = GetMapById(dataContext, MapId);

                    callingCmdlet.WriteObject(map);
                }
                else if (!string.IsNullOrEmpty(MapName))
                {
                    /// Find maps by name.
                    ///

                    List <Model.Map> maps = GetMapsByName(dataContext, MapName);

                    callingCmdlet.WriteObject(maps, true);
                }
                else
                {
                    /// Fine all maps.
                    ///

                    List <Model.Map> maps = GetAllMaps(dataContext);

                    callingCmdlet.WriteObject(maps, true);
                }
            }
        }
Exemplo n.º 4
0
 public static void CheckForRegisteredVaults(PSCmdlet cmdlet)
 {
     if (RegisteredVaultCache.VaultExtensions.Count == 0)
     {
         cmdlet.WriteWarning(NoVaultRegistered);
     }
 }
Exemplo n.º 5
0
        internal static void WriteFormattedWarning(PSCmdlet cmdlet, string message)
        {
            if (cmdlet.Host.Name == "ConsoleHost")
            {
                var messageLines = new List <string>();
                messageLines.AddRange(message.Split(new[] { '\n' }));
                var wrappedText = new List <string>();
                foreach (var messageLine in messageLines)
                {
                    wrappedText.AddRange(WordWrap(messageLine, cmdlet.Host.UI.RawUI.MaxWindowSize.Width - 2));
                }

                var notificationColor = "\x1B[7m";
                var resetColor        = "\x1B[0m";

                var outMessage = string.Empty;
                foreach (var wrappedLine in wrappedText)
                {
                    var lineToAdd = wrappedLine.PadRight(cmdlet.Host.UI.RawUI.MaxWindowSize.Width - 2);
                    outMessage += $"{notificationColor} {lineToAdd} {resetColor}\n";
                }
                cmdlet.Host.UI.WriteLine($"{notificationColor}\n{outMessage}{resetColor}\n");
            }
            else
            {
                cmdlet.WriteWarning(message);
            }
        }
Exemplo n.º 6
0
        internal void AddBinding(PSVariable variable, EventInfo eventInfo, string queueName)
        {
            Guid bindindID = Guid.NewGuid();

            lock (s_bindings)
            {
                s_bindings.Add(bindindID, new WeakReference(variable));
                WriteDebug("Added PSVariable tracking entry.");
            }

            try
            {
                Delegate handler = PSEventHelper.BindEventSink(variable, eventInfo, bindindID, queueName);
                WriteDebug("Event sink bound.");

                PSEventBindingAttribute attr = new PSEventBindingAttribute(eventInfo.Name, handler, bindindID);
                variable.Attributes.Add(attr);
                WriteDebug("Added binding attribute to PSVariable.");
            }
            catch (Exception ex)
            {
                m_command.WriteWarning(String.Format("Error binding to {0} on {1}: {2}", eventInfo.Name, variable.Name, ex.Message));

                s_bindings.Remove(bindindID);
                WriteDebug("Removed PSVariable tracking entry.");
                throw;
            }
        }
        internal static void UpdateConfig(PSCmdlet cmdlet, string[] name, ConfigScope scope, bool enable)
        {
            IEnumerable <WildcardPattern> namePatterns = SessionStateUtilities.CreateWildcardsFromStrings(name, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
            GetExperimentalFeatureCommand getExperimentalFeatureCommand = new GetExperimentalFeatureCommand();

            getExperimentalFeatureCommand.Context = cmdlet.Context;
            bool foundFeature = false;

            foreach (ExperimentalFeature feature in getExperimentalFeatureCommand.GetAvailableExperimentalFeatures(namePatterns))
            {
                foundFeature = true;
                if (!cmdlet.ShouldProcess(feature.Name))
                {
                    return;
                }

                PowerShellConfig.Instance.SetExperimentalFeatures(scope, feature.Name, enable);
            }

            if (!foundFeature)
            {
                string errMsg = string.Format(CultureInfo.InvariantCulture, ExperimentalFeatureStrings.ExperimentalFeatureNameNotFound, name);
                cmdlet.WriteError(new ErrorRecord(new ItemNotFoundException(errMsg), "ItemNotFoundException", ErrorCategory.ObjectNotFound, name));
                return;
            }

            cmdlet.WriteWarning(ExperimentalFeatureStrings.ExperimentalFeaturePending);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Gets a sql auth connection context.
        /// </summary>
        /// <param name="cmdlet">The cmdlet requesting the context</param>
        /// <param name="serverName">The name of the server to connect to</param>
        /// <param name="manageUrl">The manage url of the server</param>
        /// <param name="credentials">The credentials to connect to the server</param>
        /// <param name="sessionActivityId">The session activity ID</param>
        /// <param name="managementServiceUri">The URI for management service</param>
        /// <returns>The connection context</returns>
        public static IServerDataServiceContext GetContext(
            PSCmdlet cmdlet,
            string serverName,
            Uri manageUrl,
            SqlAuthenticationCredentials credentials,
            Guid sessionActivityId,
            Uri managementServiceUri)
        {
            Version version;

            // If a version was specified (by tests) us it.
            if (sqlVersion == SqlVersion.v2)
            {
                version = new Version(11, 0);
            }
            else if (sqlVersion == SqlVersion.v12)
            {
                version = new Version(12, 0);
            }
            else // If no version specified, determine the version by querying the server.
            {
                version = GetVersion(manageUrl, credentials);
            }
            sqlVersion = SqlVersion.None;

            IServerDataServiceContext context = null;

            if (version.Major >= 12)
            {
                context = new TSqlConnectionContext(
                    sessionActivityId,
                    manageUrl.Host,
                    credentials,
                    serverName);
            }
            else
            {
                context = ServerDataServiceSqlAuth.Create(
                    managementServiceUri,
                    sessionActivityId,
                    credentials,
                    serverName);

                // Retrieve $metadata to verify model version compatibility
                XDocument metadata         = ((ServerDataServiceSqlAuth)context).RetrieveMetadata();
                XDocument filteredMetadata = DataConnectionUtility.FilterMetadataDocument(metadata);
                string    metadataHash     = DataConnectionUtility.GetDocumentHash(filteredMetadata);
                if (!((ServerDataServiceSqlAuth)context).metadataHashes.Any(knownHash => metadataHash == knownHash))
                {
                    cmdlet.WriteWarning(Resources.WarningModelOutOfDate);
                }

                ((ServerDataServiceSqlAuth)context).MergeOption = MergeOption.PreserveChanges;
            }

            return(context);
        }
        public void WriteWarning(string text)
        {
            // Not using Check here because this assembly is very small and without resources
            if (string.IsNullOrWhiteSpace(text))
            {
                throw new ArgumentNullException("text");
            }

            _cmdlet.WriteWarning(text);
        }
Exemplo n.º 10
0
        public OldHtmlDescriptionUpdater(string description, PSCmdlet callingCmdlet)
        {
            try
            {
                var settings = new XmlReaderSettings();
                settings.ProhibitDtd = false;
                callingCmdlet.WriteWarning("Reading HTML descrption");
                using (XmlReader reader = XmlReader.Create(new StringReader(XmlDeclaration + description), settings))
                {
                    reader.ReadToFollowing("div");
                    var id = reader.GetAttribute("id");
                    if (id == "GlymaNodeDescriptionDiv")
                    {
                        callingCmdlet.WriteWarning("GlymaNodeDescriptionDiv div tag found");

                        var widthString = reader.GetAttribute("width");
                        int width;
                        if (widthString != null && int.TryParse(widthString, out width) && width > 0)
                        {
                            Width = width;
                        }

                        var heightString = reader.GetAttribute("height");
                        int height;
                        if (heightString != null && int.TryParse(heightString, out height) && height > 0)
                        {
                            Height = height;
                        }

                        Description = reader.ReadInnerXml();
                    }
                    else
                    {
                        Description = description;
                    }
                }
            }
            catch
            {
                Description = description;
            }
        }
 public void Warning(string message)
 {
     if (_treatWarningsAsErrors)
     {
         Error(message);
     }
     else
     {
         _cmdlet.WriteWarning(message);
     }
 }
Exemplo n.º 12
0
 public static void SafeWriteWarning(this PSCmdlet psCmdlet, string text)
 {
     try
     {
         psCmdlet.WriteWarning(text);
     }
     catch (Exception)
     {
         Trace.WriteLine(text);
     }
 }
Exemplo n.º 13
0
        public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string errorMsg)
        {
            errorMsg = string.Empty;
            // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition
            repoName = repoName.Trim(' ');
            if (String.IsNullOrEmpty(repoName) || repoName.Contains("*"))
            {
                throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace");
            }

            if (repoUri == null || !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile))
            {
                errorMsg = "Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based";
                return(null);
            }

            if (repoCredentialInfo != null)
            {
                bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, cmdletPassedIn);

                if (repoCredentialInfo.Credential != null)
                {
                    if (!isSecretManagementModuleAvailable)
                    {
                        errorMsg = $"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault.";
                        return(null);
                    }
                    else
                    {
                        Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, cmdletPassedIn);
                    }
                }

                if (!isSecretManagementModuleAvailable)
                {
                    cmdletPassedIn.WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo.");
                }
            }

            if (!cmdletPassedIn.ShouldProcess(repoName, "Register repository to repository store"))
            {
                return(null);
            }

            if (!string.IsNullOrEmpty(errorMsg))
            {
                return(null);
            }

            var repo = RepositorySettings.Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, force);

            return(repo);
        }
Exemplo n.º 14
0
        // Check if any of the pkg versions are already installed, if they are we'll remove them from the list of packages to install
        private IEnumerable <PSResourceInfo> FilterByInstalledPkgs(IEnumerable <PSResourceInfo> packages)
        {
            // Create list of installation paths to search.
            List <string> _pathsToSearch = new List <string>();

            // _pathsToInstallPkg will only contain the paths specified within the -Scope param (if applicable)
            // _pathsToSearch will contain all resource package subdirectories within _pathsToInstallPkg path locations
            // e.g.:
            // ./InstallPackagePath1/PackageA
            // ./InstallPackagePath1/PackageB
            // ./InstallPackagePath2/PackageC
            // ./InstallPackagePath3/PackageD
            foreach (var path in _pathsToInstallPkg)
            {
                _pathsToSearch.AddRange(Utils.GetSubDirectories(path));
            }

            var filteredPackages = new Dictionary <string, PSResourceInfo>();

            foreach (var pkg in packages)
            {
                filteredPackages.Add(pkg.Name, pkg);
            }

            GetHelper getHelper = new GetHelper(_cmdletPassedIn);
            // Get currently installed packages.
            // selectPrereleaseOnly is false because even if Prerelease is true we want to include both stable and prerelease, never select prerelease only.
            IEnumerable <PSResourceInfo> pkgsAlreadyInstalled = getHelper.GetPackagesFromPath(
                name: filteredPackages.Keys.ToArray(),
                versionRange: _versionRange,
                pathsToSearch: _pathsToSearch,
                selectPrereleaseOnly: false);

            if (!pkgsAlreadyInstalled.Any())
            {
                return(packages);
            }

            // Remove from list package versions that are already installed.
            foreach (PSResourceInfo pkg in pkgsAlreadyInstalled)
            {
                _cmdletPassedIn.WriteWarning(
                    string.Format("Resource '{0}' with version '{1}' is already installed.  If you would like to reinstall, please run the cmdlet again with the -Reinstall parameter",
                                  pkg.Name,
                                  pkg.Version));

                filteredPackages.Remove(pkg.Name);
                _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase));
            }

            return(filteredPackages.Values.ToArray());
        }
Exemplo n.º 15
0
            public static void Log <T>(T message, LogTarget logTarget, PSCmdlet invokeAll, bool noFileLogging = false)
            {
                string messageStr = null;

                if (message is ErrorRecord)
                {
                    //cast to object and then to ErrorRecord as direct casting is not allowed
                    messageStr = ((ErrorRecord)(object)message).Exception.Message;
                }
                else
                {
                    messageStr = (string)(object)message;
                }
                string logEntry = string.Format("[{0}] {1}", System.DateTime.Now.ToString(datetimeFormat), messageStr);

                switch (logTarget)
                {
                case LogTarget.File:
                    if (!noFileLogging)
                    {
                        using (StreamWriter streamWriter = new StreamWriter(logFile, append: true))
                        {
                            streamWriter.WriteLine(logEntry);
                            streamWriter.Close();
                        };
                    }
                    break;

                case LogTarget.HostVerbose:
                    invokeAll.WriteVerbose(logEntry);
                    break;

                case LogTarget.HostDebug:
                    invokeAll.WriteDebug(logEntry);
                    break;

                case LogTarget.HostError:
                    if (message is ErrorRecord)
                    {
                        invokeAll.WriteError((ErrorRecord)(object)message);
                    }
                    break;

                case LogTarget.HostWarning:
                    invokeAll.WriteWarning(logEntry);
                    break;

                default:

                    break;
                }
            }
Exemplo n.º 16
0
        // Check if any of the pkg versions are already installed, if they are we'll remove them from the list of packages to install
        private List <PSResourceInfo> FilterByInstalledPkgs(List <PSResourceInfo> packages)
        {
            // Package install paths.
            // _pathsToInstallPkg will only contain the paths specified within the -Scope param (if applicable).
            // _pathsToSearch will contain all resource package subdirectories within _pathsToInstallPkg path locations.
            // e.g.:
            // ./InstallPackagePath1/PackageA
            // ./InstallPackagePath1/PackageB
            // ./InstallPackagePath2/PackageC
            // ./InstallPackagePath3/PackageD

            // Get currently installed packages.
            var getHelper             = new GetHelper(_cmdletPassedIn);
            var installedPackageNames = new HashSet <string>(StringComparer.CurrentCultureIgnoreCase);

            foreach (var installedPkg in getHelper.GetInstalledPackages(
                         pkgs: packages,
                         pathsToSearch: _pathsToSearch))
            {
                installedPackageNames.Add(installedPkg.Name);
            }

            if (installedPackageNames.Count is 0)
            {
                return(packages);
            }

            // Return only packages that are not already installed.
            var filteredPackages = new List <PSResourceInfo>();

            foreach (var pkg in packages)
            {
                if (!installedPackageNames.Contains(pkg.Name))
                {
                    // Add packages that still need to be installed.
                    filteredPackages.Add(pkg);
                }
                else
                {
                    // Remove from tracking list of packages to install.
                    _cmdletPassedIn.WriteWarning(
                        string.Format("Resource '{0}' with version '{1}' is already installed.  If you would like to reinstall, please run the cmdlet again with the -Reinstall parameter",
                                      pkg.Name,
                                      pkg.Version));

                    _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase));
                }
            }

            return(filteredPackages);
        }
Exemplo n.º 17
0
 public void WriteWarning(string text)
 {
     if (caller != null)
     {
         caller.WriteWarning(text);
     }
     else
     {
         OnOutput(new CallerProxyEventArgs()
         {
             StreamName = "Warning", Text = text
         });
     }
 }
Exemplo n.º 18
0
        public static void Page <T>(PSCmdlet cmdlet, params T[] items)
        {
            int resultsCount = items.Length;

            if (resultsCount > 0)
            {
                if (cmdlet.PagingParameters.Skip >= (ulong)resultsCount)
                {
                    cmdlet.WriteWarning("No results satisfy the paging parameters");
                }
                else
                {
                    ulong firstNumber = cmdlet.PagingParameters.Skip;
                    ulong lastNumber  = firstNumber
                                        + Math.Min(
                        cmdlet.PagingParameters.First,
                        (ulong)resultsCount - cmdlet.PagingParameters.Skip
                        );
                    for (ulong i = firstNumber; i < lastNumber; i++)
                    {
                        cmdlet.WriteObject(items[i]);
                    }
                }

                if (cmdlet.PagingParameters.IncludeTotalCount)
                {
                    const double accuracy         = 1.0;
                    PSObject     totalCountResult = cmdlet.PagingParameters.NewTotalCount((ulong)resultsCount, accuracy);
                    cmdlet.WriteObject("\r\n\r\n");
                    cmdlet.WriteObject(totalCountResult);
                }
            }
            else
            {
                cmdlet.WriteWarning("No results generated. The query returned 0 items.");
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Write a warning message if the current window size is too small for the specified prediction view.
        /// </summary>
        internal static void WarnWhenWindowSizeTooSmallForView(PredictionViewStyle viewStyle, PSCmdlet cmdlet)
        {
            if (viewStyle != PredictionViewStyle.ListView)
            {
                return;
            }

            var console   = _singleton._console;
            var minWidth  = PredictionListView.MinWindowWidth;
            var minHeight = PredictionListView.MinWindowHeight;

            if (console.WindowWidth < minWidth || console.WindowHeight < minHeight)
            {
                cmdlet.WriteWarning(string.Format(PSReadLineResources.WindowSizeTooSmallForListView, minWidth, minHeight));
            }
        }
Exemplo n.º 20
0
        private bool UpdateMappingToolDatabase(PSCmdlet callingCmdlet)
        {
            using (MappingTool.MappingToolDatabaseDataContext mapDatabaseContext = new MappingTool.MappingToolDatabaseDataContext(MapDatabaseConnectionString))
            {
                var glymaDbVersion = mapDatabaseContext.GetGlymaDbVersion();

                foreach (var row in glymaDbVersion)
                {
                    if (row.Column1 != "v1.5.0r1")
                    {
                        callingCmdlet.WriteWarning(string.Format("This update can only update the v1.5.0r1 mapping tool database to v1.5.0r2 database. The version of this database is {0}.", row.Column1));

                        return(false);
                    }
                }
            }

            using (SqlConnection mapDbConnection = new SqlConnection(MapDatabaseConnectionString))
            {
                mapDbConnection.Open();

                try
                {
                    EmbeddedSqlScript addNewColumnContraints = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r2.UpdateGlymaDbVersion.sql");
                    addNewColumnContraints.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                    return(false);
                }

                try
                {
                    EmbeddedSqlScript addNewColumnsScript = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r2.CreateAuditLogsTable.sql");
                    addNewColumnsScript.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                    return(false);
                }

                mapDbConnection.Close();
            }

            return(true);
        }
Exemplo n.º 21
0
        private bool UpdateTransactionDatabase(PSCmdlet callingCmdlet)
        {
            using (Transaction.TransactionDatabaseDataContext transactionDatabaseContext = new Transaction.TransactionDatabaseDataContext(TransactionDatabaseConnectionString))
            {
                var glymaDbVersion = transactionDatabaseContext.GetGlymaDbVersion();

                foreach (var row in glymaDbVersion)
                {
                    if (row.Column1 != "v1.5.0r2")
                    {
                        callingCmdlet.WriteWarning(string.Format("This update can only update the v1.5.0r2 database to v1.5.0r3 database. The version of this database is {0}.", row.Column1));

                        return(false);
                    }
                }
            }

            using (SqlConnection transactionDbConnection = new SqlConnection(TransactionDatabaseConnectionString))
            {
                transactionDbConnection.Open();

                try
                {
                    EmbeddedSqlScript updateGlymaDbVersion = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r3.UpdateGlymaDbVersion.sql");
                    updateGlymaDbVersion.ExecuteNonQuery(transactionDbConnection);
                }
                catch
                {
                    return(false);
                }

                try
                {
                    EmbeddedSqlScript insertNewTransactionOperations = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r3.InsertTransactionOperations.sql");
                    insertNewTransactionOperations.ExecuteNonQuery(transactionDbConnection);
                }
                catch
                {
                    return(false);
                }

                transactionDbConnection.Close();
            }

            return(true);
        }
        internal static void Break(this PSCmdlet invokedCmdLet)
        {
            while (!Debugger.IsAttached)
            {
                invokedCmdLet.WriteWarning($"Waiting for debugger to attach to process {Process.GetCurrentProcess().Id}");
                for (var i = 0; i < 50; i++)
                {
                    if (Debugger.IsAttached)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                    invokedCmdLet.WriteProgress(new ProgressRecord(0, "Waiting for Debugger",
                        "Waiting for Debugger to attach to process"));
                }
            }

            Debugger.Break();
        }
Exemplo n.º 23
0
        // Check if any of the pkg versions are already installed, if they are we'll remove them from the list of packages to install
        public IEnumerable <PSResourceInfo> FilterByInstalledPkgs(IEnumerable <PSResourceInfo> packagesToInstall)
        {
            List <string> pkgNames = new List <string>();

            foreach (var pkg in packagesToInstall)
            {
                pkgNames.Add(pkg.Name);
            }

            List <string> _pathsToSearch = new List <string>();
            GetHelper     getHelper      = new GetHelper(_cmdletPassedIn);

            // _pathsToInstallPkg will only contain the paths specified within the -Scope param (if applicable)
            // _pathsToSearch will contain all resource package subdirectories within _pathsToInstallPkg path locations
            // e.g.:
            // ./InstallPackagePath1/PackageA
            // ./InstallPackagePath1/PackageB
            // ./InstallPackagePath2/PackageC
            // ./InstallPackagePath3/PackageD
            foreach (var path in _pathsToInstallPkg)
            {
                _pathsToSearch.AddRange(Utils.GetSubDirectories(path));
            }

            IEnumerable <PSResourceInfo> pkgsAlreadyInstalled = getHelper.FilterPkgPaths(pkgNames.ToArray(), _versionRange, _pathsToSearch);

            // If any pkg versions are already installed, write a message saying it is already installed and continue processing other pkg names
            if (pkgsAlreadyInstalled.Any())
            {
                foreach (PSResourceInfo pkg in pkgsAlreadyInstalled)
                {
                    _cmdletPassedIn.WriteWarning(string.Format("Resource '{0}' with version '{1}' is already installed.  If you would like to reinstall, please run the cmdlet again with the -Reinstall parameter", pkg.Name, pkg.Version));

                    // remove this pkg from the list of pkg names install
                    packagesToInstall.ToList().Remove(pkg);
                }
            }

            return(packagesToInstall);
        }
Exemplo n.º 24
0
        public void Register(string id, PSCmdlet cmdlet)
        {
            if (!string.IsNullOrEmpty(Name))
            {
                // already registerd
                return;
            }

            Name = id;

            Variables = new Dictionary <string, object>();

            try
            {
                var variables = ScriptBlock.Ast.FindAll(x => x is VariableExpressionAst, true).Cast <VariableExpressionAst>().Select(m => m.VariablePath.ToString());

                foreach (var variableName in variables)
                {
                    var variable = cmdlet.SessionState.PSVariable.Get(variableName);
                    if (variable != null && !variable.Options.HasFlag(ScopedItemOptions.Constant) && !variable.Options.HasFlag(ScopedItemOptions.ReadOnly))
                    {
                        if (!Variables.ContainsKey(variable.Name))
                        {
                            Variables.Add(variable.Name, cmdlet.SessionState.PSVariable.GetValue(variable.Name));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                cmdlet.WriteWarning(ex.Message);
            }

            SessionId = cmdlet.SessionState.PSVariable.Get(Constants.SessionId)?.Value as string;
            Page      = cmdlet.SessionState.PSVariable.Get(Constants.UDPage)?.Value as Page;

            var state = cmdlet.GetHostState();

            state.EndpointService.Register(this);
        }
Exemplo n.º 25
0
        public static List <T> ExecuteScript <T>(this PSCmdlet cmdlet, string contents)
        {
            List <T> output = new List <T>();

            using (PowerShell powershell = PowerShell.Create(RunspaceMode.CurrentRunspace))
            {
                powershell.AddScript(contents);
                Collection <T> result = powershell.Invoke <T>();

                if (cmdlet.SessionState != null)
                {
                    powershell.Streams.Error.ForEach(e => cmdlet.WriteError(e));
                    powershell.Streams.Verbose.ForEach(r => cmdlet.WriteVerbose(r.Message));
                    powershell.Streams.Warning.ForEach(r => cmdlet.WriteWarning(r.Message));
                }

                if (result != null && result.Count > 0)
                {
                    output.AddRange(result);
                }
            }

            return(output);
        }
Exemplo n.º 26
0
 public void Warning(string message)
 {
     _cmdlet.WriteWarning(message);
 }
Exemplo n.º 27
0
        private void UpdateMappingToolDatabase(PSCmdlet callingCmdlet)
        {
            using (var mapDatabaseContext = new MappingTool.MappingToolDatabaseDataContext(MapDatabaseConnectionString))
            {
                var glymaDbVersion = mapDatabaseContext.GetGlymaDbVersion();

                foreach (var row in glymaDbVersion)
                {
                    if (row.Column1 != "v1.5.0r3")
                    {
                        callingCmdlet.WriteWarning(string.Format("This update can only update the v1.5.0r3 database to v1.5.0r4 database. The version of this database is {0}.", row.Column1));

                        return;
                    }
                }
            }

            using (var mapDbConnection = new SqlConnection(MapDatabaseConnectionString))
            {
                mapDbConnection.Open();
                var transaction = mapDbConnection.BeginTransaction();
                try
                {
                    callingCmdlet.WriteWarning("Database update started, please wait...");
                    new UpdateAllMetadata().Execute(mapDbConnection, transaction);
                    callingCmdlet.WriteWarning("Updated to new description metadata name");

                    var descriptionTypeMetadataList = new QueryMetadata("Description.Type").GetItems(mapDbConnection, transaction);
                    callingCmdlet.WriteWarning(string.Format("{0} description type records found.", descriptionTypeMetadataList.Count()));

                    var descriptionMetadataList = new QueryMetadata("Description.Content").GetItems(mapDbConnection, transaction);
                    callingCmdlet.WriteWarning(string.Format("{0} description records found.", descriptionMetadataList.Count()));

                    foreach (var updatableNode in descriptionTypeMetadataList)
                    {
                        var found = descriptionMetadataList.FirstOrDefault(q => q.NodeUid == updatableNode.NodeUid);
                        if (found != null)
                        {
                            if (string.IsNullOrEmpty(found.MetadataValue))
                            {
                                new DeleteMetadata(updatableNode.MetadataId).Execute(mapDbConnection, transaction);
                                new DeleteMetadata(found.MetadataId).Execute(mapDbConnection, transaction);
                                callingCmdlet.WriteWarning(string.Format("Node Id {0} description deleted",
                                                                         updatableNode.NodeUid));
                            }
                            else if (found.MetadataValue.StartsWith("http://") || found.MetadataValue.StartsWith("https://") || updatableNode.MetadataValue == "Iframe")
                            {
                                var parts = found.MetadataValue.Split(',');
                                if (parts.Count() == 3)
                                {
                                    new UpdateMetadata(found.MetadataId, "Description.Url", parts[0])
                                    .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Width", parts[1].Replace("px", ""),
                                                       found.NodeUid, found.RootMapUid, found.DomainUid,
                                                       found.Created, found.Modified, found.CreatedBy, found.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Height", parts[2].Replace("px", ""),
                                                       found.NodeUid, found.RootMapUid, found.DomainUid,
                                                       found.Created, found.Modified, found.CreatedBy, found.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                    new UpdateMetadata(updatableNode.MetadataId, "Description.Type", "Iframe")
                                    .Execute(mapDbConnection, transaction);
                                    callingCmdlet.WriteWarning(
                                        string.Format("Node Id {0} description has updated to Iframe",
                                                      updatableNode.NodeUid));
                                }
                                else
                                {
                                    new UpdateMetadata(updatableNode.MetadataId, "Description.Type", "Html").Execute(mapDbConnection, transaction);
                                }
                            }
                            else
                            {
                                var descriptionUpdater = new OldHtmlDescriptionUpdater(found.MetadataValue, callingCmdlet);
                                new UpdateMetadata(updatableNode.MetadataId, "Description.Type", "Html")
                                .Execute(mapDbConnection, transaction);
                                new UpdateMetadata(found.MetadataId, "Description.Content", descriptionUpdater.Description)
                                .Execute(mapDbConnection, transaction);
                                if (descriptionUpdater.Width > 0)
                                {
                                    new InsertMetadata("Description.Width", descriptionUpdater.Width.ToString(CultureInfo.InvariantCulture), found.NodeUid, found.RootMapUid, found.DomainUid, found.Created, found.Modified, found.CreatedBy, found.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                }

                                if (descriptionUpdater.Height > 0)
                                {
                                    new InsertMetadata("Description.Height", descriptionUpdater.Height.ToString(CultureInfo.InvariantCulture), found.NodeUid, found.RootMapUid, found.DomainUid, found.Created, found.Modified, found.CreatedBy, found.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                }
                                callingCmdlet.WriteWarning(string.Format("Node Id {0} description has updated to Html", updatableNode.NodeUid));
                            }
                        }
                        else
                        {
                            new DeleteMetadata(updatableNode.MetadataId).Execute(mapDbConnection, transaction);
                            callingCmdlet.WriteWarning(string.Format("Node Id {0} description deleted",
                                                                     updatableNode.NodeUid));
                        }
                    }


                    foreach (var description in descriptionMetadataList)
                    {
                        var found = descriptionTypeMetadataList.FirstOrDefault(q => q.NodeUid == description.NodeUid);
                        if (found == null)
                        {
                            if (string.IsNullOrEmpty(description.MetadataValue))
                            {
                                new DeleteMetadata(description.MetadataId).Execute(mapDbConnection, transaction);
                                callingCmdlet.WriteWarning(string.Format("Node Id {0} description deleted", description.NodeUid));
                            }
                            else if (description.MetadataValue.StartsWith("http://") || description.MetadataValue.StartsWith("https://"))
                            {
                                var parts = description.MetadataValue.Split(',');
                                if (parts.Count() == 3)
                                {
                                    new UpdateMetadata(description.MetadataId, "Description.Url", parts[0])
                                    .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Width", parts[1].Replace("px", ""), description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Height", parts[2].Replace("px", ""), description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Type", "Iframe", description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                    callingCmdlet.WriteWarning(string.Format("Node Id {0} description has updated to Iframe", description.NodeUid));
                                }
                                else
                                {
                                    new InsertMetadata("Description.Type", "Html", description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                    callingCmdlet.WriteWarning(string.Format("Node Id {0} description has updated to Iframe", description.NodeUid));
                                }
                            }
                            else
                            {
                                var descriptionUpdater = new OldHtmlDescriptionUpdater(description.MetadataValue, callingCmdlet);
                                new InsertMetadata("Description.Type", "Html", description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                .Execute(mapDbConnection, transaction);
                                new UpdateMetadata(description.MetadataId, "Description.Content", descriptionUpdater.Description)
                                .Execute(mapDbConnection, transaction);
                                if (descriptionUpdater.Width > 0)
                                {
                                    new InsertMetadata("Description.Width", descriptionUpdater.Width.ToString(CultureInfo.InvariantCulture), description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                }

                                if (descriptionUpdater.Height > 0)
                                {
                                    new InsertMetadata("Description.Height", descriptionUpdater.Height.ToString(CultureInfo.InvariantCulture), description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                }
                                callingCmdlet.WriteWarning(string.Format("Node Id {0} description has updated to Html", description.NodeUid));
                            }
                        }
                    }


                    transaction.Commit();

                    var updateGlymaDbVersion = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r4.UpdateGlymaDbVersion.sql");
                    updateGlymaDbVersion.ExecuteNonQuery(mapDbConnection);



                    callingCmdlet.WriteWarning("Database update completed");
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    callingCmdlet.WriteWarning("Updated failed: " + ex.Message);
                    return;
                }

                mapDbConnection.Close();
            }

            using (var transactionDbConnection = new SqlConnection(TransactionDatabaseConnectionString))
            {
                try
                {
                    transactionDbConnection.Open();
                    var updateGlymatransactionDbVersion = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r4.UpdateGlymaDbVersion.sql");
                    updateGlymatransactionDbVersion.ExecuteNonQuery(transactionDbConnection);
                }
                catch (Exception ex)
                {
                    callingCmdlet.WriteWarning("Updated failed: " + ex.Message);
                    return;
                }
                transactionDbConnection.Close();
            }
        }
Exemplo n.º 28
0
        internal static void WriteFormattedMessage(PSCmdlet cmdlet, Message message)
        {
            if (cmdlet.Host.Name == "ConsoleHost")
            {
                var messageLines = new List <string>();
                messageLines.AddRange(message.Text.Split(new[] { '\n' }));
                var wrappedText = new List <string>();
                foreach (var messageLine in messageLines.Select(l => l == "\n" ? " \n" : l))
                {
                    wrappedText.AddRange(WordWrap(messageLine, cmdlet.Host.UI.RawUI.MaxWindowSize.Width - 8));
                }

                var notificationColor = "\x1B[7m";
                var resetColor        = "\x1B[0m";

                var outMessage = string.Empty;

                foreach (var wrappedLine in wrappedText)
                {
                    var lineToAdd = string.Empty;
                    if (wrappedLine == "")
                    {
                        lineToAdd = "\x00A0".PadRight(cmdlet.Host.UI.RawUI.MaxWindowSize.Width - 8);
                    }
                    else
                    {
                        lineToAdd = wrappedLine.PadRight(cmdlet.Host.UI.RawUI.MaxWindowSize.Width - 8);
                    }
                    outMessage += $" {lineToAdd}\n";
                }
                switch (message.Type)
                {
                case MessageType.Message:
                {
                    cmdlet.WriteObject($"{notificationColor}\n{outMessage}{resetColor}\n");
                    break;
                }

                case MessageType.Warning:
                {
                    cmdlet.WriteWarning($"{notificationColor}\n{outMessage}{resetColor}\n");
                    break;
                }
                }
            }
            else
            {
                switch (message.Type)
                {
                case MessageType.Message:
                {
                    cmdlet.WriteObject(message.Text);
                    break;
                }

                case MessageType.Warning:
                {
                    cmdlet.WriteWarning(message.Text);
                    break;
                }
                }
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// Logs the error.
 /// </summary>
 /// <param name="message">The message.</param>
 public void LogError(string message)
 {
     _cmdlet.WriteWarning(message);
 }
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            SqlAssemblies sqlAssemblies = new SqlAssemblies();

            if (!sqlAssemblies.LoadedSuccessfully)
            {
                callingCmdlet.WriteWarning(sqlAssemblies.ErrorMessage);
                return;
            }

            try
            {
                SmoServer server = new SmoServer(sqlAssemblies, DatabaseServer);
                server.SetApplicationName("GlymaNewMapSecurityDbInstaller");

                SmoDatabase database = new SmoDatabase(sqlAssemblies, server, DatabaseName);

                SmoFileGroup fileGroup = new SmoFileGroup(sqlAssemblies, database, "PRIMARY");
                database.AddFileGroup(fileGroup);

                SmoDataFile dataFile = new SmoDataFile(sqlAssemblies, fileGroup, DatabaseName);
                fileGroup.AddDataFile(dataFile);
                dataFile.SetFileName(server.GetMasterDbPath() + "\\" + DatabaseName + ".mdf");
                dataFile.SetSize(50.0 * 1024.0);
                dataFile.SetGrowthType("KB");
                dataFile.SetGrowth(1024.0);
                dataFile.SetIsPrimaryFile(true);

                SmoLogFile logFile = new SmoLogFile(sqlAssemblies, database, DatabaseName + "_Log");
                database.AddLogFile(logFile);
                logFile.SetFileName(server.GetMasterDbPath() + "\\" + DatabaseName + "_Log.ldf");
                logFile.SetSize(164.0 * 1024.0);
                logFile.SetGrowthType("Percent");
                logFile.SetGrowth(10.0);

                database.Create();

                fileGroup = database.GetFileGroup("PRIMARY");
                fileGroup.SetIsDefault(true);
                fileGroup.Alter();
                database.Alter();

                using (SqlConnection connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();

                    if (!string.IsNullOrEmpty(WebApplicationPoolAccount))
                    {
                        if (!IsWebApplicationPoolAccountDbo)
                        {
                            EmbeddedSqlScript createWebUserScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.CreateUser.sql");
                            createWebUserScript.AddToken("[ACCOUNT_NAME]", WebApplicationPoolAccount);
                            createWebUserScript.ExecuteNonQuery(connection);

                            EmbeddedSqlScript grantWebUserRoleScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.GrantUserRole.sql");
                            grantWebUserRoleScript.AddToken("[ACCOUNT_NAME]", WebApplicationPoolAccount);
                            grantWebUserRoleScript.AddToken("[ROLE]", "db_owner");
                            grantWebUserRoleScript.ExecuteNonQuery(connection);
                        }
                    }
                    else
                    {
                        callingCmdlet.WriteWarning("There was no web application pool account provided. As we are skipping this step, the web application pool account will need to be manually given db_owner rights to this Glyma Security DB.");
                    }

                    if (!string.IsNullOrEmpty(GlymaServiceApplicationPoolAccount))
                    {
                        if (!IsGlymaServiceApplicationPoolAccountDbo)
                        {
                            EmbeddedSqlScript createGlymaServiceUserScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.CreateUser.sql");
                            createGlymaServiceUserScript.AddToken("[ACCOUNT_NAME]", GlymaServiceApplicationPoolAccount);
                            createGlymaServiceUserScript.ExecuteNonQuery(connection);

                            EmbeddedSqlScript grantGlymaServiceUserRoleScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.GrantUserRole.sql");
                            grantGlymaServiceUserRoleScript.AddToken("[ACCOUNT_NAME]", GlymaServiceApplicationPoolAccount);
                            grantGlymaServiceUserRoleScript.AddToken("[ROLE]", "db_owner");
                            grantGlymaServiceUserRoleScript.ExecuteNonQuery(connection);
                        }
                    }
                    else
                    {
                        callingCmdlet.WriteWarning("There was no Glyma service application pool account provided. As we are skipping this step, the Glyma application pool account will need to be manually given db_owner rights to this Glyma Security DB.");
                    }

                    EmbeddedSqlScript createTablesAndConstraintsScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.CreateTablesAndConstraints.sql");
                    createTablesAndConstraintsScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createGetAllowedGroupsSP = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.CreateGetAllowedGroupsSP.sql");
                    createGetAllowedGroupsSP.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createGetSiteCollectionAssociationsSP = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.CreateGetSiteCollectionAssociationsSP.sql");
                    createGetSiteCollectionAssociationsSP.ExecuteNonQuery(connection);

                    if (!string.IsNullOrEmpty(SearchCrawlAccount))
                    {
                        if (!IsSearchCrawlAccountDbo)
                        {
                            EmbeddedSqlScript createSearchUserScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.CreateUser.sql");
                            createSearchUserScript.AddToken("[ACCOUNT_NAME]", SearchCrawlAccount);
                            createSearchUserScript.ExecuteNonQuery(connection);

                            EmbeddedSqlScript grantSearchPermissionsScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.GrantSearchPermissions.sql");
                            grantSearchPermissionsScript.AddToken("[ACCOUNT_NAME]", SearchCrawlAccount);
                            grantSearchPermissionsScript.ExecuteNonQuery(connection);
                        }
                    }
                    else
                    {
                        callingCmdlet.WriteWarning("There was no search crawl account provided. As we are skipping this step, the Glyma search crawl account will need to be manually granted execute permissions on the GetAllowedGroups stored proecedure.");
                    }


                    connection.Close();
                }
            }
            catch (TargetInvocationException tiex)
            {
                //If it was a Target Invocation Exception find the last InnerException and throw it so the user gets a useful message to troubleshoot.
                Exception ex = Util.FindLastException(tiex);
                throw ex;
            }
        }