Example #1
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (UseSystem)
                {
                    v.Proxy = null;
                }
                else
                {
                    v.Proxy = new Vault.ProxyConfig
                    {
                        UseNoProxy      = UseNoProxy,
                        ProxyURI        = UseProxy,
                        UseDefCred      = DefaultCredential,
                        Username        = Credential?.UserName,
                        PasswordEncoded = Credential?.GetNetworkCredential()?.Password,
                    };

                    if (!string.IsNullOrEmpty(v.Proxy.PasswordEncoded))
                    {
                        v.Proxy.PasswordEncoded = Convert.ToBase64String(Encoding.Unicode.GetBytes(
                                                                             v.Proxy.PasswordEncoded));
                    }
                };

                vp.SaveVault(v);
            }
        }
        public override void ExecuteCmdlet()
        {
            // register the subscription for this service if it has not been before
            // sebsequent call to register is redundent
            RegisterSubscriptionWithRdfeForRemoteApp();

            NetworkCredential         creds   = null;
            CollectionCreationDetails details = new CollectionCreationDetails()
            {
                Name = CollectionName,
                TemplateImageName = ImageName,
                Region            = Location,
                PlanName          = Plan,
                Description       = Description,
                CustomRdpProperty = CustomRdpProperty,
                Mode = (ResourceType == null || ResourceType == CollectionMode.Unassigned) ? CollectionMode.Apps : ResourceType.Value
            };
            OperationResultWithTrackingId response = null;


            if (ParameterSetName == "AzureVNet")
            {
                details.VNetName   = VNetName;
                details.SubnetName = SubnetName;
                ValidateCustomerVNetParams(details.VNetName, details.SubnetName);

                if (DnsServers != null)
                {
                    details.DnsServers = DnsServers.Split(new char[] { ',' });
                }

                if (!String.IsNullOrWhiteSpace(Domain) || Credential != null)
                {
                    if (String.IsNullOrWhiteSpace(Domain) || Credential == null)
                    {
                        // you supplied either a domain or a cred, but not both.
                        ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                            Commands_RemoteApp.InvalidADArguments,
                            String.Empty,
                            Client.Collections,
                            ErrorCategory.InvalidArgument
                            );

                        ThrowTerminatingError(er);
                    }

                    creds          = Credential.GetNetworkCredential();
                    details.AdInfo = new ActiveDirectoryConfig()
                    {
                        DomainName         = Domain,
                        OrganizationalUnit = OrganizationalUnit,
                        UserName           = creds.UserName,
                        Password           = creds.Password,
                    };
                }
            }
            else
            {
                if (String.IsNullOrEmpty(details.Region))
                {
                    ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                        Commands_RemoteApp.InvalidLocationArgument,
                        String.Empty,
                        Client.Collections,
                        ErrorCategory.InvalidArgument
                        );

                    ThrowTerminatingError(er);
                }
            }

            response = CallClient(() => Client.Collections.Create(false, details), Client.Collections);

            if (response != null)
            {
                TrackingResult trackingId = new TrackingResult(response);
                WriteObject(trackingId);
            }
        }
        internal virtual void PrepareSession()
        {
            // make sure we have a valid WebRequestSession object to work with
            if (null == WebSession)
            {
                WebSession = new WebRequestSession();
            }

            if (null != SessionVariable)
            {
                // save the session back to the PS environment if requested
                PSVariableIntrinsics vi = SessionState.PSVariable;
                vi.Set(SessionVariable, WebSession);
            }

            //
            // handle credentials
            //
            if (null != Credential)
            {
                // get the relevant NetworkCredential
                NetworkCredential netCred = Credential.GetNetworkCredential();
                WebSession.Credentials = netCred;

                // supplying a credential overrides the UseDefaultCredentials setting
                WebSession.UseDefaultCredentials = false;
            }
            else if (UseDefaultCredentials)
            {
                WebSession.UseDefaultCredentials = true;
            }


            if (null != CertificateThumbprint)
            {
                X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection   = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false);
                if (tbCollection.Count == 0)
                {
                    CryptographicException ex = new CryptographicException(WebCmdletStrings.ThumbprintNotFound);
                    throw ex;
                }
                foreach (X509Certificate2 tbCert in tbCollection)
                {
                    X509Certificate certificate = (X509Certificate)tbCert;
                    WebSession.AddCertificate(certificate);
                }
            }

            if (null != Certificate)
            {
                WebSession.AddCertificate(Certificate);
            }

            //
            // handle the user agent
            //
            if (null != UserAgent)
            {
                // store the UserAgent string
                WebSession.UserAgent = UserAgent;
            }

            if (null != Proxy)
            {
                WebProxy webProxy = new WebProxy(Proxy);
                webProxy.BypassProxyOnLocal = false;
                if (null != ProxyCredential)
                {
                    webProxy.Credentials = ProxyCredential.GetNetworkCredential();
                }
                else if (ProxyUseDefaultCredentials)
                {
                    // If both ProxyCredential and ProxyUseDefaultCredentials are passed,
                    // UseDefaultCredentials will overwrite the supplied credentials.
                    webProxy.UseDefaultCredentials = true;
                }
                WebSession.Proxy = webProxy;
            }

            if (-1 < MaximumRedirection)
            {
                WebSession.MaximumRedirection = MaximumRedirection;
            }

            // store the other supplied headers
            if (null != Headers)
            {
                foreach (string key in Headers.Keys)
                {
                    // add the header value (or overwrite it if already present)
                    WebSession.Headers[key] = Headers[key].ToString();
                }
            }
        }
Example #4
0
        /// <summary>
        /// Performs record-by-record processing functionality for the cmdlet.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (PrtgSessionState.Client == null || Force.IsPresent)
            {
                PrtgSessionState.Client = PassHash.IsPresent ?
                                          new PrtgClient(Server, Credential.GetNetworkCredential().UserName, Credential.GetNetworkCredential().Password, AuthMode.PassHash, IgnoreSSL) :
                                          new PrtgClient(Server, Credential.GetNetworkCredential().UserName, Credential.GetNetworkCredential().Password, ignoreSSL: IgnoreSSL);

                if (RetryCount != null)
                {
                    PrtgSessionState.Client.RetryCount = RetryCount.Value;
                }

                if (RetryDelay != null)
                {
                    PrtgSessionState.Client.RetryDelay = RetryDelay.Value;
                }

                if (LogLevel != null)
                {
                    LogLevel level = PrtgAPI.LogLevel.None;

                    foreach (var l in LogLevel)
                    {
                        level |= l;
                    }

                    PrtgSessionState.Client.LogLevel = level;
                }

                if (!ProgressTrue && (ProgressFalse || IsScript || IsISE))
                {
                    PrtgSessionState.EnableProgress = false;
                }
                else
                {
                    PrtgSessionState.EnableProgress = true;
                }

                WritePassThru();
            }
            else
            {
                throw new InvalidOperationException($"Already connected to server {PrtgSessionState.Client.Server}. To override please specify -Force");
            }
        }
Example #5
0
        /// <summary>
        /// BeginProcessing code
        /// </summary>
        protected override void BeginProcessing()
        {
            if (_uri.ToString().Trim().Length == 0)
            {
                Exception   ex = new ArgumentException(WebServiceResources.InvalidUri);
                ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null);
                ThrowTerminatingError(er);
            }
            //check if system.web is available.This assembly is not available in win server core.
            string AssemblyString = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

            try
            {
                Assembly webAssembly = Assembly.Load(AssemblyString);
            }
            catch (FileNotFoundException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "SystemWebAssemblyNotFound", ErrorCategory.ObjectNotFound, null);
                er.ErrorDetails = new ErrorDetails(WebServiceResources.NotSupported);
                ThrowTerminatingError(er);
            }

            int sourceCache = 0;

            lock (s_uriCache)
            {
                if (s_uriCache.ContainsKey(_uri))
                {
                    //if uri is present in the cache
                    string ns;
                    s_uriCache.TryGetValue(_uri, out ns);
                    string[] data = ns.Split('|');
                    if (string.IsNullOrEmpty(_namespace))
                    {
                        if (data[0].StartsWith("Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.", StringComparison.OrdinalIgnoreCase))
                        {
                            _namespace = data[0];
                            _class     = data[1];
                        }
                    }
                    sourceCache = Int32.Parse(data[2].ToString(), CultureInfo.InvariantCulture);
                }
            }
            if (string.IsNullOrEmpty(_namespace))
            {
                _namespace = "Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy" + GenerateRandomName();
            }
            //if class is null,generate a name for it
            if (string.IsNullOrEmpty(_class))
            {
                _class = "MyClass" + GenerateRandomName();
            }

            Assembly webserviceproxy = GenerateWebServiceProxyAssembly(_namespace, _class);

            if (webserviceproxy == null)
            {
                return;
            }
            Object instance = InstantinateWebServiceProxy(webserviceproxy);

            //to set the credentials into the generated webproxy Object
            PropertyInfo[] pinfo = instance.GetType().GetProperties();
            foreach (PropertyInfo pr in pinfo)
            {
                if (pr.Name.Equals("UseDefaultCredentials", StringComparison.OrdinalIgnoreCase))
                {
                    if (UseDefaultCredential.IsPresent)
                    {
                        bool flag = true;
                        pr.SetValue(instance, flag as object, null);
                    }
                }
                if (pr.Name.Equals("Credentials", StringComparison.OrdinalIgnoreCase))
                {
                    if (Credential != null)
                    {
                        NetworkCredential cred = Credential.GetNetworkCredential();
                        pr.SetValue(instance, cred as object, null);
                    }
                }
            }

            //disposing the entries in a cache
            //Adding to Cache
            lock (s_uriCache)
            {
                s_uriCache.Remove(_uri);
            }
            if (sourceCache > 0)
            {
                lock (_cachelock)
                {
                    s_srccodeCache.Remove(sourceCache);
                }
            }
            string key = string.Join("|", new string[] { _namespace, _class, _sourceHash.ToString(System.Globalization.CultureInfo.InvariantCulture) });

            lock (s_uriCache)
            {
                s_uriCache.Add(_uri, key);
            }
            lock (_cachelock)
            {
                s_srccodeCache.Add(_sourceHash, instance);
            }

            WriteObject(instance, true);
        }//End BeginProcessing()
Example #6
0
        /// <summary>
        /// BeginProcessing override.
        /// </summary>
        protected override void BeginProcessing()
        {
            try
            {
                // Set the sender address of the mail message
                _mMailMessage.From = new MailAddress(From);
            }
            catch (FormatException e)
            {
                ErrorRecord er = new ErrorRecord(e, "FormatException", ErrorCategory.InvalidType, From);
                ThrowTerminatingError(er);
            }

            // Set the recipient address of the mail message
            AddAddressesToMailMessage(To, "to");

            // Set the BCC address of the mail message
            if (Bcc != null)
            {
                AddAddressesToMailMessage(Bcc, "bcc");
            }

            // Set the CC address of the mail message
            if (Cc != null)
            {
                AddAddressesToMailMessage(Cc, "cc");
            }

            // Set the Reply-To address of the mail message
            if (ReplyTo != null)
            {
                AddAddressesToMailMessage(ReplyTo, "replyTo");
            }

            // Set the delivery notification
            _mMailMessage.DeliveryNotificationOptions = DeliveryNotificationOption;

            // Set the subject of the mail message
            _mMailMessage.Subject = Subject;

            // Set the body of the mail message
            _mMailMessage.Body = Body;

            // Set the subject and body encoding
            _mMailMessage.SubjectEncoding = Encoding;
            _mMailMessage.BodyEncoding    = Encoding;

            // Set the format of the mail message body as HTML
            _mMailMessage.IsBodyHtml = BodyAsHtml;

            // Set the priority of the mail message to normal
            _mMailMessage.Priority = Priority;

            // Get the PowerShell environment variable
            // globalEmailServer might be null if it is deleted by: PS> del variable:PSEmailServer
            PSVariable globalEmailServer = SessionState.Internal.GetVariable(SpecialVariables.PSEmailServer);

            if (SmtpServer == null && globalEmailServer != null)
            {
                SmtpServer = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture);
            }

            if (string.IsNullOrEmpty(SmtpServer))
            {
                ErrorRecord er = new ErrorRecord(new InvalidOperationException(SendMailMessageStrings.HostNameValue), null, ErrorCategory.InvalidArgument, null);
                this.ThrowTerminatingError(er);
            }

            if (Port == 0)
            {
                _mSmtpClient = new SmtpClient(SmtpServer);
            }
            else
            {
                _mSmtpClient = new SmtpClient(SmtpServer, Port);
            }

            if (UseSsl)
            {
                _mSmtpClient.EnableSsl = true;
            }

            if (Credential != null)
            {
                _mSmtpClient.UseDefaultCredentials = false;
                _mSmtpClient.Credentials           = Credential.GetNetworkCredential();
            }
            else if (!UseSsl)
            {
                _mSmtpClient.UseDefaultCredentials = true;
            }
        }
Example #7
0
        protected override void EndProcessing()
        {
            if (ParameterSetName == "Simple")
            {
                connbuilder = new ConnectionString
                {
                    Connection  = Mode,
                    InitialSize = InitialSize,
                    Collation   = collation
                };

                if (Credential != null)
                {
                    connbuilder.Password = Credential.GetNetworkCredential().Password;
                }

                if (ReadOnly)
                {
                    connbuilder.ReadOnly = true;
                }

                if (Upgrade)
                {
                    connbuilder.Upgrade = true;
                }



                if (Database != null && !string.IsNullOrEmpty(Database) && !string.IsNullOrWhiteSpace(Database))
                {
                    resolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(Database);

                    if (File.Exists(resolvedPath))
                    {
                        connbuilder.Filename = resolvedPath;
                        _connectioninfo      = connbuilder;


                        try
                        {
                            _connection = new LiteDatabase(connbuilder);
                            _connectioninfo.Password = null;
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("Path not found:\t['{0}']", resolvedPath));
                    }
                }
                else
                {
                    _connection = new LiteDatabase(":memory:");
                    WriteVerbose($"Open-LiteDBConnection: Opened connection to In-Memory database");
                }
            }
            else
            {
                //custom connection string passed by the user
                try
                {
                    _connection     = new LiteDatabase(ConnectionString);
                    _connectioninfo = null;
                }
                catch (Exception)
                {
                    throw;
                }
            }

            BsonMapper.Global.SerializeNullValues = true;

/*            if (DontSerializeNullValues)
 *          {
 *              BsonMapper.Global.SerializeNullValues = false;
 *          }
 *
 *          if (DontTrimWhitespace)
 *          {
 *              BsonMapper.Global.TrimWhitespace = false;
 *          }
 *
 *          if (DontConvertEmptyStringToNull)
 *          {
 *              BsonMapper.Global.EmptyStringToNull = false;
 *          }*/

            if (IncludeFields)
            {
                BsonMapper.Global.IncludeFields = true;
            }

            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                //add the database path as a custom property to the connection object
                PowerShellInstance.Commands.AddCommand("Add-Member").AddParameter("inputobject", _connection).AddParameter("MemberType", "NoteProperty").
                AddParameter("Name", "Database").AddParameter("Value", resolvedPath);
                PowerShellInstance.AddStatement();
                PowerShellInstance.Commands.AddCommand("Add-Member").AddParameter("inputobject", _connection).AddParameter("MemberType", "NoteProperty").
                AddParameter("Name", "ConnectionInfo").AddParameter("Value", _connectioninfo).AddParameter("PassThru", true);


                var PSOutput = PowerShellInstance.Invoke();
            }

            //check if there is an existing connection variable if yes then dont overwrite it!
            try
            {
                var conns = (LiteDatabase)SessionState.PSVariable.Get("LiteDBPSConnection").Value;
            }
            catch (Exception)
            {
                SessionState.PSVariable.Set("LiteDBPSConnection", _connection);
            }



            //write the connection to the pipeline
            WriteObject(_connection);
        }
Example #8
0
        public override void ExecuteCmdlet()
        {
            NetworkCredential             creds    = null;
            CollectionUpdateDetails       details  = null;
            OperationResultWithTrackingId response = null;
            Collection collection    = null;
            bool       forceRedeploy = false;

            collection = FindCollection(CollectionName);
            if (collection == null)
            {
                return;
            }

            details = new CollectionUpdateDetails();

            if (Credential != null)
            {
                if (collection.AdInfo == null)
                {
                    ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                        Commands_RemoteApp.AadInfoCanNotBeAddedToCloudOnlyCollectionMessage,
                        String.Empty,
                        Client.Collections,
                        ErrorCategory.InvalidArgument);
                    ThrowTerminatingError(er);
                }

                details.AdInfo = new ActiveDirectoryConfig();

                creds = Credential.GetNetworkCredential();
                details.AdInfo.UserName           = Credential.UserName;
                details.AdInfo.Password           = creds.Password;
                details.AdInfo.DomainName         = collection.AdInfo.DomainName;
                details.AdInfo.OrganizationalUnit = collection.AdInfo.OrganizationalUnit;

                if (String.Equals("Inactive", collection.Status, StringComparison.OrdinalIgnoreCase))
                {
                    // the collection may have failed due to bad domain join information before,
                    // re-trying with the new information
                    forceRedeploy = true;
                }
            }
            else if (Plan != null)
            {
                details.PlanName = Plan;
            }
            else if (Description != null)
            {
                details.Description = Description;
            }
            else if (CustomRdpProperty != null)
            {
                details.CustomRdpProperty = CustomRdpProperty;
            }
            else
            {
                ErrorRecord er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                    "At least one parameter must be set with this cmdlet",
                    String.Empty,
                    Client.Collections,
                    ErrorCategory.InvalidArgument);
                ThrowTerminatingError(er);
            }

            response = CallClient(() => Client.Collections.Set(CollectionName, forceRedeploy, false, details), Client.Collections);
            if (response != null)
            {
                WriteTrackingId(response);
            }
        }
        /// <summary>
        /// Performs record-by-record processing functionality for the cmdlet.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (PrtgSessionState.Client == null || Force.IsPresent)
            {
                PrtgSessionState.Client = PassHash.IsPresent ?
                                          new PrtgClient(Server, Credential.GetNetworkCredential().UserName, Credential.GetNetworkCredential().Password, AuthMode.PassHash) :
                                          new PrtgClient(Server, Credential.GetNetworkCredential().UserName, Credential.GetNetworkCredential().Password);

                if (RetryCount != null)
                {
                    PrtgSessionState.Client.RetryCount = RetryCount.Value;
                }

                if (RetryDelay != null)
                {
                    PrtgSessionState.Client.RetryDelay = RetryDelay.Value;
                }
            }
            else
            {
                throw new Exception($"Already connected to server {PrtgSessionState.Client.Server}. To override please specify -Force");
            }
        }
Example #10
0
        /// <summary>
        /// Performs record-by-record processing functionality for the cmdlet.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (PrtgSessionState.Client == null || Force.IsPresent)
            {
                PrtgSessionState.Client = PassHash.IsPresent ?
                                          new PrtgClient(Server, Credential.GetNetworkCredential().UserName, Credential.GetNetworkCredential().Password, AuthMode.PassHash) :
                                          new PrtgClient(Server, Credential.GetNetworkCredential().UserName, Credential.GetNetworkCredential().Password);

                if (RetryCount != null)
                {
                    PrtgSessionState.Client.RetryCount = RetryCount.Value;
                }

                if (RetryDelay != null)
                {
                    PrtgSessionState.Client.RetryDelay = RetryDelay.Value;
                }

                if (Progress == false || (!string.IsNullOrEmpty(MyInvocation.ScriptName) && !GoPrtgScript()) || GetVariableValue("global:psISE") != null)
                {
                    PrtgSessionState.EnableProgress = false;
                }
                else
                {
                    PrtgSessionState.EnableProgress = true;
                }

                WritePassThru();
            }
            else
            {
                throw new Exception($"Already connected to server {PrtgSessionState.Client.Server}. To override please specify -Force");
            }
        }