Example #1
0
 public ExternalEthernetPort(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
 public BcdObject(ManagementPath path, ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
        /// <summary>
        /// Remove an object given either path,class name or pipeline input.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (this.AsJob)
            {
                RunAsJob("Remove-WMIObject");
                return;
            }
            if (_inputObject != null)
            {
                try
                {
                    if (!ShouldProcess(_inputObject["__PATH"].ToString()))
                    {
                        return;
                    }
                    _inputObject.Delete();
                }
                catch (ManagementException e)
                {
                    ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null);
                    WriteError(errorRecord);
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null);
                    WriteError(errorRecord);
                }
                return;
            }
            else
            {
                ConnectionOptions options = GetConnectionOption();
                ManagementPath    mPath   = null;
                ManagementObject  mObject = null;
                if (_path != null)
                {
                    mPath = new ManagementPath(_path);
                    if (String.IsNullOrEmpty(mPath.NamespacePath))
                    {
                        mPath.NamespacePath = this.Namespace;
                    }
                    else if (namespaceSpecified)
                    {
                        //ThrowTerminatingError
                        ThrowTerminatingError(new ErrorRecord(
                                                  new InvalidOperationException(),
                                                  "NamespaceSpecifiedWithPath",
                                                  ErrorCategory.InvalidOperation,
                                                  this.Namespace));
                    }

                    if (mPath.Server != "." && serverNameSpecified)
                    {
                        //ThrowTerminatingError
                        ThrowTerminatingError(new ErrorRecord(
                                                  new InvalidOperationException(),
                                                  "ComputerNameSpecifiedWithPath",
                                                  ErrorCategory.InvalidOperation,
                                                  this.ComputerName));
                    }
                    if (!(mPath.Server == "." && serverNameSpecified))
                    {
                        string[] serverName = new string[] { mPath.Server };
                        ComputerName = serverName;
                    }
                }
                foreach (string name in ComputerName)
                {
                    try
                    {
                        if (_path != null)
                        {
                            mPath.Server = name;
                            if (mPath.IsClass)
                            {
                                ManagementClass mClass = new ManagementClass(mPath);
                                mObject = mClass;
                            }
                            else
                            {
                                ManagementObject mInstance = new ManagementObject(mPath);
                                mObject = mInstance;
                            }
                            ManagementScope mScope = new ManagementScope(mPath, options);
                            mObject.Scope = mScope;
                        }
                        else
                        {
                            ManagementScope scope  = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options);
                            ManagementClass mClass = new ManagementClass(_className);
                            mObject       = mClass;
                            mObject.Scope = scope;
                        }
                        if (!ShouldProcess(mObject["__PATH"].ToString()))
                        {
                            continue;
                        }
                        mObject.Delete();
                    }
                    catch (ManagementException e)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null);
                        WriteError(errorRecord);
                    }
                    catch (System.Runtime.InteropServices.COMException e)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null);
                        WriteError(errorRecord);
                    }
                }
            }
        }
Example #4
0
 public ExternalEthernetPort(ManagementScope mgmtScope, ManagementPath path) : base(mgmtScope, path, ClassName)
 {
 }
Example #5
0
 public InstanceCreationEvent(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
 public StorageExtendedStatus(ManagementPath path) : base(path, ClassName)
 {
 }
Example #7
0
 public MsftBase(ManagementScope mgmtScope, ManagementPath path, string ClassName)
 {
     CreatedClassName = ClassName;
     InitializeObject(mgmtScope, path, null);
 }
	public ManagementObject(ManagementPath path) {}
Example #9
0
 public HostInstance(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions)
 {
     InitializeObject(mgmtScope, path, getOptions);
 }
Example #10
0
 public MsftBase(ManagementPath path, ObjectGetOptions getOptions, string ClassName)
 {
     CreatedClassName = ClassName;
     InitializeObject(null, path, getOptions);
 }
Example #11
0
 public HostInstance(ManagementPath path)
 {
     InitializeObject(null, path, null);
 }
Example #12
0
 public HostInstance(ManagementScope mgmtScope, ManagementPath path)
 {
     InitializeObject(mgmtScope, path, null);
 }
Example #13
0
 public HostInstance(ManagementPath path, ObjectGetOptions getOptions)
 {
     InitializeObject(null, path, getOptions);
 }
	public ManagementClass(ManagementPath path, ObjectGetOptions options) {}
Example #15
0
 public MsvmBase(ManagementPath path, string ClassName)
 {
     CreatedClassName = ClassName;
     InitializeObject(null, path, null);
 }
	public ManagementPath CopyTo(ManagementPath path, PutOptions options) {}
Example #17
0
 public MsvmBase(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions, string ClassName)
 {
     CreatedClassName = ClassName;
     InitializeObject(mgmtScope, path, getOptions);
 }
	public ManagementScope(ManagementPath path) {}
Example #19
0
    public static int Main(string[] args)
    {
        string[] DRIVE_TYPES = { "Unknown", "No Root Directory", "Removable Disk", "Local Disk", "Network Drive", "Compact Disc", "RAM Disk" };

        string system = ".";

        foreach (string arg in args)
        {
            switch (arg.ToUpper())
            {
            case "/?":
                return(PrintUsage());

            default:
                system = args[0].Trim(new Char[] { '\\', ' ' });
                break;
            }
        }

        ManagementPath path = new ManagementPath()
        {
            NamespacePath = @"root\cimv2",
            Server        = system
        };
        ManagementScope scope = new ManagementScope(path);

        string[]    selectedProperties = new string[] { "DeviceID", "DriveType", "ProviderName", "FreeSpace", "Size", "VolumeName" };
        SelectQuery query = new SelectQuery("Win32_LogicalDisk", "", selectedProperties);

        try {
            // Execute query within scope and iterate through results
            using (var searcher = new ManagementObjectSearcher(scope, query)) {
                foreach (ManagementObject volume in searcher.Get())
                {
                    Console.WriteLine("\nDrive " + volume.GetPropertyValue("DeviceID") + "\\");

                    if (String.Format("{0}", volume.GetPropertyValue("VolumeName")) != "")
                    {
                        Console.WriteLine("  Name:       {0}", volume.GetPropertyValue("VolumeName"));
                    }

                    Console.WriteLine("  Type:       {0}", DRIVE_TYPES[Convert.ToInt32(volume.GetPropertyValue("DriveType"))]);

                    if (Convert.ToInt32(volume.GetPropertyValue("DriveType")) == 4)
                    {
                        Console.WriteLine("  Provider:   {0}", volume.GetPropertyValue("ProviderName"));
                    }

                    if (Convert.ToInt64(volume.GetPropertyValue("Size")) > 0)
                    {
                        Console.WriteLine("  Free Space: {0}", String.Format("{0:n0}", Convert.ToInt64(volume.GetPropertyValue("FreeSpace"))) + " bytes");
                        Console.WriteLine("  Size:       {0}", String.Format("{0:n0}", Convert.ToInt64(volume.GetPropertyValue("Size"))) + " bytes");
                    }
                }
            }

            Console.WriteLine("\nDONE");
            return(0);
        } catch (Exception e) {
            Console.WriteLine("ERROR: " + e.Message);
            Console.WriteLine("\nDONE");
            return(1);
        }
    }
 public StorageExtendedStatus(ManagementScope mgmtScope, ManagementPath path) : base(mgmtScope, path, ClassName)
 {
 }
Example #21
0
        private void Create()
        {
            this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Creating share: {0} on: {1}", this.ShareName, this.MachineName));
            this.GetManagementScope(@"\root\cimv2");
            ManagementPath path = new ManagementPath("Win32_Share");

            if (!this.TargetingLocalMachine(true))
            {
                // we need to operate remotely
                string      fullQuery = @"Select * From Win32_Directory Where Name = '" + this.SharePath.Replace("\\", "\\\\") + "'";
                ObjectQuery query1    = new ObjectQuery(fullQuery);
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query1))
                {
                    ManagementObjectCollection queryCollection = searcher.Get();
                    if (queryCollection.Count == 0)
                    {
                        if (this.CreateSharePath)
                        {
                            this.LogTaskMessage(MessageImportance.Low, "Attempting to create remote folder for share");
                            ManagementPath  path2            = new ManagementPath("Win32_Process");
                            ManagementClass managementClass2 = new ManagementClass(this.Scope, path2, null);

                            ManagementBaseObject inParams1 = managementClass2.GetMethodParameters("Create");
                            string tex = "cmd.exe /c md \"" + this.SharePath + "\"";
                            inParams1["CommandLine"] = tex;

                            ManagementBaseObject outParams1 = managementClass2.InvokeMethod("Create", inParams1, null);
                            uint rc = Convert.ToUInt32(outParams1.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture);
                            if (rc != 0)
                            {
                                this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Non-zero return code attempting to create remote share location: {0}", rc));
                                return;
                            }

                            // adding a sleep as it may take a while to register.
                            System.Threading.Thread.Sleep(1000);
                        }
                        else
                        {
                            this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "SharePath not found: {0}. Set CreateSharePath to true to create a SharePath that does not exist.", this.SharePath));
                            return;
                        }
                    }
                }
            }
            else
            {
                if (!Directory.Exists(this.SharePath))
                {
                    if (this.CreateSharePath)
                    {
                        Directory.CreateDirectory(this.SharePath);

                        // adding a sleep as it may take a while to register.
                        System.Threading.Thread.Sleep(1000);
                    }
                    else
                    {
                        this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "SharePath not found: {0}. Set CreateSharePath to true to create a SharePath that does not exist.", this.SharePath));
                        return;
                    }
                }
            }

            using (ManagementClass managementClass = new ManagementClass(this.Scope, path, null))
            {
                // Set the input parameters
                ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
                inParams["Description"] = this.Description;
                inParams["Name"]        = this.ShareName;
                inParams["Path"]        = this.SharePath;

                // build the access permissions
                if (this.AllowUsers != null | this.DenyUsers != null)
                {
                    inParams["Access"] = this.SetAccessPermissions();
                }

                // Disk Drive
                inParams["Type"] = 0x0;

                if (this.MaximumAllowed > 0)
                {
                    inParams["MaximumAllowed"] = this.MaximumAllowed;
                }

                ManagementBaseObject outParams  = managementClass.InvokeMethod("Create", inParams, null);
                ReturnCode           returnCode = (ReturnCode)Convert.ToUInt32(outParams.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture);
                switch (returnCode)
                {
                case ReturnCode.Success:
                    break;

                case ReturnCode.AccessDenied:
                    this.Log.LogError("Access Denied");
                    break;

                case ReturnCode.UnknownFailure:
                    this.Log.LogError("Unknown Failure");
                    break;

                case ReturnCode.InvalidName:
                    this.Log.LogError("Invalid Name");
                    break;

                case ReturnCode.InvalidLevel:
                    this.Log.LogError("Invalid Level");
                    break;

                case ReturnCode.InvalidParameter:
                    this.Log.LogError("Invalid Parameter");
                    break;

                case ReturnCode.RedirectedPath:
                    this.Log.LogError("Redirected Path");
                    break;

                case ReturnCode.UnknownDeviceOrDirectory:
                    this.Log.LogError("Unknown Device or Directory");
                    break;

                case ReturnCode.NetNameNotFound:
                    this.Log.LogError("Net name not found");
                    break;

                case ReturnCode.ShareAlreadyExists:
                    this.LogTaskWarning(string.Format(CultureInfo.CurrentCulture, "The share already exists: {0}", this.ShareName));
                    break;
                }
            }
        }
 public StorageExtendedStatus(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
Example #23
0
        public static void ActionComputers()
        {
            ManagementObjectCollection instances;
            List <string> ComputerNames = GetComputers();
            var           response      = GetJsonData();

            //Create log file
            using (StreamWriter log = new StreamWriter(fileName))
            {
                log.WriteLine("TIMESTAMP :" + DateTime.Now);
                log.WriteLine("ACTION TAKEN :" + response.Action.action);

                foreach (var i in ComputerNames)
                {
                    try
                    {
                        //Connecting to individual machines with config credentials
                        ConnectionOptions options = new ConnectionOptions();
                        options.Authority        = "ntlmdomain:" + response.ServerConfiguration.domain;
                        options.Username         = response.ServerConfiguration.domainAdminUserName;
                        options.Password         = response.ServerConfiguration.domainAdminPassword;
                        options.EnablePrivileges = true;

                        ManagementScope scope = new ManagementScope("\\\\" + i + "\\root\\CIMV2", options);
                        scope.Connect();

                        ManagementPath  osPath = new ManagementPath("Win32_OperatingSystem");
                        ManagementClass os     = new ManagementClass(scope, osPath, null);
                        instances = os.GetInstances();
                    }

                    catch (Exception e)
                    {
                        hasError = true;
                        Console.WriteLine(i + e);
                        log.WriteLine(i + e);
                        continue;
                    }


                    foreach (ManagementObject instance in instances)
                    {
                        ManagementBaseObject inParams = instance.GetMethodParameters("Win32Shutdown");
                        inParams["Flags"] = 0;
                        if (response.Action.action.ToLower() == "logoff")
                        {
                            try
                            {
                                //logoff action using WMI
                                object result = instance.InvokeMethod("Win32Shutdown", inParams, null);
                                Console.WriteLine("Successful logoff attempt on " + i);
                                log.WriteLine("Successful logoff attempt on " + i);
                            }
                            catch (Exception)
                            {
                                Console.WriteLine("Unsuccessful logoff attempt on " + i);
                                log.WriteLine("Unsuccessful logoff attempt on " + i);
                                continue;
                            }
                        }
                        else
                        {
                            //Every other action using WMI
                            object result = instance.InvokeMethod(response.Action.action, new object[] { });

                            uint returnValue = (uint)result;

                            if (returnValue != 0)
                            {
                                hasError = true;
                                Console.WriteLine("Action NOT taken on " + i);
                                log.WriteLine("Action NOT taken on " + i);
                            }
                            else
                            {
                                Console.WriteLine("Action taken on " + i);
                                log.WriteLine("Action taken on " + i);
                            }
                        }
                    }
                }
            }
            if (hasError == true)
            {
                try
                {
                    //Send email if errors were found
                    MailMessage mail       = new MailMessage();
                    SmtpClient  SmtpServer = new SmtpClient(response.EmailConfiguration.Server);
                    SmtpServer.UseDefaultCredentials = true;
                    string str = string.Empty;
                    foreach (var item in response.EmailConfiguration.toAddresses)
                    {
                        mail.To.Add(item);
                    }

                    mail.From    = new MailAddress(response.EmailConfiguration.fromAddress);
                    mail.Subject = "LogFile" + DateTime.Now;
                    mail.Body    = "attached log file";

                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment(fileName);
                    mail.Attachments.Add(attachment);

                    SmtpServer.Port        = response.EmailConfiguration.Port;
                    SmtpServer.Credentials = new System.Net.NetworkCredential(response.EmailConfiguration.userName, response.EmailConfiguration.password);
                    SmtpServer.EnableSsl   = true;

                    SmtpServer.Send(mail);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
Example #24
0
        /// <summary>
        /// based on the task, either starts/stops/restarts the services @hostname
        /// </summary>
        /// <param name="hostname"></param>
        /// <param name="task"></param>
        /// <param name="services"></param>

        private PluginExecutionResult ServiceActionPerform(string hostAddress, int task, List <string> services, PluginEnvironment environment)
        {
            //Using Managemnent Scope. Instantiate the Win32_Service application and sned the appropriate command to the service.
            try
            {
                ConnectionOptions options = new ConnectionOptions();
                //GlobalSettings.Items.DomainAdminCredential.UserName
                options.Username = environment.UserDomain + @"\" + environment.PluginSettings["DomainAdminUserName"];
                options.Password = environment.PluginSettings["DomainAdminPassword"];

                ManagementScope scope = new ManagementScope(@"\\" + hostAddress + @"\root\cimv2");
                scope.Options = options;
                scope.Connect();


                foreach (string service in services)
                {
                    ManagementPath       path = new ManagementPath(string.Format("Win32_Service.Name='{0}'", service));
                    ManagementObject     obj  = new ManagementObject(scope, path, new ObjectGetOptions());
                    ManagementBaseObject outParams;


                    switch (task)
                    {
                    case 0:
                        outParams = obj.InvokeMethod("StopService", null, null);
                        break;

                    case 1:
                        outParams = obj.InvokeMethod("StartService", null, null);
                        break;

                    case 2:
                        outParams = obj.InvokeMethod("StopService", null, null);
                        System.Threading.Thread.Sleep(1000);
                        outParams = obj.InvokeMethod("StartService", null, null);

                        break;

                    default:
                        throw new IndexOutOfRangeException();
                    }
                    uint returnCode = System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);

                    Logger.LogDebug($"Code Value; {returnCode}");
                    //If 0, success, if not, failed.
                    if (returnCode != 0)
                    {
                        throw new DeviceWorkflowException("Failed to successfuly modify service.");
                    }
                }
                return(new PluginExecutionResult(PluginResult.Passed));
            }
            catch (Exception e)
            {
                if (e.Message == "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)")
                {
                    return(new PluginExecutionResult(PluginResult.Failed, "Could Not Connect to Server"));
                }
                else
                {
                    return(new PluginExecutionResult(PluginResult.Failed, e));
                }
            }
        }
Example #25
0
        private bool CheckService(string servicename)
        {
            ServiceController sc = new ServiceController(servicename);

            try
            {
                AddTextString("Service '" + sc.ServiceName + @"' found!");
            }
            catch
            {
                AddTextString("Cannot find the service '" + servicename + "'.");
                return(false);
            }

            try
            {
                // Check the service startup type
                string           path          = "Win32_Service.Name='" + servicename + "'";
                ManagementPath   p             = new ManagementPath(path);
                ManagementObject ManagementObj = new ManagementObject(p);
                AddTextString("Statup type " + ManagementObj["StartMode"].ToString());

                if ((ManagementObj["StartMode"].ToString() == "Disabled") ||
                    (ManagementObj["StartMode"].ToString() == "Manual"))
                {
                    object[] parameters = new object[1];
                    parameters[0] = "Automatic";
                    AddTextString("Setting statup type to Automatic.");
                    ManagementObj.InvokeMethod("ChangeStartMode", parameters);
                }

                // Check is the service is running and start if required.
                AddTextString("The service is currently " + sc.Status.ToString().ToLower() + ".");
                if (sc.Status == ServiceControllerStatus.Stopped)
                {
                    AddTextString("");
                    AddTextString("Starting service.");
                    sc.Start();

                    for (int i = 0; i < 10; i++)
                    {
                        Thread.Sleep(1000);
                        sc.Refresh();
                        AddTextString("The service is currently " + sc.Status.ToString().ToLower() + ".");
                        if (sc.Status == ServiceControllerStatus.Running)
                        {
                            break;
                        }
                        if (sc.Status == ServiceControllerStatus.Stopped)
                        {
                            break;
                        }
                    }


                    if (sc.Status == ServiceControllerStatus.Running)
                    {
                        AddTextString("Service started.");
                        return(true);
                    }
                    else
                    {
                        AddTextString("Service failed to start.");
                        return(false);
                    }
                }
            }
            catch
            {
                AddTextString("A problem has occured when trying to check the service. Vista UAC can cause this!");
            }
            AddTextString("");
            return(true);
        }
Example #26
0
 public ExternalEthernetPort(ManagementPath path) : base(path, ClassName)
 {
 }
        public ICustomActivityResult Execute()

        {
            StringWriter sw = new StringWriter();
            DataTable    dt = new DataTable("resultSet");

            dt.Columns.Add("Result", typeof(string));

            if (string.IsNullOrEmpty(Path))
            {
                throw new Exception("Folder not found");
            }
            if (string.IsNullOrEmpty(PermissionsData))
            {
                throw new Exception("Permissions data is empty.");
            }

            ConnectionOptions connectionOptions = new ConnectionOptions();

            connectionOptions.Username         = UserName;
            connectionOptions.Password         = Password;
            connectionOptions.Authentication   = AuthenticationLevel.PacketPrivacy;
            connectionOptions.Impersonation    = ImpersonationLevel.Impersonate;
            connectionOptions.EnablePrivileges = true;
            ManagementScope oms;

            if (HostName.ToLower() == "localhost" || HostName.ToLower() == "127.0.0.1")
            {
                oms = new ManagementScope(@"\\.\root\cimv2");
            }
            else
            {
                oms = new ManagementScope(string.Format(@"\\{0}\root\cimv2", HostName), connectionOptions);
            }

            Path = Path.Trim();
            string dirName = System.IO.Path.GetDirectoryName(Path);

            if (Path.EndsWith(@"\") && !string.IsNullOrEmpty(dirName))
            {
                Path = Path.Substring(0, Path.LastIndexOf(@"\"));
            }

            string[] singleUserData = PermissionsData.Split(new String[] { "<value>" }, StringSplitOptions.None);
            string   fullUserName   = GetUserName(HostName, singleUserData[0], Path);

            if (Path.StartsWith(@"\\")) // || HostName.ToLower() == "localhost" || HostName.ToLower() == "127.0.0.1")
            {
                // SET PERMISSIONS LOCAL ------------------


                if (!Directory.Exists(Path))
                {
                    throw new Exception("Folder not found");
                }

                //get file info
                DirectoryInfo fi = new DirectoryInfo(Path);

                //get security access
                DirectorySecurity fs = fi.GetAccessControl();


                // *** Always allow objects to inherit on a directory
                InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

                FileSystemRights Rights = (FileSystemRights)0;

                SecurityIdentifier si = null;
                // Check is User/Group exist
                try
                {
                    si = GetSecurityIdentifier(HostName, fullUserName, Path);
                    AddAccessRule(fs, si, singleUserData, Rights, iFlags);
                }
                catch
                {
                    throw new Exception(@"User / Group does not exist or you are not authorized to change the security settings.");
                }


                if (bool.Parse(InheritablePermissions))
                {
                    //remove any inherited access
                    fs.SetAccessRuleProtection(true, false);
                }

                //get any special user access
                AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

                //remove any special access
                foreach (FileSystemAccessRule rule in rules)
                {
                    if (bool.Parse(InheritablePermissions))
                    {
                        fs.RemoveAccessRule(rule);
                    }
                    else
                    {
                        if (string.Equals(fullUserName, rule.IdentityReference.Value.ToLower()))
                        {
                            fs.RemoveAccessRule(rule);
                        }
                    }
                }


                AddAccessRule(fs, si, singleUserData, Rights, iFlags);


                //if (bool.Parse(singleUserData[1]))
                //{
                //    // FullControl
                //    //add current user with full control.
                //    Rights = FileSystemRights.FullControl;
                //    fs.AddAccessRule(new FileSystemAccessRule(fullUserName, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow));
                //    //fs.AddAccessRule(new FileSystemAccessRule(UsrName, FileSystemRights.FullControl, AccessControlType.Allow));
                //}
                //else
                //{
                //    if (bool.Parse(singleUserData[2]))
                //    {
                //        // Modify
                //        //add current user with Modify.
                //        Rights = FileSystemRights.Modify;
                //        fs.AddAccessRule(new FileSystemAccessRule(fullUserName, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow));
                //        //fs.AddAccessRule(new FileSystemAccessRule(UsrName, FileSystemRights.Modify, AccessControlType.Allow));
                //    }
                //    else
                //    {
                //        if (bool.Parse(singleUserData[3]))
                //        {
                //            // Read & Execute
                //            //add current user with Read.
                //            Rights = FileSystemRights.ReadAndExecute;
                //            fs.AddAccessRule(new FileSystemAccessRule(fullUserName, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow));
                //            //fs.AddAccessRule(new FileSystemAccessRule(UsrName, FileSystemRights.ReadAndExecute, AccessControlType.Allow));
                //        }
                //        else
                //        {
                //            if (bool.Parse(singleUserData[4]))
                //            {
                //                // Read
                //                //add current user with Read.
                //                Rights = FileSystemRights.Read;
                //                fs.AddAccessRule(new FileSystemAccessRule(fullUserName, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow));
                //                //fs.AddAccessRule(new FileSystemAccessRule(UsrName, FileSystemRights.Read, AccessControlType.Allow));
                //            }
                //        }
                //        if (bool.Parse(singleUserData[5]))
                //        {
                //            // Write
                //            //add current user with Write.
                //            Rights = FileSystemRights.Write;
                //            fs.AddAccessRule(new FileSystemAccessRule(fullUserName, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow));
                //            //fs.AddAccessRule(new FileSystemAccessRule(UsrName, FileSystemRights.Write, AccessControlType.Allow));
                //        }
                //        if (bool.Parse(singleUserData[6]))
                //        {
                //            // Delete
                //            //add current user with Write.
                //            Rights = FileSystemRights.Delete;
                //            fs.AddAccessRule(new FileSystemAccessRule(fullUserName, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow));
                //            //fs.AddAccessRule(new FileSystemAccessRule(UsrName, FileSystemRights.Delete, AccessControlType.Allow));
                //        }
                //    }


                //}


                //fs.AddAccessRule(new FileSystemAccessRule(UsrName, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow));


                // Without inheritance
                //fs.AddAccessRule(new FileSystemAccessRule(UsrName, Rights, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));



                //add all other users delete only permissions.
                //fs.AddAccessRule(new FileSystemAccessRule("Authenticated Users", FileSystemRights.Delete, AccessControlType.Allow));

                //flush security access.
                fi.SetAccessControl(fs);

                dt.Rows.Add("Success");
            }
            else
            {
                //int lastInd = Path.LastIndexOf(@"\");
                ////string folderPath = Path.Substring(0, Path.Length - lastInd);
                //string folderPath = Path; //Path.Substring(0, lastInd);

                //string Volume = System.IO.Path.GetPathRoot(folderPath);
                //string PathOnlyNoVolume = string.Empty;
                //if (!string.IsNullOrEmpty(Volume))
                //{
                //    PathOnlyNoVolume = folderPath.Replace(Volume, "");
                //}
                //PathOnlyNoVolume = PathOnlyNoVolume.Replace(@"\", @"\\");

                // ----------------- Check File existance -----------------------------------
                //ObjectQuery oQuery = null;
                //if (string.IsNullOrEmpty(PathOnlyNoVolume))
                //{
                //    oQuery = new System.Management.ObjectQuery("SELECT Name FROM CIM_DataFile WHERE Drive = '" + Volume.Replace(@"\", "") + @"' and path = '\\'");
                //}
                //else
                //{
                //    oQuery = new System.Management.ObjectQuery("SELECT Name FROM CIM_DataFile WHERE Drive = '" + Volume.Replace(@"\", "") + @"' and path = '\\" + PathOnlyNoVolume + @"\\'");
                //}

                ObjectQuery oQuery = new System.Management.ObjectQuery("SELECT Name FROM Win32_Directory WHERE Name = '" + Path.Replace(@"\", @"\\") + "'");

                ManagementObjectSearcher oSearcher1 = new ManagementObjectSearcher(oms, oQuery);
                var allOb1 = oSearcher1.Get();


                bool isFound = false;
                foreach (ManagementObject fobject in allOb1)
                {
                    isFound = true;
                }
                if (!isFound)
                {
                    throw new Exception("Folder not found.");
                }
                // --------------------- End Check File Existance ------------------------------------------------------------


                // Works when fileName is local directory, but not UNC path.
                ManagementPath mngPath = new ManagementPath();
                mngPath.RelativePath = @"Win32_LogicalFileSecuritySetting.Path=" + "'" + Path + "'";
                //+ "'" + @"C:\Test1\tf1.txt" + "'";

                ManagementObject fileSecurity = new ManagementObject(
                    oms, mngPath, null);

                // When used with UNC path, exception with "Not Found" is thrown.
                ManagementBaseObject outParams = null;
                try
                {
                    outParams = (ManagementBaseObject)fileSecurity.InvokeMethod(
                        "GetSecurityDescriptor", null, null);
                }
                catch
                {
                    throw new Exception("Failed to get Security Descriptor.");
                }

                // Get security descriptor and DACL for specified file.
                ManagementBaseObject   descriptor = (ManagementBaseObject)outParams.Properties["Descriptor"].Value;
                ManagementBaseObject[] dacl       = (ManagementBaseObject[])descriptor.Properties["Dacl"].Value;

                //string ppp = fileSecurity.Properties["ControlFlags"].Value.ToString();
                //fileSecurity.Properties["ControlFlags"].Value = 4 | 4096 | 8192;//ControlFlags.DiscretionaryAclProtected;

                //string propName = string.Empty;
                //foreach (var prop in fileSecurity.Properties)
                //{
                //    propName += prop.Name + ";";
                //}

                //ControlFlags.SystemAclProtected property
                //string name = string.Empty;

                //string[] singleUserData = PermissionsData.Split(new String[] { "<value>" }, StringSplitOptions.None);


                //string fullUserName = GetUserName(singleUserData[0]);
                string   machineName     = GetMachineName(HostName);
                string[] dividedUserName = fullUserName.Split(new string[] { @"\" }, StringSplitOptions.None);
                string   UserDomain      = string.Empty;
                string   UsrName         = string.Empty;
                if (dividedUserName.Length < 2)
                {
                    UsrName = dividedUserName[0].ToLower();
                }
                else
                {
                    UserDomain = dividedUserName[0].ToLower();
                    UsrName    = dividedUserName[1].ToLower();
                }

                // Get the user account to be trustee.
                ManagementObject userAccount = new ManagementClass(oms,
                                                                   new ManagementPath("Win32_Trustee"), null);
                userAccount.Properties["Name"].Value   = UsrName;
                userAccount.Properties["Domain"].Value = UserDomain;

                // Create a new ACE for the descriptor.

                ManagementObject newAce = CreateNewACE(oms, userAccount, singleUserData);


                // Check is User/Group exist.
                try
                {
                    // Add ACE to DACL and set to descriptor.
                    ArrayList daclArray = new ArrayList(dacl);
                    daclArray.Add(newAce);

                    descriptor.Properties["Dacl"].Value = daclArray.ToArray();

                    // User SetSecurityDescriptor to apply the descriptor.
                    ManagementBaseObject inParamsCheck = fileSecurity.GetMethodParameters("SetSecurityDescriptor");
                    inParamsCheck["Descriptor"] = descriptor;
                    outParams = fileSecurity.InvokeMethod("SetSecurityDescriptor", inParamsCheck, null);

                    uint errorcodeCheck = (uint)outParams["returnValue"];

                    ErrorCheck(errorcodeCheck);
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("Invalid parameter"))
                    {
                        throw new Exception(@"User / Group does not exist or you are not authorized to change the security settings.");
                    }
                    else
                    {
                        throw new Exception(ex.Message);
                    }
                }

                ArrayList NewdaclArray = new ArrayList();

                if (bool.Parse(InheritablePermissions))
                {
                    // Remove inheritable permissions.
                    int descriptorMask = 0x0004 | 0x1000;
                    descriptor.Properties["ControlFlags"].Value = descriptorMask;
                }
                else
                {
                    // leave all inheritable permissions
                    foreach (var ace in dacl)
                    {
                        if (ace.Properties["AccessMask"] != null)
                        {
                            // ACE children inheritance
                            //ace.Properties["AceFlags"].Value = 16 | 1;

                            ManagementBaseObject mob = (ManagementBaseObject)ace.Properties["Trustee"].Value;

                            string TrusteeName   = string.Empty;
                            string TrusteeDomain = string.Empty;

                            if (mob.Properties["Domain"] != null)
                            {
                                if (mob.Properties["Domain"].Value != null)
                                {
                                    TrusteeDomain = mob.Properties["Domain"].Value.ToString().ToLower();
                                }
                            }

                            if (mob.Properties["Name"] != null)
                            {
                                if (mob.Properties["Name"].Value != null)
                                {
                                    TrusteeName = mob.Properties["Name"].Value.ToString().ToLower();
                                }
                            }


                            if (!string.Equals(UsrName, TrusteeName))
                            {
                                NewdaclArray.Add(ace);
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(UserDomain))
                                {
                                    if (!string.Equals(machineName, TrusteeDomain))
                                    {
                                        NewdaclArray.Add(ace);
                                    }
                                }
                                else
                                {
                                    if (!string.Equals(UserDomain, TrusteeDomain))
                                    {
                                        NewdaclArray.Add(ace);
                                    }
                                }
                            }
                        }
                    }
                }

                // Add ACE to DACL and set to descriptor.
                NewdaclArray.Add(newAce);
                descriptor.Properties["Dacl"].Value = NewdaclArray.ToArray();

                // User SetSecurityDescriptor to apply the descriptor.
                ManagementBaseObject inParams = fileSecurity.GetMethodParameters("SetSecurityDescriptor");
                inParams["Descriptor"] = descriptor;
                outParams = fileSecurity.InvokeMethod("SetSecurityDescriptor", inParams, null);

                uint errorcode = (uint)outParams["returnValue"];

                ErrorCheck(errorcode);

                dt.Rows.Add("Success");
            }
            return(this.GenerateActivityResult(dt));
        }
Example #28
0
 public uint RequestStateChange(ushort RequestedState, DateTime TimeoutPeriod, out ManagementPath Job)
 {
     if (IsEmbedded == false)
     {
         ManagementBaseObject inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange");
         inParams[nameof(RequestedState)] = RequestedState;
         inParams["TimeoutPeriod"]        = ToDmtfDateTime(TimeoutPeriod);
         ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null);
         Job = null;
         if (outParams.Properties["Job"] != null)
         {
             Job = new ManagementPath(outParams["Job"] as string);
         }
         return(Convert.ToUInt32(outParams.Properties["ReturnValue"].Value));
     }
     else
     {
         Job = null;
         return(Convert.ToUInt32(0));
     }
 }
Example #29
0
 public DataConduITMgr()
 {
     /*PATH PARA CONECTAR A DATACONDUIT */
     path = new ManagementPath("\\\\10.11.34.96\\root\\OnGuard");
     //VERIFICAR SI ESTO SERA UN PARAMETRO O SE FIJARA EN UN ARCHIVO DE CONFIGURACION EN CADA LUGAR DONDE SE EJECUTE
 }
	public ManagementClass(ManagementPath path) {}
Example #31
0
 public Memory(ManagementPath path, ObjectGetOptions getOptions) : base(path, getOptions, ClassName)
 {
 }
	public ManagementPath CopyTo(ManagementPath path) {}
Example #33
0
 public Memory(ManagementScope mgmtScope, ManagementPath path) : base(mgmtScope, path, ClassName)
 {
 }
	public void CopyTo(ManagementOperationObserver watcher, ManagementPath path, PutOptions options) {}
Example #35
0
 public Memory(ManagementPath path) : base(path, ClassName)
 {
 }
	public ManagementObject(ManagementScope scope, ManagementPath path, ObjectGetOptions options) {}
Example #37
0
 public Memory(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
	public ManagementScope(ManagementPath path, ConnectionOptions options) {}
Example #39
0
 public InstanceCreationEvent(ManagementPath path) : base(path, ClassName)
 {
 }