示例#1
0
        public void Should_be_possible_to_build_a_WMI_Query_Language()
        {
            string wql = new WQLBuilder()
                         .WithWmiClass("cim_logicalfile")
                         .AddParameter("drive", "c:")
                         .AddParameter("path", "\\temp\\")
                         .Build().ToLower().Trim();


            List <String> wqlLines = this.GetSplittedWQL(wql);

            Assert.AreEqual(3, wqlLines.Count);
            Assert.AreEqual("select * from cim_logicalfile", wqlLines[0].ToLower().Trim());
            Assert.AreEqual("where drive = 'c:'", wqlLines[1].ToLower().Trim());
            Assert.AreEqual("and path = '\\temp\\'", wqlLines[2].ToLower().Trim());
        }
示例#2
0
        private IEnumerable <WindowsAccount> GetAllLocalGroups()
        {
            var wqlToGetAllLocalGroups =
                new WQLBuilder()
                .WithWmiClass("Win32_Group")
                .AddParameter("localaccount", "1")
                .Build();

            var wqlResult = this.WmiProvider.ExecuteWQL(wqlToGetAllLocalGroups);

            return
                (wqlResult
                 .Select(g =>
                         new WindowsAccount(
                             g.GetFieldValueAsString("Name"),
                             (bool?)g.GetValueOf("Disabled"),
                             g.GetFieldValueAsString("SID"),
                             AccountType.Group)
                         ).ToList());
        }
示例#3
0
        private IEnumerable <WindowsAccount> GetAllBuiltinAccounts()
        {
            var wqlAllGetBuiltinAccounts = new WQLBuilder().WithWmiClass("Win32_SystemAccount").Build();

            var wqlResult = this.WmiProvider.ExecuteWQL(wqlAllGetBuiltinAccounts);

            if (wqlResult != null && wqlResult.Count() > 0)
            {
                return
                    (wqlResult.Select(
                         wql =>
                         new WindowsAccount(
                             wql.GetFieldValueAsString("Name"),
                             (bool?)true,
                             wql.GetFieldValueAsString("SID"),
                             AccountType.User)));
            }

            return(new WindowsAccount[] { });
        }
示例#4
0
        public void Should_be_possible_to_build_a_WMI_Query_Language_adding_all_parameters_at_once()
        {
            Dictionary <string, string> allParameters = new Dictionary <string, string>();

            allParameters.Add("drive", "d:");
            allParameters.Add("path", "\\fakedirectory\\");
            allParameters.Add("filename", "fakefile");
            allParameters.Add("extension", "fex");

            string wql = new WQLBuilder().WithWmiClass("cim_logicalfile").AddParameters(allParameters).Build();

            List <String> wqlLines = this.GetSplittedWQL(wql);

            Assert.AreEqual(5, wqlLines.Count);
            Assert.AreEqual("select * from cim_logicalfile", wqlLines[0].ToLower().Trim());
            Assert.AreEqual("where drive = 'd:'", wqlLines[1].ToLower().Trim());
            Assert.AreEqual("and path = '\\fakedirectory\\'", wqlLines[2].ToLower().Trim());
            Assert.AreEqual("and filename = 'fakefile'", wqlLines[3].ToLower().Trim());
            Assert.AreEqual("and extension = 'fex'", wqlLines[4].ToLower().Trim());
        }
        private WmiDataProvider GetWmiProviderMockWithNoWmiResultBehavior()
        {
            // This mocked WmiDataProvider must be used in order to test GetAllGroupsByUser method.
            var mocks           = new MockRepository();
            var fakeWmiProvider = mocks.StrictMock <WmiDataProvider>();

            // Create expectation for first calling (to get computer name).
            var wqlToGetComputerName          = new WQLBuilder().WithWmiClass("Win32_ComputerSystem").Build();
            var fakeWin32ComputerSystemRecord = new WmiObject();

            fakeWin32ComputerSystemRecord.Add("Name", FAKE_COMPUTER_NAME);
            fakeWin32ComputerSystemRecord.Add("DomainRole", 1);
            Expect.Call(fakeWmiProvider.ExecuteWQL(wqlToGetComputerName)).Return(new[] { fakeWin32ComputerSystemRecord });

            // Create expectation for second calling (to get all local groups);
            var wqlToGetAllLocalGroups = new WQLBuilder().WithWmiClass("Win32_Group").AddParameter("localaccount", "1").Build();
            var fakeWin32GroupRecords  = new List <WmiObject>();

            fakeWin32GroupRecords.Add(NewWmiObjectForFakeLocalGroup("Administrators", "S-1-5-32-544"));
            fakeWin32GroupRecords.Add(NewWmiObjectForFakeLocalGroup("Backup Operators", "S-1-5-32-551"));
            fakeWin32GroupRecords.Add(NewWmiObjectForFakeLocalGroup("Users", "S-1-5-32-545"));
            Expect.Call(fakeWmiProvider.ExecuteWQL(wqlToGetAllLocalGroups)).Return(fakeWin32GroupRecords);

            // Create expectation for each get group component calling...
            CreateExpectationForGetGroupComponent(fakeWmiProvider, "Administrators");
            CreateExpectationForGetGroupComponent(fakeWmiProvider, "Backup Operators");
            CreateExpectationForGetGroupComponent(fakeWmiProvider, "Users");

            // Create expectation for each get user details calling (3 first times) and get user SID (3 last times)
            Expect.Call(fakeWmiProvider.ExecuteWQL(null)).IgnoreArguments().Repeat.Times(6).Return(null);

            var wqlAllGetBuiltinAccounts = new WQLBuilder().WithWmiClass("Win32_SystemAccount").Build();

            Expect.Call(fakeWmiProvider.ExecuteWQL(wqlAllGetBuiltinAccounts)).Return(null);

            mocks.ReplayAll();

            return(fakeWmiProvider);
        }
示例#6
0
        public bool FileExists(string localFilepath)
        {
            /* IMPORTANT
             * BEFORE CHANGING OR REFACTORING THIS METHOD, YOU MUST READ THIS NOTICE.
             *
             * The code below sounds confusing, but there is a reason to be like that.
             * The first issue is that the System.IO.File.Exists and Directory.Exists behavior (see Remarks Session in http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx).
             * If an error such as "Acess Denied" or "Invalid Path" occurs during those methods calling,
             * .NET API will return FALSE instead of throwing an exception. Thus, when the return is false,
             * maybe the file or directory exists, but some error occurred.
             * The best way to find out if a file or directory exists is trying to open them. The methods
             * that open a file (or directory) will throw an exception if it does not exist.
             *
             * Now, we have a second issue:
             * To do the above, it is necessary that the administrative share on the remote machine is enabled.
             * It´s very common that is not enabled.
             * The solution to this issue is to make another attempt in order to check file (or directory) existence.
             * You can make that through a WMI query.
             *
             * So, we have three ways to check File Existence. Why not use only WMI ?
             * Because, we have a third issue: performance.
             * In some scenarios, this WMI Query can be really slow.
             * OK, but why the code below still using File.Exists and Directory.Exists methods?
             * When those methods return TRUE, we can safely say that file (or directory) really exists.
             * Besides, those methods are very fast. Hence, we can stop the method if one of those methods return TRUE.
             */

            try
            {
                var windowsConnectionProvider = new StraightNetworkConnectionProvider();
                var adminShareFilePath        = GetAdministrativeSharePathFromLocalFilepath(TargetInfo.GetAddress(), localFilepath);
                try
                {
                    // To use Administrative Share resource, we need open a straight connection to remote machine.
                    windowsConnectionProvider.Connect(TargetInfo);
                    try
                    {
                        // If one of these methods return TRUE, we can return this result.
                        if (System.IO.File.Exists(adminShareFilePath) || System.IO.Directory.Exists(adminShareFilePath))
                        {
                            return(true);
                        }

                        // If both methods above return FALSE, we CAN NOT rely on in this.
                        try
                        {
                            // So, we will try to open the file...
                            System.IO.File.Open(adminShareFilePath, FileMode.Open);
                            // If we could open it, the file exists.
                            return(true);
                        }
                        catch (FileNotFoundException)
                        {
                            // obviously we can return FALSE if File.Open thrown FileNotFoundException.
                            return(false);
                        }
                    }
                    catch (Exception)
                    {
                        try
                        {
                            // If any else Exception was thrown, maybe the passed path is a directory...
                            // So, we will try to open it.
                            System.IO.Directory.EnumerateFiles(adminShareFilePath, "*");
                            return(true);
                        }
                        catch (FileNotFoundException)
                        {
                            return(false);
                        }
                    }
                }
                finally
                {
                    windowsConnectionProvider.Disconnect();
                }
            }
            catch (Exception)
            {
                // At last, if it was not possible to check file (or directory) existence due to any error,
                // we will try to find this information out through WMI.
                var wmiParametersForFileSearching = this.CreateWmiParameters(localFilepath);
                var wqlForFileSearching           = new WQLBuilder().WithWmiClass("CIM_LogicalFile").AddParameters(wmiParametersForFileSearching).Build();
                var wmiQueryResult = this.WmiDataProvider.ExecuteWQL(wqlForFileSearching);

                return((wmiQueryResult != null) && (wmiQueryResult.Count() > 0));
            }
        }