public SPOnlineConnection(ClientContext context, ConnectionType connectionType, int minimalHealthScore, int retryCount, int retryWait, PSCredential credential, string url, string tenantAdminUrl, string pnpVersionTag, System.Management.Automation.Host.PSHost host, bool disableTelemetry)
        {
            if (!disableTelemetry)
            {
                InitializeTelemetry(context, host);
            }
            var coreAssembly = Assembly.GetExecutingAssembly();

            userAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            Context = context;
            Context.ExecutingWebRequest += Context_ExecutingWebRequest;
            ConnectionType     = connectionType;
            MinimalHealthScore = minimalHealthScore;
            RetryCount         = retryCount;
            RetryWait          = retryWait;
            PSCredential       = credential;
            TenantAdminUrl     = tenantAdminUrl;
            ContextCache       = new List <ClientContext> {
                context
            };
            PnPVersionTag    = pnpVersionTag;
            Url              = (new Uri(url)).AbsoluteUri;
            ConnectionMethod = ConnectionMethod.Credentials;
        }
Example #2
0
        static void Main(string[] args)
        {
            string  strURI       = "";
            string  strAdminName = "";
            string  strPwd       = "";
            string  strMailbox   = "";
            string  strSubject   = "";
            string  strGOID      = "";
            bool    bUseSubject  = true;
            bool    bExact       = false;
            DataSet dsMsgs       = new DataSet("Messages");

            Console.WriteLine("");
            Console.WriteLine("================");
            Console.WriteLine("Meeting Analyzer");
            Console.WriteLine("================");
            Console.WriteLine("Creates a timeline of a meeting and reports any problems found.\r\n");

            Console.WriteLine("Enter a connection URI for remote powershell.");
            Console.WriteLine("You can leave this blank for Office 365 connections, or enter a");
            Console.WriteLine("URI like \"https://outlook.office365.com/powershell-liveid\"");
            Console.Write("or \"https://yourdomain.onmicrosoft.com/powershell-liveid\" : ");

            strURI = Console.ReadLine();
            if (string.IsNullOrEmpty(strURI))
            {
                // >>> O365 - https://outlook.office365.com/powershell-liveid (from https://technet.microsoft.com/en-us/library/jj984289(v=exchg.160).aspx)
                strURI = "https://outlook.office365.com/powershell-liveid";
            }

            Console.WriteLine("");
            // get the tenant admin
            Console.Write("Enter the tenant admin name (eg. [email protected]): ");
            strAdminName = Console.ReadLine();
            // get the password
            Console.Write("Enter the password for {0}: ", strAdminName);
            // use below while loop to mask the password while reading it in
            bool bEnter    = true;
            int  iPwdChars = 0;

            while (bEnter)
            {
                ConsoleKeyInfo ckiKey = Console.ReadKey(true);
                if (ckiKey.Key == ConsoleKey.Enter)
                {
                    bEnter = false;
                }
                else if (ckiKey.Key == ConsoleKey.Backspace)
                {
                    if (strPwd.Length >= 1)
                    {
                        int oldLength = strPwd.Length;
                        strPwd = strPwd.Substring(0, oldLength - 1);
                        Console.Write("\b \b");
                    }
                }
                else
                {
                    strPwd = strPwd + ckiKey.KeyChar.ToString();
                    iPwdChars++;
                    Console.Write('*');
                }
            }
            Console.WriteLine("");
            // have to make the password secure for the connection
            SecureString secPwd = new SecureString();

            foreach (char c in strPwd)
            {
                secPwd.AppendChar(c);
            }
            // get rid of the textual password as soon as we have the secure password.
            strPwd = "";
            strPwd = null;

            // Now we have our username+password creds we can use for the connection
            PSCredential psCred = new PSCredential(strAdminName, secPwd);

            // Get rid of admin username now that the cred object is created
            strAdminName = "";
            strAdminName = null;

            // Now make the connection object for the service
            Uri    uriPS       = new Uri(strURI);
            string strShellUri = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
            WSManConnectionInfo connectionInfo = new WSManConnectionInfo(uriPS, strShellUri, psCred);

            connectionInfo.AuthenticationMechanism           = AuthenticationMechanism.Basic;
            connectionInfo.MaximumConnectionRedirectionCount = 5;

            Collection <PSObject> pshResults = new Collection <PSObject>(); // results collection object from running commands

            // Now do the connection and run PS commands
            using (Runspace rs = RunspaceFactory.CreateRunspace(connectionInfo))
            {
                PowerShell psh = PowerShell.Create();
                Console.WriteLine("\r\nAttempting to connect to the service.");
                try
                {
                    rs.Open();
                    psh.Runspace = rs;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Could not open the remote powershell session.");
                    Console.WriteLine("Error: " + ex.Message.ToString());
                    goto Exit;
                }

                Console.WriteLine("Successfully connected.\r\n");

                //Get rid of the secure password, don't need it anymore.
                secPwd.Dispose();
                secPwd = null;

NextMtg:

                // Now get user and meeting info from the user
                Console.Write("Enter the SMTP address of the user for the meeting to analyze: ");
                strMailbox        = Console.ReadLine();
                Timeline.m_strMbx = strMailbox; // For printing out to screen later
                Utils.m_MBX       = strMailbox;
                Console.Write("Enter the Subject of the meeting to analyze (leave blank to enter a Meeting ID instead): ");
                strSubject = Console.ReadLine();
                if (string.IsNullOrEmpty(strSubject))
                {
                    Console.Write("Enter the Meeting ID (Global Object ID) of the problem meeting: ");
                    strGOID = Console.ReadLine();

                    if (!(string.IsNullOrEmpty(strMailbox)) && !(string.IsNullOrEmpty(strGOID)))
                    {
                        Utils.CreateFile(strMailbox, strGOID);
                        bUseSubject = false;
                    }
                    else
                    {
                        string strYN = "no";
                        Console.Write("\r\nSMTP address and Subject or Global Object ID must have values. Do you want to try again (yes/no)? ");
                        strYN = Console.ReadLine().ToLower();
                        Console.WriteLine();
                        if (strYN.StartsWith("y"))
                        {
                            strMailbox        = "";
                            Timeline.m_strMbx = "";
                            Utils.m_MBX       = "";
                            strSubject        = "";
                            strGOID           = "";
                            goto NextMtg;
                        }
                        else
                        {
                            goto Exit;
                        }
                    }
                }
                else
                {
                    strSubject      = strSubject.Trim('"'); // remove quotes - they make things not work.
                    Utils.m_Subject = strSubject;
                    if (!(string.IsNullOrEmpty(strMailbox)) && !(string.IsNullOrEmpty(strSubject)))
                    {
                        Utils.CreateFile(strMailbox, strSubject);
                        string strExact = "no";
                        Console.Write("Search for exact match on Subject? (yes/no): ");
                        strExact = Console.ReadLine().ToLower();
                        if (strExact.StartsWith("y"))
                        {
                            bExact = true;
                        }
                        else
                        {
                            bExact = false;
                        }
                    }
                    else
                    {
                        string strYN = "no";
                        Console.Write("\r\nSMTP address and Subject or Global Object ID must have values. Do you want to try again (yes/no)? ");
                        strYN = Console.ReadLine().ToLower();
                        Console.WriteLine();
                        if (strYN.StartsWith("y"))
                        {
                            strMailbox        = "";
                            Timeline.m_strMbx = "";
                            Utils.m_MBX       = "";
                            strSubject        = "";
                            strGOID           = "";
                            goto NextMtg;
                        }
                        else
                        {
                            goto Exit;
                        }
                    }
                }


                Console.WriteLine("\r\nRunning command to retrieve the meeting data...");

                // Run Get-CalendarDiagnosticObjects to get the version history data
                // Get-CalendarDiagnosticObjects -Identity <user smtp address> -Subject <meeting subject>  -OutputProperties Custom -CustomPropertyNames ItemClass,NormalizedSubject...
                try
                {
                    psh.AddCommand("Get-CalendarDiagnosticObjects");
                    psh.AddParameter("-Identity", strMailbox);
                    if (bUseSubject)
                    {
                        psh.AddParameter("-Subject", strSubject);
                    }
                    else
                    {
                        psh.AddParameter("-MeetingId", strGOID);
                    }
                    if (bExact)
                    {
                        psh.AddParameter("-ExactMatch", 1);
                    }
                    //psh.AddParameter("-OutputProperties", "Custom");
                    psh.AddParameter("-CustomPropertyNames", Utils.rgstrPropsToGet);
                    psh.AddParameter("-ShouldBindToItem", 1);

                    pshResults = psh.Invoke();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\r\nUnable to process the Get-CalendarDiagnosticObjects command.");
                    Console.WriteLine("Error: " + ex.Message.ToString());
                    goto Exit;
                }

                if (pshResults.Count > 0)
                {
                    MsgData md = new MsgData();
                    Console.WriteLine("Successfully retrieved the meeting data.\r\n");

                    Timeline.m_iNumMsgs = pshResults.Count;
                    Console.Write("Importing data from messages.");

                    foreach (PSObject message in pshResults)
                    {
                        MsgData.PopulateDataSet(message);
                        Console.Write(".");
                    }
                    Console.WriteLine("\r\nData import completed.\r\n");
                }
                else
                {
                    Console.WriteLine("No meeting data was retrieved. Check the user and meeting information and try again.\r\n");
                    psh.Commands.Clear();
                    pshResults.Clear();
                    Utils.Reset();
                    strGOID        = "";
                    MsgData.m_GOID = "";
                    File.Delete(Utils.m_FilePath);
                    goto NextMtg;
                }
                // we got the data imported - now we can sort by the Modified Time
                if (MsgData.m_bNoTime == false)
                {
                    dsMsgs = MsgData.dsSort(MsgData.msgDataSet, "OrigModTime");
                }

                // Create the timeline with the sorted messages
                Timeline.CreateTimeline(dsMsgs);

                Utils.CreateCSVFile(Utils.m_MBX, Utils.m_Subject);
                Utils.WriteMsgData(dsMsgs);

                Console.WriteLine("Timeline output written to:             {0}", Utils.m_FilePath);
                Console.WriteLine("Calendar item property data written to: {0}", Utils.m_CSVPath);

                string strYesNo = "no";
                //strYesNo = "no";
                Console.Write("\r\nAnalyze data for another meeting (yes/no)? ");
                strYesNo = Console.ReadLine().ToLower();
                Console.WriteLine();
                if (strYesNo.StartsWith("y"))
                {
                    dsMsgs.Clear();
                    psh.Commands.Clear();
                    pshResults.Clear();
                    Utils.Reset();
                    strGOID        = "";
                    MsgData.m_GOID = "";
                    Console.WriteLine("==================================================");
                    Console.WriteLine();
                    goto NextMtg;
                }
                else
                {
                    // clear out stuff
                    dsMsgs.Clear();
                    psh.Commands.Clear();
                    pshResults.Clear();
                    Utils.Reset();
                    strGOID        = "";
                    MsgData.m_GOID = "";

                    // close out the runspace since we're done.
                    rs.Close();
                    rs.Dispose();
                }
            }

Exit:
            // Exit the app...
            Console.Write("\r\nExiting the program.");
            //Console.ReadLine();
        }
        private static PSDriveInfo GetDriveInfo(Rule aliasRule, ProviderInfo providerInfo, PSCredential psCredential)
        {
            var name      = aliasRule.Parameter;
            var account   = aliasRule.HasProperty("key") ? aliasRule["key"].Value : name;
            var container = aliasRule.HasProperty("container") ? aliasRule["container"].Value : "";

            if (psCredential == null || (psCredential.UserName == null && psCredential.Password == null))
            {
                psCredential = new PSCredential(account, aliasRule.HasProperty("secret") ? aliasRule["secret"].Value.ToSecureString() : null);
            }

            if (string.IsNullOrEmpty(container))
            {
                return(new PSDriveInfo(name, providerInfo, @"{0}:\{1}\".format(ProviderScheme, account), ProviderDescription, psCredential));
            }

            var root = aliasRule.HasProperty("root") ? aliasRule["root"].Value.Replace('/', '\\').Replace("\\\\", "\\").Trim('\\') : "";

            if (string.IsNullOrEmpty(root))
            {
                return(new PSDriveInfo(name, providerInfo, @"{0}:\{1}\{2}\".format(ProviderScheme, account, container), ProviderDescription, psCredential));
            }

            return(new PSDriveInfo(name, providerInfo, @"{0}:\{1}\{2}\{3}\".format(ProviderScheme, account, container, root), ProviderDescription, psCredential));
        }
        /*
         * public static string SetRoot(string root, PSCredential credential) {
         *  if (credential != null && credential.UserName.Contains(" "))
         *  {
         *      var sasUsernamePieces = credential.UserName.Split(' ');
         *      if (sasUsernamePieces.Length != 2)
         *      {
         *          throw new ClrPlusException("Wrong number of SASUsername pieces, should be 2");
         *
         *      }
         *
         *      if (!sasUsernamePieces[1].IsWebUri())
         *          throw new ClrPlusException("Second part of SASUsername must be a valid Azure Uri");
         *
         *      var containerUri = new Uri(sasUsernamePieces[1]);
         *
         *      //TODO Do I actually need to flip the slashes here? I'll do it to be safe for now
         *      root = @"azure:\\{0}\{1}".format(sasUsernamePieces[0], containerUri.AbsolutePath.Replace('/', '\\'));
         *
         *      SasAccountUri = "https://" + containerUri.Host;
         *      SasContainer = containerUri.AbsolutePath;
         *
         *
         *
         *
         *      //it's a SASToken!
         *  }
         *
         *  return root;
         * }*/

        private void Init(ProviderInfo provider, string root, PSCredential credential)
        {
            // first, try to get the account from the credential
            // if that fails, attempt to get it from the root.
            // http://account.blob.core.windows.net ... guess the account, have the base uri
            // https://account.blob.core.windows.net ... guess the account, have the base uri

            // azure://coapp ... -> guess the account, generate the baseuri

            // http://downloads.coapp.org  user must supply account, have the base uri
            // https://downloads.coapp.org user must supply account, have the base uri
            // http://127.0.0.1:10000/     user must supply account, have the base uri

            var parsedPath = Path.ParseWithContainer(root);


            //check if Credential is Sas


            if (credential != null && credential.UserName != null && credential.Password != null)
            {
                if (credential.UserName.Contains(SAS_GUID))
                {
                    _accountName = credential.UserName.Split(new[] {
                        SAS_GUID
                    }, StringSplitOptions.RemoveEmptyEntries)[0];
                    _isSas = true;
                }
                else
                {
                    _accountName = credential.UserName;
                }



                if (parsedPath.Scheme == ProviderScheme)
                {
                    // generate the baseuri like they do
                    _baseUri = new Uri("https://{0}.blob.core.windows.net/".format(_accountName));
                }
                else
                {
                    _baseUri = new Uri("{0}://{1}/".format(parsedPath.Scheme, parsedPath.HostAndPort));
                }

                Secret = credential.Password.ToUnsecureString();
            }
            else
            {
                if (parsedPath.Scheme == ProviderScheme)
                {
                    _accountName = parsedPath.HostName;
                    _baseUri     = new Uri("https://{0}.blob.core.windows.net/".format(_accountName));
                }
                else if (parsedPath.HostName.ToLower().EndsWith(".blob.core.windows.net"))
                {
                    _accountName = parsedPath.HostName.Substring(0, parsedPath.HostName.IndexOf('.'));
                    _baseUri     = new Uri("{0}://{1}/".format(parsedPath.Scheme, parsedPath.HostAndPort));
                }
                else
                {
                    // throw xxx
                }
            }

            Path = parsedPath;



            if (string.IsNullOrEmpty(parsedPath.HostAndPort) || string.IsNullOrEmpty(parsedPath.Scheme))
            {
                Path = parsedPath;
                return; // this is the root azure namespace.
            }

            var pi = provider as AzureProviderInfo;

            if (pi == null)
            {
                throw new ClrPlusException("Invalid ProviderInfo");
            }


            var alldrives = (pi.AddingDrives.Union(pi.Drives)).Select(each => each as AzureDriveInfo).ToArray();

            if (parsedPath.Scheme == ProviderScheme)
            {
                // it's being passed a full url to a blob storage
                Path = parsedPath;

                if (credential == null || credential.Password == null)
                {
                    // look for another mount off the same account and container for the credential
                    foreach (var d in alldrives.Where(d => d.HostAndPort == HostAndPort && d.ContainerName == ContainerName))
                    {
                        Secret = d.Secret;
                        return;
                    }
                    // now look for another mount off just the same account for the credential
                    foreach (var d in alldrives.Where(d => d.HostAndPort == HostAndPort))
                    {
                        Secret = d.Secret;
                        return;
                    }
                    throw new ClrPlusException("Missing credential information for {0} mount '{1}'".format(ProviderScheme, root));
                }

                Secret = credential.Password.ToUnsecureString();
                return;
            }

            // otherwise, it's an sub-folder off of another mount.
            foreach (var d in alldrives.Where(d => d.Name == parsedPath.Scheme))
            {
                Path = new Path {
                    HostAndPort = d.HostAndPort,
                    Container   = string.IsNullOrEmpty(d.ContainerName) ? parsedPath.HostAndPort : d.ContainerName,
                    SubPath     = string.IsNullOrEmpty(d.RootPath) ? parsedPath.SubPath : d.RootPath + '\\' + parsedPath.SubPath
                };
                Path.Validate();
                Secret = d.Secret;
                return;
            }
        }
 //DomainJoinParameterSet with certificate thumbprint and Join Option number
 public SetAzureServiceDomainJoinExtensionCmdletInfo(string domainName, string certificateThumbprint,
                                                     uint?joinOption, PSCredential unjoinDomainCredential, string[] role, string slot, string serviceName,
                                                     string thumbprintAlgorithm, bool restart, PSCredential credential, string oUPath)
     : this(domainName, unjoinDomainCredential, role, slot, serviceName, thumbprintAlgorithm, restart, credential, oUPath)
 {
     if (!string.IsNullOrEmpty(certificateThumbprint))
     {
         this.cmdletParams.Add(new CmdletParam("CertificateThumbprint", certificateThumbprint));
     }
     if (joinOption.HasValue)
     {
         this.cmdletParams.Add(new CmdletParam("JoinOption", joinOption.Value));
     }
 }
 //DomainJoinParameterSet with X509Certificate2 Certificate and Join Option number
 public SetAzureServiceDomainJoinExtensionCmdletInfo(string domainName, X509Certificate2 x509Certificate,
                                                     uint?joinOption, PSCredential unjoinDomainCredential, string[] role, string slot, string serviceName,
                                                     string thumbprintAlgorithm, bool restart, PSCredential credential, string oUPath)
     : this(domainName, unjoinDomainCredential, role, slot, serviceName, thumbprintAlgorithm, restart, credential, oUPath)
 {
     if (x509Certificate != null)
     {
         this.cmdletParams.Add(new CmdletParam("X509Certificate", x509Certificate));
     }
     if (joinOption.HasValue)
     {
         this.cmdletParams.Add(new CmdletParam("JoinOption", joinOption.Value));
     }
 }
Example #7
0
        /// <summary>
        /// Loads string from the given path
        /// </summary>
        /// <param name="cmdlet">cmdlet instance</param>
        /// <param name="path">path to load</param>
        /// <param name="credential">credential</param>
        /// <returns>string loaded</returns>
        internal static string LoadStringFromPath(PSCmdlet cmdlet, string path, PSCredential credential)
        {
            Debug.Assert(path != null);

            if (credential != null)
            {
                // New PSDrive

                using (UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(cmdlet, Path.GetDirectoryName(path), credential))
                {
                    string tempPath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetTempFileName()));

                    if (!cmdlet.InvokeProvider.Item.Exists(Path.Combine(drive.DriveName, Path.GetFileName(path))))
                    {
                        return null;
                    }

                    cmdlet.InvokeProvider.Item.Copy(new string[1] { Path.Combine(drive.DriveName, Path.GetFileName(path)) }, tempPath,
                        false, CopyContainers.CopyTargetContainer, true, true);

                    path = tempPath;
                }
            }

            if (File.Exists(path))
            {
                using (FileStream currentHelpInfoFile = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    StreamReader reader = new StreamReader(currentHelpInfoFile);

                    return reader.ReadToEnd();
                }
            }

            return null;
        }
Example #8
0
        /// <summary>
        /// Decode object.
        /// </summary>
        internal static object DecodeObject(object obj, Type type)
        {
            if (obj == null)
            {
                return(null);
            }

            Dbg.Assert(type != null, "Expected type != null");
            if (type == typeof(PSObject))
            {
                return(DecodePSObject(obj));
            }
            else if (type == typeof(ProgressRecord))
            {
                return(ProgressRecord.FromPSObjectForRemoting(PSObject.AsPSObject(obj)));
            }
            else if (IsKnownType(type))
            {
                return(obj);
            }
            else if (obj is SecureString)
            {
                return(obj);
            }
            else if (obj is PSCredential)
            {
                return(obj);
            }
            else if (obj is PSObject && type == typeof(PSCredential))
            {
                // BUGBUG: The following piece of code is a workaround
                // because custom serialization is busted. If rehydration
                // works correctly then PSCredential should be available
                PSObject     objAsPSObject = (PSObject)obj;
                PSCredential cred          = null;
                try
                {
                    cred = new PSCredential((string)objAsPSObject.Properties["UserName"].Value,
                                            (SecureString)objAsPSObject.Properties["Password"].Value);
                }
                catch (GetValueException)
                {
                    cred = null;
                }
                return(cred);
            }
            else if (obj is int && type.IsEnum)
            {
                return(Enum.ToObject(type, (int)obj));
            }
            else if (obj is string && type == typeof(CultureInfo))
            {
                return(new CultureInfo((string)obj));
            }
            else if (obj is PSObject && type == typeof(Exception))
            {
                return(DecodeException((PSObject)obj));
            }
            else if (obj is PSObject && type == typeof(object[]))
            {
                return(DecodeObjectArray((PSObject)obj));
            }
            else if (obj is PSObject && type.IsArray)
            {
                return(DecodeArray((PSObject)obj, type));
            }
            else if (obj is PSObject && IsCollection(type))
            {
                return(DecodeCollection((PSObject)obj, type));
            }
            else if (obj is PSObject && IsDictionary(type))
            {
                return(DecodeDictionary((PSObject)obj, type));
            }
            else if (obj is PSObject && IsEncodingAllowedForClassOrStruct(type))
            {
                return(DecodeClassOrStruct((PSObject)obj, type));
            }
            else if (obj is PSObject && IsGenericIEnumerableOfInt(type))
            {
                // we cannot create an instance of interface type like IEnumerable
                // Since a Collection implements IEnumerable, falling back to use
                // that.
                return(DecodeCollection((PSObject)obj, typeof(Collection <int>)));
            }
            else if (obj is PSObject && type == typeof(RemoteHostCall))
            {
                return(RemoteHostCall.Decode((PSObject)obj));
            }
            else if (obj is PSObject && type == typeof(RemoteHostResponse))
            {
                return(RemoteHostResponse.Decode((PSObject)obj));
            }
            else
            {
                throw RemoteHostExceptions.NewRemoteHostDataDecodingNotSupportedException(type);
            }
        }
        internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string connectionString, string certificateThumbprint, bool usessl)
        {
            ValidateSpecifiedAuthentication(authentication, credential, certificateThumbprint);

            ////if authentication is given
            int sessionFlags = 0;

            if (authentication.ToString() != null)
            {
                if (authentication.Equals(AuthenticationMechanism.None))
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNoAuthentication;
                }
                if (authentication.Equals(AuthenticationMechanism.Basic))
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseBasic | (int)WSManSessionFlags.WSManFlagCredUserNamePassword;
                }
                if (authentication.Equals(AuthenticationMechanism.Negotiate))
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNegotiate;
                }
                if (authentication.Equals(AuthenticationMechanism.Kerberos))
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseKerberos;
                }
                if (authentication.Equals(AuthenticationMechanism.Digest))
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseDigest | (int)WSManSessionFlags.WSManFlagCredUserNamePassword;
                }
                if (authentication.Equals(AuthenticationMechanism.Credssp))
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseCredSsp | (int)WSManSessionFlags.WSManFlagCredUserNamePassword;
                }
                if (authentication.Equals(AuthenticationMechanism.ClientCertificate))
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate;
                }
            }

            IWSManConnectionOptionsEx2 connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions();

            if (credential != null)
            {
                //connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions();
                System.Net.NetworkCredential nwCredential = new System.Net.NetworkCredential();
                if (credential.UserName != null)
                {
                    nwCredential = credential.GetNetworkCredential();
                    if (String.IsNullOrEmpty(nwCredential.Domain))
                    {
                        if (authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic))
                        {
                            connObject.UserName = nwCredential.UserName;
                        }
                        else
                        {
                            // just wanted to not use null domain, empty is actually fine
                            connObject.UserName = "******" + nwCredential.UserName;
                        }
                    }
                    else
                    {
                        connObject.UserName = nwCredential.Domain + "\\" + nwCredential.UserName;
                    }
                    connObject.Password = nwCredential.Password;
                    if (!authentication.Equals(AuthenticationMechanism.Credssp) || !authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic))
                    {
                        sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagCredUserNamePassword;
                    }
                }
            }

            if (certificateThumbprint != null)
            {
                connObject.CertificateThumbprint = certificateThumbprint;
                sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate;
            }

            if (sessionoption != null)
            {
                if (sessionoption.ProxyAuthentication != 0)
                {
                    int ProxyAccessflags         = 0;
                    int ProxyAuthenticationFlags = 0;
                    if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyIEConfig))
                    {
                        ProxyAccessflags = connObject.ProxyIEConfig();
                    }
                    else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyAutoDetect))
                    {
                        ProxyAccessflags = connObject.ProxyAutoDetect();
                    }
                    else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyNoProxyServer))
                    {
                        ProxyAccessflags = connObject.ProxyNoProxyServer();
                    }
                    else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyWinHttpConfig))
                    {
                        ProxyAccessflags = connObject.ProxyWinHttpConfig();
                    }

                    if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Basic))
                    {
                        ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseBasic();
                    }
                    else if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Negotiate))
                    {
                        ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseNegotiate();
                    }
                    else if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Digest))
                    {
                        ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseDigest();
                    }
                    if (sessionoption.ProxyCredential != null)
                    {
                        try
                        {
                            connObject.SetProxy(ProxyAccessflags, ProxyAuthenticationFlags, sessionoption.ProxyCredential.UserName, sessionoption.ProxyCredential.Password);
                        }
                        catch (Exception ex)
                        {
                            AssertError(ex.Message, false, null);
                        }
                    }
                    else
                    {
                        connObject.SetProxy((int)sessionoption.ProxyAccessType, (int)sessionoption.ProxyAuthentication, null, null);
                    }
                }
                if (sessionoption.SkipCACheck)
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipCACheck;
                }
                if (sessionoption.SkipCNCheck)
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipCNCheck;
                }
                if (sessionoption.SPNPort > 0)
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagEnableSpnServerPort;
                }
                if (sessionoption.UseUtf16)
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf16;
                }
                else
                {
                    //If UseUtf16 is false, then default Encoding is Utf8
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf8;
                }
                if (!sessionoption.UseEncryption)
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagNoEncryption;
                }
                if (sessionoption.SkipRevocationCheck)
                {
                    sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipRevocationCheck;
                }
            }
            else
            {
                //If SessionOption is null then, default Encoding is Utf8
                sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf8;
            }

            if (usessl)
            {
                sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseSsl;
            }

            IWSManSession m_SessionObj = null;

            try
            {
                m_SessionObj = (IWSManSession)wsmanObject.CreateSession(connectionString, sessionFlags, connObject);
                if (sessionoption != null)
                {
                    if (sessionoption.OperationTimeout > 0)
                    {
                        m_SessionObj.Timeout = sessionoption.OperationTimeout;
                    }
                }
            }
            catch (COMException ex)
            {
                AssertError(ex.Message, false, null);
            }
            return(m_SessionObj);
        }
Example #10
0
        /// <summary>
        /// This method is used by Connect-WsMan Cmdlet and New-Item of WsMan Provider to create connection to WsMan
        /// </summary>
        /// <param name="ParameterSetName"></param>
        /// <param name="connectionuri"></param>
        /// <param name="port"></param>
        /// <param name="computername"></param>
        /// <param name="applicationname"></param>
        /// <param name="usessl"></param>
        /// <param name="authentication"></param>
        /// <param name="sessionoption"></param>
        /// <param name="credential"></param>
        /// <param name="certificateThumbprint"></param>
        internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, int port, string computername, string applicationname, bool usessl, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string certificateThumbprint)
        {
            IWSManEx m_wsmanObject = (IWSManEx) new WSManClass();

            try
            {
                string connectionStr = CreateConnectionString(connectionuri, port, computername, applicationname);
                if (connectionuri != null)
                {
                    //in the format http(s)://server[:port/applicationname]
                    string[] constrsplit  = connectionStr.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None);
                    string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None);
                    computername = constrsplit1[1].Trim();
                }
                IWSManSession m_session = CreateSessionObject(m_wsmanObject, authentication, sessionoption, credential, connectionStr, certificateThumbprint, usessl);
                m_session.Identify(0);
                string key = computername;
                if (key == null)
                {
                    key = "localhost";
                }
                AddtoDictionary(key, m_session);
            }
            catch (IndexOutOfRangeException)
            {
                AssertError(_resourceMgr.GetString("NotProperURI"), false, connectionuri);
            }
            catch (Exception ex)
            {
                AssertError(ex.Message, false, computername);
            }
            finally
            {
                if (!String.IsNullOrEmpty(m_wsmanObject.Error))
                {
                    AssertError(m_wsmanObject.Error, true, computername);
                }
            }
        }
Example #11
0
        /// <summary>
        /// Used to resolve authentication from the parameters chosen by the user.
        /// User has the following options:
        /// 1. AuthMechanism + Credential
        /// 2. CertificateThumbPrint
        ///
        /// All the above are mutually exclusive.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// If there is ambiguity as specified above.
        /// </exception>
        static internal void ValidateSpecifiedAuthentication(AuthenticationMechanism authentication, PSCredential credential, string certificateThumbprint)
        {
            if ((credential != null) && (certificateThumbprint != null))
            {
                String message = FormatResourceMsgFromResourcetextS(
                    "AmbiguosAuthentication",
                    "CertificateThumbPrint", "credential");

                throw new InvalidOperationException(message);
            }

            if ((authentication != AuthenticationMechanism.Default) &&
                (authentication != AuthenticationMechanism.ClientCertificate) &&
                (certificateThumbprint != null))
            {
                String message = FormatResourceMsgFromResourcetextS(
                    "AmbiguosAuthentication",
                    "CertificateThumbPrint", authentication.ToString());

                throw new InvalidOperationException(message);
            }
        }
        protected override void ProcessRecord()
        {
            if (IgnoreSslErrors)
            {
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            }

            PSCredential creds = null;

            if (Credentials != null)
            {
                creds = Credentials.Credential;
            }
            SPOnlineConnection connection = null;

            if (ParameterSetName == ParameterSet_TOKEN)
            {
                connection = SPOnlineConnectionHelper.InstantiateSPOnlineConnection(new Uri(Url), Realm, AppId, AppSecret, Host, MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck);
            }
            else if (UseWebLogin)
            {
                connection = SPOnlineConnectionHelper.InstantiateWebloginConnection(new Uri(Url), MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck);
            }
            else if (UseAdfs)
            {
                if (creds == null)
                {
                    if ((creds = GetCredentials()) == null)
                    {
                        creds = Host.UI.PromptForCredential(Properties.Resources.EnterYourCredentials, "", "", "");
                    }
                }

                connection = SPOnlineConnectionHelper.InstantiateAdfsConnection(new Uri(Url), creds, Host, MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck);
            }
#if !ONPREMISES
            else if (ParameterSetName == ParameterSet_SPOMANAGEMENT)
            {
                connection = ConnectNativAAD(SPOManagementClientId, SPOManagementRedirectUri);
            }
            else if (ParameterSetName == ParameterSet_NATIVEAAD)
            {
                connection = ConnectNativAAD(ClientId, RedirectUri);
            }
            else if (ParameterSetName == ParameterSet_APPONLYAAD)
            {
                connection = SPOnlineConnectionHelper.InitiateAzureADAppOnlyConnection(new Uri(Url), ClientId, Tenant, CertificatePath, CertificatePassword, MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck, AzureEnvironment);
            }
            else if (ParameterSetName == ParameterSet_GRAPHWITHSCOPE)
            {
                ConnectGraphScopes();
            }
#endif
#if ONPREMISES
            else if (ParameterSetName == ParameterSet_HIGHTRUST)
            {
                connection = SPOnlineConnectionHelper.InstantiateHighTrustConnection(Url, ClientId, HighTrustCertificatePath, HighTrustCertificatePassword, HighTrustCertificateIssuerId, MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck);
            }
#endif
            else
            {
                if (!CurrentCredentials && creds == null)
                {
                    creds = GetCredentials();
                    if (creds == null)
                    {
                        creds = Host.UI.PromptForCredential(Properties.Resources.EnterYourCredentials, "", "", "");
                    }
                }
                connection = SPOnlineConnectionHelper.InstantiateSPOnlineConnection(new Uri(Url), creds, Host, CurrentCredentials, MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck, AuthenticationMode);
            }
#if !ONPREMISES
            if (MyInvocation.BoundParameters.ContainsKey("Scopes") && ParameterSetName != ParameterSet_GRAPHWITHSCOPE)
            {
                ConnectGraphScopes();
            }
#endif
            WriteVerbose($"PnP PowerShell Cmdlets ({System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}): Connected to {Url}");
            SPOnlineConnection.CurrentConnection = connection;
            if (CreateDrive && SPOnlineConnection.CurrentConnection.Context != null)
            {
                var provider = SessionState.Provider.GetAll().FirstOrDefault(p => p.Name.Equals(SPOProvider.PSProviderName, StringComparison.InvariantCultureIgnoreCase));
                if (provider != null)
                {
                    if (provider.Drives.Any(d => d.Name.Equals(DriveName, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        SessionState.Drive.Remove(DriveName, true, "Global");
                    }

                    var drive = new PSDriveInfo(DriveName, provider, string.Empty, Url, null);
                    SessionState.Drive.New(drive, "Global");
                }
            }
            if (ReturnConnection)
            {
                WriteObject(connection);
            }
        }
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, PSHost host, bool currentCredentials, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            ClientContext context = new ClientContext(url.AbsoluteUri);

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
            if (!currentCredentials)
            {
                try
                {
                    SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(credentials.UserName, credentials.Password);
                    context.Credentials = onlineCredentials;
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                    catch (ServerException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                }
                catch (ArgumentException)
                {
                    // OnPrem?
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                    catch (ServerException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                }
            }
            else
            {
                if (credentials != null)
                {
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                }
            }
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, credentials, url.ToString()));
        }
Example #14
0
 /// <summary>
 /// Creates a credential parameter from a NetworkCredential object
 /// </summary>
 /// <param name="Credential">The credentials to use</param>
 public DbaCredentialParameter(NetworkCredential Credential)
 {
     this.Credential = new PSCredential(String.Format("{0}\\{1}", Credential.Domain, Credential.UserName).Trim('\\'), Credential.SecurePassword);
 }
Example #15
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmdlet"></param>
        /// <param name="path"></param>
        /// <param name="credential"></param>
        internal UpdatableHelpSystemDrive(PSCmdlet cmdlet, string path, PSCredential credential)
        {
            for (int i = 0; i < 6; i++)
            {
                _driveName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                _cmdlet = cmdlet;

                // Need to get rid of the trailing \, otherwise New-PSDrive will not work...
                if (path.EndsWith("\\", StringComparison.OrdinalIgnoreCase) || path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
                {
                    path = path.Remove(path.Length - 1);
                }

                PSDriveInfo mappedDrive = cmdlet.SessionState.Drive.GetAtScope(_driveName, "local");

                if (mappedDrive != null)
                {
                    if (mappedDrive.Root.Equals(path))
                    {
                        return;
                    }

                    // Remove the drive after 5 tries
                    if (i < 5)
                    {
                        continue;
                    }

                    cmdlet.SessionState.Drive.Remove(_driveName, true, "local");
                }

                mappedDrive = new PSDriveInfo(_driveName, cmdlet.SessionState.Internal.GetSingleProvider("FileSystem"),
                    path, String.Empty, credential);

                cmdlet.SessionState.Drive.New(mappedDrive, "local");

                break;
            }
        }
Example #16
0
 // Token: 0x06001036 RID: 4150 RVA: 0x00031694 File Offset: 0x0002F894
 public MonadConnectionInfo(Uri server, PSCredential credentials, string shellUri, string typesFile, AuthenticationMechanism authenticationMechanism, ExchangeRunspaceConfigurationSettings.SerializationLevel serializationLevel, ExchangeRunspaceConfigurationSettings.ExchangeApplication clientApplication, string clientVersion) : this(server, credentials, shellUri, typesFile, authenticationMechanism, serializationLevel, clientApplication, clientVersion, 0, true)
 {
 }
Example #17
0
 internal PnPConnection(ClientContext context, ConnectionType connectionType, int minimalHealthScore, int retryCount, int retryWait, PSCredential credential, string clientId, string clientSecret, string url, string tenantAdminUrl, string pnpVersionTag, PSHost host, bool disableTelemetry, InitializationType initializationType)
     : this(context, connectionType, minimalHealthScore, retryCount, retryWait, credential, url, tenantAdminUrl, pnpVersionTag, host, disableTelemetry, initializationType)
 {
     ClientId     = clientId;
     ClientSecret = clientSecret;
 }
Example #18
0
 public SetAzureServiceRemoteDesktopExtensionCmdletInfo
     (string serviceName, PSCredential credential, X509Certificate2 cert, DateTime?expiration, string[] roles, string slot)
     : this(serviceName, credential, expiration, roles, slot)
 {
     this.cmdletParams.Add(new CmdletParam("X509Certificate", cert));
 }
Example #19
0
        internal PnPConnection(ClientContext context, GenericToken tokenResult, ConnectionType connectionType, int minimalHealthScore, int retryCount, int retryWait, PSCredential credential, string url, string tenantAdminUrl, string pnpVersionTag, PSHost host, bool disableTelemetry, InitializationType initializationType)
        {
            if (!disableTelemetry)
            {
                InitializeTelemetry(context, host, initializationType);
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var coreAssembly = Assembly.GetExecutingAssembly();

            UserAgent          = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            Context            = context;
            ConnectionType     = connectionType;
            MinimalHealthScore = minimalHealthScore;
            RetryCount         = retryCount;
            RetryWait          = retryWait;
            PSCredential       = credential;
            TenantAdminUrl     = tenantAdminUrl;
            ContextCache       = new List <ClientContext> {
                context
            };
            PnPVersionTag                = pnpVersionTag;
            Url                          = (new Uri(url)).AbsoluteUri;
            ConnectionMethod             = ConnectionMethod.AccessToken;
            ClientId                     = DeviceLoginClientId;
            Tenant                       = tokenResult.ParsedToken.Claims.FirstOrDefault(c => c.Type == "tid").Value;
            context.ExecutingWebRequest += (sender, args) =>
            {
                args.WebRequestExecutor.WebRequest.UserAgent            = UserAgent;
                args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + tokenResult.AccessToken;
            };
        }
        //constructors for each parameter set

        //BasicDomainParameterSet
        private SetAzureServiceDomainJoinExtensionCmdletInfo(string domainName, PSCredential unjoinDomainCredential,
                                                             string[] role, string slot, string serviceName, string thumbprintAlgorithm, bool restart, PSCredential credential, string oUPath)
            : this(DomainJoinExtensionParameterSetType.DomainName, domainName, role, slot, serviceName, thumbprintAlgorithm, restart, credential)
        {
            if (unjoinDomainCredential != null)
            {
                this.cmdletParams.Add(new CmdletParam("UnjoinDomainCredential", unjoinDomainCredential));
            }
            if (!string.IsNullOrEmpty(oUPath))
            {
                this.cmdletParams.Add(new CmdletParam("OUPath", oUPath));
            }
        }
        /// <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 = Util.Sprintf(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);
            }
        }
        public static CredentialEntry CreateCredential(string targetName, CredentialType type, CredentialPersist persist, PSCredential credential)
        {
            NativeMethods.Credential nativeCredential = new NativeMethods.Credential()
            {
                TargetName         = targetName,
                Type               = (NativeMethods.CredentialType)type,
                Persist            = (NativeMethods.CredentialPersist)persist,
                AttributeCount     = 0,
                UserName           = credential.UserName,
                CredentialBlob     = Marshal.StringToCoTaskMemUni(credential.GetNetworkCredential().Password),
                CredentialBlobSize = (uint)Encoding.Unicode.GetByteCount(credential.GetNetworkCredential().Password)
            };

            try
            {
                if (NativeMethods.CredWrite(ref nativeCredential, 0))
                {
                    return(GetCredential(targetName, type));
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (nativeCredential.CredentialBlob != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(nativeCredential.CredentialBlob);
                }
            }
        }
Example #23
0
        public void LoadExchangeDAG()
        {
            if (ExchangeServerTextBox.Text.ToLower().Contains("http://") == false && ExchangeServerTextBox.Text.ToLower().Contains("https://") == false)
            {
                errorDiv.InnerHtml   = "Not a Valid Exchange Server Address!. Server Address shoud be in the form of 'https://myexchange.com'";
                errorDiv.Style.Value = "display: block";
                return;
            }

            DataTable dt       = new DataTable();
            string    strError = "";
            string    UserName = "";
            string    Password = "";

            if (CredentialsComboBox.Text != "")
            {
                ArrayList Cred = getCredentials();
                if (Cred.Count > 1)
                {
                    UserName = Cred[0].ToString();
                    Password = Cred[1].ToString();

                    if (UserName == "" || Password == "")
                    {
                        errorDiv.InnerHtml   = "User Id or Password not set for the selected Credentials";
                        errorDiv.Style.Value = "display: block";
                        return;
                    }
                }
            }
            else
            {
                UserName = UserIdtextBox.Text;                // "jnittech\\administrator";
                Password = PasswordTextbox.Text;              // "Pa$$w0rd";
                if (UserName == "" || Password == "")
                {
                    errorDiv.InnerHtml   = "Please Enter the User Id and Password.";
                    errorDiv.Style.Value = "display: block";
                    return;
                }
            }
            Uid = UserName;
            Pwd = Password;


            string IPAddress = ExchangeServerTextBox.Text;            // "https://jnittech-exchg1.jnittech.com";
            //ViewState["Pwd"] = Password;
            //ViewState.Add("Pwd", Password);
            bool updatedsrv = VSWebBL.SettingBL.SettingsBL.Ins.UpdateSvalue("Primary Exchange Server", ExchangeServerTextBox.Text, VSWeb.Constants.Constants.SysString);

            System.Uri uri = new Uri(IPAddress + "/powershell?serializationLevel=Full");
            System.Security.SecureString securePassword = String2SecureString(Password);
            PSCredential creds      = new PSCredential(UserName, securePassword);
            Runspace     runspace   = RunspaceFactory.CreateRunspace();
            PowerShell   powershell = PowerShell.Create();

            PSCommand command = new PSCommand();

            command.AddCommand("New-PSSession");
            command.AddParameter("ConfigurationName", "Microsoft.Exchange");
            command.AddParameter("ConnectionUri", uri);
            command.AddParameter("Credential", creds);
            command.AddParameter("Authentication", "Default");
            System.Collections.ObjectModel.Collection <PSObject> results = new System.Collections.ObjectModel.Collection <PSObject>();

            PSSessionOption sessionOption = new PSSessionOption();

            sessionOption.SkipCACheck         = true;
            sessionOption.SkipCNCheck         = true;
            sessionOption.SkipRevocationCheck = true;

            command.AddParameter("SessionOption", sessionOption);
            powershell.AddScript(@"set-executionpolicy unrestricted");
            powershell.Commands = command;

            try
            {
                using (runspace)
                {
                    runspace.Open();
                    powershell.Runspace = runspace;
                    System.Collections.ObjectModel.Collection <PSSession> result = powershell.Invoke <PSSession>();

                    //foreach (ErrorRecord current in powershell.Streams.Error)
                    //{
                    //    strError += "Exception Importing Servers: " + current.Exception.ToString() + ",\r\nInner Exception: " + current.Exception.InnerException;
                    //    errorDiv.InnerHtml = strError;
                    //    errorDiv.Style.Value = "display: block";
                    //    return;
                    //}

                    if (result.Count == 0)
                    {
                        //errorDiv.InnerHtml = "Unexpected number of Remote Runspace connections returned.";
                        //errorDiv.Style.Value = "display: block";
                        //return;
                        foreach (ErrorRecord current in powershell.Streams.Error)
                        {
                            strError            += "Exception Importing Servers: " + current.Exception.ToString() + ",\r\nInner Exception: " + current.Exception.InnerException;
                            errorDiv.InnerHtml   = strError;
                            errorDiv.Style.Value = "display: block";
                            return;
                        }
                    }
                    PSSession pssession = (PSSession)result[0];
                    command = new PSCommand();
                    command.AddCommand("Set-Variable");
                    command.AddParameter("Name", "ra");
                    command.AddParameter("Value", result[0]);
                    powershell.Commands = command;;
                    powershell.Invoke();


                    command = new PSCommand();
                    command.AddScript("Import-PSSession -Session $ra -CommandName Get-DatabaseAvailabilityGroup, Test-ReplicationHealth, Get-MailboxDatabase, Get-MailboxDatabaseCopyStatus");
                    powershell.Commands = command;
                    powershell.Invoke();

                    powershell.Streams.Error.Clear();

                    String str = "Get-DatabaseAvailabilityGroup | Select-Object -Property Name,WitnessServer";
                    powershell.AddScript(str);

                    results = powershell.Invoke();

                    dt.Columns.Add("DAGName", typeof(string));
                    dt.Columns.Add("WitnessServer", typeof(string));
                    if (results.Count > 0)
                    {
                        foreach (PSObject ps in results)
                        {
                            string Fqdn = ps.Properties["Name"].Value.ToString();
                            string name = ps.Properties["Name"].Value.ToString();
                            //load exchange servers
                            errorDiv.Style.Value     = "display: none;";
                            errorinfoDiv.Style.Value = "display: none";
                            DataTable LocationsDataTable = new DataTable();
                            LocationsDataTable = VSWebBL.SecurityBL.LocationsBL.Ins.GetAllData();
                            if (LocationsDataTable.Rows.Count > 0)
                            {
                                LocComboBox.DataSource = LocationsDataTable;
                                LocComboBox.TextField  = "Location";
                                LocComboBox.ValueField = "Location";
                                LocComboBox.DataBind();
                                LocIDComboBox.DataSource = LocationsDataTable;
                                LocIDComboBox.TextField  = "ID";
                                LocIDComboBox.ValueField = "ID";
                                LocIDComboBox.DataBind();

                                try
                                {
                                    DataRow[] foundRows;

                                    DataTable importedDT;
                                    importedDT = VSWebBL.ConfiguratorBL.AlertsBL.Ins.GetServer();
                                    foundRows  = importedDT.Select("ServerName = '" + name + "'");
                                    if (foundRows.Length == 0)
                                    {
                                        DataRow dr = dt.NewRow();
                                        dr["DAGName"]       = name;
                                        dr["WitnessServer"] = name;
                                        dt.Rows.Add(dr);
                                        dr = dt.NewRow();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    errorDiv.InnerHtml       = "The following error has occurred: " + ex.Message;
                                    errorDiv.Style.Value     = "display: block";
                                    errorinfoDiv.Style.Value = "display: block";
                                    Log.Entry.Ins.WriteHistoryEntry(DateTime.Now.ToString() + " Exception - " + ex);
                                    return;
                                }
                            }
                            else
                            {
                                errorDiv.InnerHtml   = "All imported servers must be assigned to a location. There were no locations found. Please create at least one location entry using the 'Setup & Security - Maintain Server Locations' menu option.";
                                errorDiv.Style.Value = "display: block";
                                return;
                            }
                        }
                        results.Clear();
                        result.Clear();
                        if (dt.Rows.Count > 0)
                        {
                            infoDiv.Style.Value        = "display: block";
                            SrvCheckBoxList.DataSource = dt;
                            SrvCheckBoxList.TextField  = "DAGName";
                            SrvCheckBoxList.ValueField = "DAGName";
                            SrvCheckBoxList.DataBind();
                            IPCheckBoxList.DataSource = dt;
                            IPCheckBoxList.TextField  = "DAGName";
                            IPCheckBoxList.ValueField = "DAGName";
                            IPCheckBoxList.DataBind();
                            ASPxRoundPanel1.Visible = true;
                        }
                        else
                        {
                            errorDiv.InnerHtml   = "There are no new servers in the address book that have not already been imported into VitalSigns.";
                            errorDiv.Style.Value = "display: block";
                            return;
                        }
                        if (pssession != null)
                        {
                            Command cmd = new Command("remove-pssession");
                            cmd.Parameters.Add("id", pssession.Id);
                            powershell.Commands.Clear();
                            powershell.Commands.AddCommand(cmd);
                            powershell.Invoke();
                        }
                        if (runspace != null)
                        {
                            if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
                            {
                                runspace.Close();
                                runspace.Dispose();
                                powershell.Dispose();
                            }
                        }
                    }
                    else
                    {
                        errorDiv.InnerHtml   = "No Servers Found!.";
                        errorDiv.Style.Value = "display: block";
                        return;
                    }
                }
                GC.Collect();
            }
            catch (Exception ex)
            {
                errorDiv.InnerHtml   = ex.Message.ToString();
                errorDiv.Style.Value = "display: block";
                return;
            }
        }
Example #24
0
 public AzureDriveInfo(string name, ProviderInfo provider, string root, string description, PSCredential credential)
     : base(name, provider, root, description, credential)
 {
     Init(provider, root, credential);
 }
Example #25
0
 public PowerShellCommonSession(ILogger logger, string targetServer, PowershellConnectionType connectionType, PSCredential credentials)
 {
     this.RemotePowershellSession = new RemotePowershellSession(logger, targetServer, connectionType, true, new Func <string, bool>(this.ShouldInvokePowershellCommandHandler));
     this.RemotePowershellSession.Connect(credentials, Thread.CurrentThread.CurrentUICulture);
 }
        public static int SetUpDefaultRemoteAppCollectionSet(Mock <IRemoteAppManagementClient> clientMock, string collectionName, string subscriptionId, string billingPlan, string imageName, PSCredential credential, string domainName, string trackingId)
        {
            NetworkCredential cred = credential != null?credential.GetNetworkCredential() : null;

            CollectionCreationDetails collectionDetails = new CollectionCreationDetails()
            {
                Name              = collectionName,
                PlanName          = billingPlan,
                TemplateImageName = imageName,
                Mode              = CollectionMode.Apps,
                Description       = "unit test"
            };

            if (cred != null)
            {
                collectionDetails.AdInfo = new ActiveDirectoryConfig()
                {
                    DomainName = domainName,
                    UserName   = cred.UserName,
                    Password   = cred.Password
                };
            }

            List <Collection> collectionList = new List <Collection>()
            {
                new Collection()
                {
                    Name              = collectionDetails.Name,
                    PlanName          = collectionDetails.PlanName,
                    TemplateImageName = collectionDetails.TemplateImageName,
                    Mode              = collectionDetails.Mode,
                    Description       = collectionDetails.Description,
                    Status            = "Active",
                    AdInfo            = collectionDetails.AdInfo != null ? collectionDetails.AdInfo : null
                }
            };

            OperationResultWithTrackingId response = new OperationResultWithTrackingId()
            {
                StatusCode = System.Net.HttpStatusCode.Accepted,
                TrackingId = trackingId,
                RequestId  = "222-3456-789"
            };

            mockTrackingId = new List <TrackingResult>()
            {
                new TrackingResult(response)
            };

            ISetup <IRemoteAppManagementClient, Task <OperationResultWithTrackingId> > setup =
                clientMock.Setup(
                    c => c.Collections.SetAsync(
                        collectionName,
                        It.IsAny <bool>(),
                        It.IsAny <bool>(),
                        It.IsAny <CollectionUpdateDetails>(),
                        It.IsAny <CancellationToken>()));

            setup.Returns(Task.Factory.StartNew(() => response));

            mockCollectionList = collectionList;

            return(mockCollectionList.Count);
        }
Example #27
0
        // Нажата кнопка руссификации папок сотрудника
        private void btRussificationFolder_Click(object sender, RoutedEventArgs e)
        {
            if (!_userIsSelected)
            {
                MessageBox.Show("Не выбран пользователь!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (string.IsNullOrWhiteSpace(_pathToConfig))
            {
                MessageBox.Show("Отсутствует конфигурационный файл плагина!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            string errorMesg           = "";
            string userToRussification = dnUserForChange.Text;

            Thread t = new Thread(() =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Clear();
                    _processRun.Add(new ProcessRunData {
                        Text = "---- Руссификация папок пользователя " + userToRussification + " ----"
                    });
                    btSelectUser.IsEnabled          = false;
                    btRussificationFolder.IsEnabled = false;
                }));

                #region Чтение конфигурационного файла плагина
                ProcessRunData itemProcess = new ProcessRunData {
                    Text = "Чтение конфигурационного файла плагина..."
                };
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Чтение конфигурационного файла плагина..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                configData = GetConfigData(_pathToConfig, ref errorMesg);
                if (!string.IsNullOrWhiteSpace(errorMesg))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Ошибка чтения конфигурационного файла:\r\n" + errorMesg;
                    }));
                    return;
                }
                if (!configData.ContainsKey("mailserver"))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text  = "Отсутсвуют требуемые параметры в конфигурационном файле!!!";
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Чтение конфигурационного файла плагина";
                }));
                #endregion

                //============================================================
                PSCredential credential                = new PSCredential(_login, _password);
                WSManConnectionInfo connectionInfo     = new WSManConnectionInfo((new Uri(configData["mailserver"])), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                Runspace runspace     = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                PowerShell powershell = PowerShell.Create();
                PSCommand command     = new PSCommand();
                //============================================================

                #region Подключение к Exchange Server
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Подключение к Exchange Server..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));
                try
                {
                    runspace.Open();
                    powershell.Runspace = runspace;
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image               = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text                = "Ошибка подключения к Exchange Server:\r\n" + exp.Message;
                        btSelectUser.IsEnabled          = true;
                        btRussificationFolder.IsEnabled = true;
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Подключение к Exchange Server";
                }));
                #endregion

                #region  уссификация папок пользователя
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "Руссификация папок пользователя " + userToRussification + "..."
                    });
                    itemProcess = _processRun[_processRun.Count - 1];
                }));

                try
                {
                    command.AddCommand("Set-MailboxRegionalConfiguration");
                    command.AddParameter("Identity", userToRussification);
                    command.AddParameter("Language", "ru-RU");
                    command.AddParameter("LocalizeDefaultFolderName", true);
                    powershell.Commands = command;
                    powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            itemProcess.Text = "";
                        }));
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка руссификации папок пользователя:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                                itemProcess.Text += errorMsg;
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            btSelectUser.IsEnabled          = true;
                            btRussificationFolder.IsEnabled = true;
                        }));
                        return;
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        itemProcess.Image               = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/stop.ico", UriKind.RelativeOrAbsolute));
                        itemProcess.Text                = "Ошибка руссификации папок пользователя:\r\n" + exp.Message;
                        btSelectUser.IsEnabled          = true;
                        btRussificationFolder.IsEnabled = true;
                    }));
                    return;
                }

                Dispatcher.BeginInvoke(new Action(() =>
                {
                    itemProcess.Image = new BitmapImage(new Uri(@"/RussificationOutlookFolders;component/Resources/select.ico", UriKind.RelativeOrAbsolute));
                    itemProcess.Text  = "Руссификация папок пользователя " + userToRussification;
                }));

                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
                #endregion

                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _processRun.Add(new ProcessRunData {
                        Text = "---- Процесс завершён! ----"
                    });
                    dnUserForChange.Text            = "";
                    _userIsSelected                 = false;
                    dnUserForChange.FontWeight      = FontWeights.Normal;
                    dnUserForChange.TextDecorations = null;
                    btSelectUser.IsEnabled          = true;
                    btRussificationFolder.IsEnabled = true;
                }));
            });

            t.IsBackground = true;
            t.Start();
        }
        public SPOnlineConnection(ClientContext context, TokenResult tokenResult, ConnectionType connectionType, int minimalHealthScore, int retryCount, int retryWait, PSCredential credential, string url, string tenantAdminUrl, string pnpVersionTag, PSHost host, bool disableTelemetry)
        {
            if (!disableTelemetry)
            {
                InitializeTelemetry(context, host);
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            TokenResult = tokenResult;
            var coreAssembly = Assembly.GetExecutingAssembly();

            userAgent          = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            Context            = context;
            ConnectionType     = connectionType;
            MinimalHealthScore = minimalHealthScore;
            RetryCount         = retryCount;
            RetryWait          = retryWait;
            PSCredential       = credential;
            TenantAdminUrl     = tenantAdminUrl;
            ContextCache       = new List <ClientContext> {
                context
            };
            PnPVersionTag                = pnpVersionTag;
            Url                          = (new Uri(url)).AbsoluteUri;
            ConnectionMethod             = ConnectionMethod.AccessToken;
            context.ExecutingWebRequest += (sender, args) =>
            {
                args.WebRequestExecutor.WebRequest.UserAgent            = userAgent;
                args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + CurrentConnection.AccessToken;
            };
        }
Example #29
0
        protected override void ProcessRecord()
        {
            PSCredential creds = null;

            if (Credentials != null)
            {
                creds = Credentials.Credential;
            }

            if (ParameterSetName == ParameterSet_TOKEN)
            {
                SPOnlineConnection.CurrentConnection = SPOnlineConnectionHelper.InstantiateSPOnlineConnection(new Uri(Url), Realm, AppId, AppSecret, Host, MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck);
            }
            else if (UseWebLogin)
            {
                SPOnlineConnection.CurrentConnection = SPOnlineConnectionHelper.InstantiateWebloginConnection(new Uri(Url), MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck);
            }
            else if (UseAdfs)
            {
                if (creds == null)
                {
                    if ((creds = GetCredentials()) == null)
                    {
                        creds = Host.UI.PromptForCredential(Properties.Resources.EnterYourCredentials, "", "", "");
                    }
                }

                SPOnlineConnection.CurrentConnection = SPOnlineConnectionHelper.InstantiateAdfsConnection(new Uri(Url), creds, Host, MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck);
            }
#if !ONPREMISES
            else if (ParameterSetName == ParameterSet_NATIVEAAD)
            {
                if (ClearTokenCache)
                {
                    string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string configFile    = Path.Combine(appDataFolder, "SharePointPnP.PowerShell\\tokencache.dat");
                    if (File.Exists(configFile))
                    {
                        File.Delete(configFile);
                    }
                }
                SPOnlineConnection.CurrentConnection = SPOnlineConnectionHelper.InitiateAzureADNativeApplicationConnection(new Uri(Url), ClientId, new Uri(RedirectUri), MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck, AzureEnvironment);
            }
            else if (ParameterSetName == ParameterSet_APPONLYAAD)
            {
                SPOnlineConnection.CurrentConnection = SPOnlineConnectionHelper.InitiateAzureADAppOnlyConnection(new Uri(Url), ClientId, Tenant, CertificatePath, CertificatePassword, MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck, AzureEnvironment);
            }
#endif
            else
            {
                if (!CurrentCredentials && creds == null)
                {
                    creds = GetCredentials();
                    if (creds == null)
                    {
                        creds = Host.UI.PromptForCredential(Properties.Resources.EnterYourCredentials, "", "", "");
                    }
                }
                SPOnlineConnection.CurrentConnection = SPOnlineConnectionHelper.InstantiateSPOnlineConnection(new Uri(Url), creds, Host, CurrentCredentials, MinimalHealthScore, RetryCount, RetryWait, RequestTimeout, TenantAdminUrl, SkipTenantAdminCheck, AuthenticationMode);
            }
            WriteVerbose($"PnP PowerShell Cmdlets ({System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}): Connected to {Url}");

            if (CreateDrive && SPOnlineConnection.CurrentConnection.Context != null)
            {
                var provider = SessionState.Provider.GetAll().FirstOrDefault(p => p.Name.Equals("SPO", StringComparison.InvariantCultureIgnoreCase));
                if (provider != null)
                {
                    if (provider.Drives.Any(d => d.Name.Equals(DriveName, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        SessionState.Drive.Remove(DriveName, true, "Global");
                    }

                    var drive = new PSDriveInfo(DriveName, provider, string.Empty, Url, null);
                    SessionState.Drive.New(drive, "Global");
                }
            }
        }
Example #30
0
 /// <summary>
 /// Creates a credential parameter from a PSCredential object
 /// </summary>
 /// <param name="Credential">A PSCredential object</param>
 public DbaCredentialParameter(PSCredential Credential)
 {
     this.Credential = Credential;
 }
Example #31
0
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, PSHost host, bool currentCredentials, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool disableTelemetry, bool skipAdminCheck = false, ClientAuthenticationMode authenticationMode = ClientAuthenticationMode.Default)
        {
            var context = new PnPClientContext(url.AbsoluteUri);

            context.RetryCount      = retryCount;
            context.Delay           = retryWait * 1000;
            context.ApplicationName = Properties.Resources.ApplicationName;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016 || SP2019
            context.DisableReturnValueCache = true;
#endif
            context.RequestTimeout = requestTimeout;

            context.AuthenticationMode = authenticationMode;

            if (authenticationMode == ClientAuthenticationMode.FormsAuthentication)
            {
                var formsAuthInfo = new FormsAuthenticationLoginInfo(credentials.UserName, EncryptionUtility.ToInsecureString(credentials.Password));
                context.FormsAuthenticationLoginInfo = formsAuthInfo;
            }

            if (!currentCredentials)
            {
                try
                {
                    SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(credentials.UserName, credentials.Password);
                    context.Credentials = onlineCredentials;
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                    catch (ServerException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                }
                catch (ArgumentException)
                {
                    // OnPrem?
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                    catch (ServerException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                }
            }
            else
            {
                if (credentials != null)
                {
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                }
            }
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry);
            spoConnection.ConnectionMethod = Model.ConnectionMethod.Credentials;
            return(spoConnection);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="powerShellVersion"></param>
        /// <param name="credential"></param>
        /// <param name="initializationScript"></param>
        /// <param name="useWow64"></param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            string psWow64Path = s_PSExePath;

            if (useWow64)
            {
                string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                    procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                {
                    psWow64Path = s_PSExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                    if (!File.Exists(psWow64Path))
                    {
                        string message =
                            PSRemotingErrorInvariants.FormatResourceString(
                                RemotingErrorIdStrings.IPCWowComponentNotPresent,
                                psWow64Path);
                        throw new PSInvalidOperationException(message);
                    }
                }
            }

            string processArguments = string.Empty;
            // Adding Version parameter to powershell.exe
            // Version parameter needs to go before all other parameters because the native layer looks for Version or 
            // PSConsoleFile parameters before parsing other parameters.
            // The other parameters get parsed in the managed layer.
            Version tempVersion = powerShellVersion ?? PSVersionInfo.PSVersion;
            processArguments = string.Format(CultureInfo.InvariantCulture,
                       "-Version {0}", new Version(tempVersion.Major, tempVersion.Minor));

            processArguments = string.Format(CultureInfo.InvariantCulture,
                "{0} -s -NoLogo -NoProfile", processArguments);

            if (initializationScript != null)
            {
                string scripBlockAsString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scripBlockAsString))
                {
                    string encodedCommand =
                        Convert.ToBase64String(Encoding.Unicode.GetBytes(scripBlockAsString));
                    processArguments = string.Format(CultureInfo.InvariantCulture,
                        "{0} -EncodedCommand {1}", processArguments, encodedCommand);
                }
            }

            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName = useWow64 ? psWow64Path : s_PSExePath,
                Arguments = processArguments,
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                LoadUserProfile = true,
            };

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
#if CORECLR
                _startInfo.PasswordInClearText = ClrFacade.ConvertSecureStringToString(credential.Password);
#else
                _startInfo.Password = credential.Password;
#endif
            }

            Process = new Process { StartInfo = _startInfo, EnableRaisingEvents = true };
        }
Example #33
0
 // Token: 0x06001033 RID: 4147 RVA: 0x0003164D File Offset: 0x0002F84D
 public MonadConnectionInfo(Uri server, PSCredential credentials, string shellUri, string typesFile, AuthenticationMechanism authenticationMechanism) : this(server, credentials, shellUri, typesFile, authenticationMechanism, ExchangeRunspaceConfigurationSettings.SerializationLevel.Partial)
 {
 }