public static string InstallHosts(string ServerName, string HostName, string UserName, string Password, bool StartHost)
        {
            PutOptions options = new PutOptions();
            options.Type = PutType.CreateOnly;
            ObjectGetOptions bts_objOptions = new ObjectGetOptions();

            // Creating instance of BizTalk Host.
            ManagementClass bts_AdminObjClassServerHost = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_ServerHost", bts_objOptions);
            ManagementObject bts_AdminObjectServerHost = bts_AdminObjClassServerHost.CreateInstance();

            // Make sure to put correct Server Name,username and // password
            bts_AdminObjectServerHost["ServerName"] = ServerName;
            bts_AdminObjectServerHost["HostName"] = HostName;
            bts_AdminObjectServerHost.InvokeMethod("Map", null);

            ManagementClass bts_AdminObjClassHostInstance = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_HostInstance", bts_objOptions);
            ManagementObject bts_AdminObjectHostInstance = bts_AdminObjClassHostInstance.CreateInstance();

            bts_AdminObjectHostInstance["Name"] = "Microsoft BizTalk Server " + HostName + " " + ServerName;

            //Also provide correct user name and password.
            ManagementBaseObject inParams = bts_AdminObjectHostInstance.GetMethodParameters("Install");
            inParams["GrantLogOnAsService"] = false;
            inParams["Logon"] = UserName;
            inParams["Password"] = Password;

            bts_AdminObjectHostInstance.InvokeMethod("Install", inParams, null);
            
            if(StartHost)
                bts_AdminObjectHostInstance.InvokeMethod("Start", null);

            return "  Host - " + HostName + " - has been installed. \r\n";
        }
        /// <summary>
        /// Create a Receive Handler.
        /// </summary>
        /// <param name="adapterName">The Adapter name.</param>
        /// <param name="hostName">The Host name.</param>
        public static void Create(string adapterName, string hostName)
        {
            PutOptions options = new PutOptions();
            options.Type = PutType.CreateOnly;
            using (ManagementClass handlerManagementClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_ReceiveHandler", null))
            {
                foreach (ManagementObject handler in handlerManagementClass.GetInstances())
                {
                    if ((string)handler["AdapterName"] == adapterName && (string)handler["HostName"] == hostName)
                    {
                        handler.Delete();
                    }
                }

                ManagementObject recieveHandlerManager = handlerManagementClass.CreateInstance();
                if (recieveHandlerManager == null)
                {
                    throw new BizTalkExtensionsException("Could not create Management Object.");
                }

                recieveHandlerManager["AdapterName"] = adapterName;
                recieveHandlerManager["HostName"] = hostName;
                recieveHandlerManager.Put(options);
            }
        }
Beispiel #3
0
 public void CommitObject(System.Management.PutOptions putOptions)
 {
     if ((isEmbedded == false))
     {
         PrivateLateBoundObject.Put(putOptions);
     }
 }
Beispiel #4
0
        /// <summary>
        /// Create a Send Handler.
        /// </summary>
        /// <param name="adapterName">The Adapter name.</param>
        /// <param name="hostName">The Host name.</param>
        /// <param name="isDefault">Indicating if the Handler is the default.</param>
        public static void Create(string adapterName, string hostName, bool isDefault)
        {
            PutOptions options = new PutOptions();
            options.Type = PutType.CreateOnly;
            using (ManagementClass handlerManagementClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_SendHandler2", null))
            {
                foreach (ManagementObject handler in handlerManagementClass.GetInstances())
                {
                    if ((string)handler["AdapterName"] == adapterName && (string)handler["HostName"] == hostName)
                    {
                        handler.Delete();
                    }
                }

                ManagementObject handlerInstance = handlerManagementClass.CreateInstance();
                if (handlerInstance == null)
                {
                    throw new CoreException("Could not create Management Object.");
                }

                handlerInstance["AdapterName"] = adapterName;
                handlerInstance["HostName"] = hostName;
                handlerInstance["IsDefault"] = isDefault;
                handlerInstance.Put(options);
            }
        }
        public static Status AddSendHostHandler(string Adapter, string HostName)
        {
            Status operationStatus = new Status();

            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.UpdateOnly;

                //Look for the target WMI Class MSBTS_SendHandler2 instance
                string strWQL = "SELECT * FROM MSBTS_SendHandler2 WHERE AdapterName = '" + Adapter + "'";
                ManagementObjectSearcher searcherSendHandler = new ManagementObjectSearcher(new ManagementScope("root\\MicrosoftBizTalkServer"), new WqlObjectQuery(strWQL), null);

                foreach (ManagementObject objSendHandler in searcherSendHandler.Get())
                {
                    objSendHandler.SetPropertyValue("HostNameToSwitchTo", HostName);
                    objSendHandler.Put();
                }

                operationStatus.Message = "Send Adapter " + Adapter + " set to use Host " + HostName;
            }
            catch (Exception exception)
            {
                operationStatus.Message = exception.Message;
                operationStatus.State = OperationState.FAILURE;
            }

            return operationStatus;
        }
        public static string MakeHost(string HostName, string Type, string HostNTGroup, bool AuthTrusted)
        {
            PutOptions options = new PutOptions();
            options.Type = PutType.CreateOnly;

            // create a ManagementClass object and spawn a ManagementObject instance
            ManagementClass objHostSettingClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_HostSetting", null);
            ManagementObject objHostSetting = objHostSettingClass.CreateInstance();

            // set the properties for the Managementobject
            // Host Name
            objHostSetting["Name"] = HostName;
            
            // Host Type
            if(Type == "Isolated")
                objHostSetting["HostType"] = HostType.Isolated;
            else
                objHostSetting["HostType"] = HostType.InProcess;

            objHostSetting["NTGroupName"] = HostNTGroup;

            objHostSetting["AuthTrusted"] = AuthTrusted;

            //create the Managementobject
            objHostSetting.Put(options);

            return Type + " Host - " + HostName + " - has been created. \r\n";
        }
        public static string AddReceiveHostHandler(string Adapter, string HostName)
        {
            PutOptions options = new PutOptions();
            options.Type = PutType.UpdateOnly;

            //Look for the target WMI Class MSBTS_ReceiveHandler instance
            string strWQL = "SELECT * FROM MSBTS_ReceiveHandler WHERE AdapterName = '" + Adapter + "'";
            ManagementObjectSearcher searcherReceiveHandler = new ManagementObjectSearcher(new ManagementScope("root\\MicrosoftBizTalkServer"), new WqlObjectQuery(strWQL), null);

            foreach (ManagementObject objReceiveHandler in searcherReceiveHandler.Get())
            {
                objReceiveHandler.SetPropertyValue("HostNameToSwitchTo", HostName);
                objReceiveHandler.Put();
            }

            return "    Receive Adapter " + Adapter + " set to use Host " + HostName + "\r\n";
        }
Beispiel #8
0
        /// <summary>
        /// Create a new Host.
        /// </summary>
        /// <param name="hostName">The Host name.</param>
        /// <param name="windowsGroupName">The Windows Group name.</param>
        /// <param name="trusted">Whether a trusted host.</param>
        /// <param name="hostType">The Host type.</param>
        /// <param name="hostTracking">Whether Host tracking is enabled.</param>
        /// <param name="isDefault">Whether the Host is default.</param>
        public static void Create(string hostName, string windowsGroupName, bool trusted, HostType hostType, bool hostTracking, bool isDefault)
        {
            PutOptions options = new PutOptions();
            options.Type = PutType.CreateOnly;
            ManagementObject btsHostSetting = HostManagement.GetHostSettingClass().CreateInstance();
            if (btsHostSetting == null)
            {
                throw new BizTalkExtensionsException("Could not create Management Object.");
            }

            btsHostSetting["Name"] = hostName;
            btsHostSetting["HostType"] = (int)hostType;
            btsHostSetting["NTGroupName"] = windowsGroupName;
            btsHostSetting["AuthTrusted"] = trusted;
            btsHostSetting["HostTracking"] = hostTracking;
            btsHostSetting["IsDefault"] = isDefault;
            btsHostSetting.Put(options);
        }
        private void Create()
        {
            if (this.CheckExists())
            {
                if (this.Force)
                {
                    this.Delete();
                }
                else
                {
                    this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "ReceiveHandler: {0} already exists for: {1}. Set Force to true to delete the ReceiveHandler.", this.AdapterName, this.HostName));
                    return;
                }
            }

            PutOptions options = new PutOptions { Type = PutType.CreateOnly };
            using (ManagementClass instance = new ManagementClass(this.Scope, new ManagementPath("MSBTS_ReceiveHandler"), null))
            {
                ManagementObject btsHostSetting = instance.CreateInstance();
                if (btsHostSetting == null)
                {
                    Log.LogError("There was a failure creating the MSBTS_ReceiveHandler instance");
                    return;
                }

                btsHostSetting["HostName"] = this.HostName;
                btsHostSetting["AdapterName"] = this.AdapterName;
                btsHostSetting["CustomCfg"] = this.CustomCfg;
                btsHostSetting["MgmtDbServerOverride"] = this.DatabaseServer;

                btsHostSetting.Put(options);
                this.explorer.SaveChanges();
            }
        }
Beispiel #10
0
 public void CommitObject(PutOptions putOptions)
 {
     if ((_isEmbedded == false))
     {
         _privateLateBoundObject.Put(putOptions);
     }
 }
        public static Status MakeHost(string HostName, string Type, string HostNTGroup, bool AuthTrusted)
        {
            Status operationStatus = new Status();

            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.CreateOnly;

                // create a ManagementClass object and spawn a ManagementObject instance
                ManagementClass objHostSettingClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_HostSetting", null);
                ManagementObject objHostSetting = objHostSettingClass.CreateInstance();

                // set the properties for the Managementobject
                // Host Name
                objHostSetting["Name"] = HostName;

                // Host Type
                if (Type == "Isolated")
                    objHostSetting["HostType"] = HostType.Isolated;
                else
                    objHostSetting["HostType"] = HostType.InProcess;

                objHostSetting["NTGroupName"] = HostNTGroup;

                objHostSetting["AuthTrusted"] = AuthTrusted;

                //create the Managementobject
                objHostSetting.Put(options);

                operationStatus.Message = Type + " Host - " + HostName + " - has been created.";
            }
            catch (Exception exception)
            {
                operationStatus.Message = exception.Message;
                operationStatus.State = OperationState.FAILURE;
            }

            return operationStatus;
        }
        /// <summary>
        ///    <para>Copies the object to a different location, asynchronously.</para>
        /// </summary>
        /// <param name='watcher'>The object that will receive the results of the operation.</param>
        /// <param name='path'>The path to which the object should be copied.</param>
        /// <param name='options'>The options for how the object should be put.</param>
        public void CopyTo(ManagementOperationObserver watcher, ManagementPath path, PutOptions options)
        {
            if (null == watcher)
                throw new ArgumentNullException("watcher");
            else
            {
                Initialize ( false ) ;
                ManagementScope destinationScope = null;

                destinationScope = new ManagementScope(path, scope);
                destinationScope.Initialize();

                PutOptions o = (null != options) ? (PutOptions) options.Clone() : new PutOptions();

                // If someone has registered for progress, make sure we flag it
                if (watcher.HaveListenersForProgress)
                    o.SendStatus = true;

                WmiEventSink sink = watcher.GetNewPutSink(destinationScope, o.Context, 
                    path.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY), ClassName);
                IWbemServices destWbemServices = destinationScope.GetIWbemServices();

                SecurityHandler securityHandler = null;
                int status                        = (int)ManagementStatus.NoError;

                securityHandler = destinationScope.GetSecurityHandler();

                if (IsClass)
                {
                    status = destinationScope.GetSecuredIWbemServicesHandler( destWbemServices ).PutClassAsync_(
                                                    wbemObject, 
                                                    o.Flags, 
                                                    o.GetContext(), 
                                                    sink.Stub);
                    
                }
                else
                {
                    status = destinationScope.GetSecuredIWbemServicesHandler( destWbemServices ).PutInstanceAsync_(
                                                    wbemObject, 
                                                    o.Flags, 
                                                    o.GetContext(), 
                                                    sink.Stub);
                }


                if (securityHandler != null)
                    securityHandler.Reset();

                if (status < 0)
                {
                    watcher.RemoveSink(sink);
                    if ((status & 0xfffff000) == 0x80041000)
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                    else
                        Marshal.ThrowExceptionForHR(status);
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Do the actual connection to remote machine for Set-WMIInstance cmdlet and raise operation complete event.
        /// </summary>
        private void ConnectSetWmi()
        {
            SetWmiInstance setObject = (SetWmiInstance)_wmiObject;
            _state = WmiState.Running;
            RaiseWmiOperationState(null, WmiState.Running);
            if (setObject.InputObject != null)
            {
                ManagementObject mObj = null;
                try
                {
                    PutOptions pOptions = new PutOptions();
                    //Extra check
                    if (setObject.InputObject.GetType() == typeof(ManagementClass))
                    {
                        //Check if Flag specified is CreateOnly or not
                        if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly)
                        {
                            InvalidOperationException e = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath");
                            internalException = e;
                            _state = WmiState.Failed;
                            RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                            return;
                        }
                        mObj = ((ManagementClass)setObject.InputObject).CreateInstance();
                        setObject.PutType = PutType.CreateOnly;
                    }
                    else
                    {
                        //Check if Flag specified is Updateonly or UpdateOrCreateOnly or not
                        if (setObject.flagSpecified)
                        {
                            if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate))
                            {
                                InvalidOperationException e = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath");
                                internalException = e;
                                _state = WmiState.Failed;
                                RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                                return;
                            }
                        }
                        else
                        {
                            setObject.PutType = PutType.UpdateOrCreate;
                        }

                        mObj = (ManagementObject)setObject.InputObject.Clone();
                    }
                    if (setObject.Arguments != null)
                    {
                        IDictionaryEnumerator en = setObject.Arguments.GetEnumerator();
                        while (en.MoveNext())
                        {
                            mObj[en.Key as string] = en.Value;
                        }
                    }
                    pOptions.Type = setObject.PutType;
                    if (mObj != null)
                    {
                        mObj.Put(_results, pOptions);
                    }
                    else
                    {
                        InvalidOperationException exp = new InvalidOperationException();
                        internalException = exp;
                        _state = WmiState.Failed;
                        RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                    }
                }
                catch (ManagementException e)
                {
                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                }
                catch (System.UnauthorizedAccessException e)
                {
                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                }
            }
            else
            {
                ManagementPath mPath = null;
                //If Class is specified only CreateOnly flag is supported
                if (setObject.Class != null)
                {
                    if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly)
                    {
                        InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath");
                        internalException = exp;
                        _state = WmiState.Failed;
                        RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                        return;
                    }
                    setObject.PutType = PutType.CreateOnly;
                }
                else
                {
                    mPath = new ManagementPath(setObject.Path);
                    if (String.IsNullOrEmpty(mPath.NamespacePath))
                    {
                        mPath.NamespacePath = setObject.Namespace;
                    }
                    else if (setObject.namespaceSpecified)
                    {
                        InvalidOperationException exp = new InvalidOperationException("NamespaceSpecifiedWithPath");
                        internalException = exp;
                        _state = WmiState.Failed;
                        RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                        return;
                    }

                    if (mPath.Server != "." && setObject.serverNameSpecified)
                    {
                        InvalidOperationException exp = new InvalidOperationException("ComputerNameSpecifiedWithPath");
                        internalException = exp;
                        _state = WmiState.Failed;
                        RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                        return;
                    }
                    if (mPath.IsClass)
                    {
                        if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly)
                        {
                            InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath");
                            internalException = exp;
                            _state = WmiState.Failed;
                            RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                            return;
                        }
                        setObject.PutType = PutType.CreateOnly;
                    }
                    else
                    {
                        if (setObject.flagSpecified)
                        {
                            if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate))
                            {
                                InvalidOperationException exp = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath");
                                internalException = exp;
                                _state = WmiState.Failed;
                                RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                                return;
                            }
                        }
                        else
                        {
                            setObject.PutType = PutType.UpdateOrCreate;
                        }
                    }
                }
                //If server name is specified loop through it.
                if (mPath != null)
                {
                    if (!(mPath.Server == "." && setObject.serverNameSpecified))
                    {
                        _computerName = mPath.Server;
                    }
                }
                ConnectionOptions options = setObject.GetConnectionOption();
                ManagementObject mObject = null;
                try
                {
                    if (setObject.Path != null)
                    {
                        mPath.Server = _computerName;
                        ManagementScope mScope = new ManagementScope(mPath, options);
                        if (mPath.IsClass)
                        {
                            ManagementClass mClass = new ManagementClass(mPath);
                            mClass.Scope = mScope;
                            mObject = mClass.CreateInstance();
                        }
                        else
                        {
                            //This can throw if path does not exist caller should catch it.
                            ManagementObject mInstance = new ManagementObject(mPath);
                            mInstance.Scope = mScope;
                            try
                            {
                                mInstance.Get();
                            }
                            catch (ManagementException e)
                            {
                                if (e.ErrorCode != ManagementStatus.NotFound)
                                {
                                    internalException = e;
                                    _state = WmiState.Failed;
                                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                                    return;
                                }
                                int namespaceIndex = setObject.Path.IndexOf(':');
                                if (namespaceIndex == -1)
                                {
                                    internalException = e;
                                    _state = WmiState.Failed;
                                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                                    return;
                                }
                                int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.');
                                if (classIndex == -1)
                                {
                                    internalException = e;
                                    _state = WmiState.Failed;
                                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                                    return;
                                }
                                //Get class object and create instance.
                                string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex);
                                ManagementPath classPath = new ManagementPath(newPath);
                                ManagementClass mClass = new ManagementClass(classPath);
                                mClass.Scope = mScope;
                                mInstance = mClass.CreateInstance();
                            }
                            mObject = mInstance;
                        }
                    }
                    else
                    {
                        ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, setObject.Namespace), options);
                        ManagementClass mClass = new ManagementClass(setObject.Class);
                        mClass.Scope = scope;
                        mObject = mClass.CreateInstance();
                    }
                    if (setObject.Arguments != null)
                    {
                        IDictionaryEnumerator en = setObject.Arguments.GetEnumerator();
                        while (en.MoveNext())
                        {
                            mObject[en.Key as string] = en.Value;
                        }
                    }
                    PutOptions pOptions = new PutOptions();
                    pOptions.Type = setObject.PutType;
                    if (mObject != null)
                    {
                        mObject.Put(_results, pOptions);
                    }
                    else
                    {
                        InvalidOperationException exp = new InvalidOperationException();
                        internalException = exp;
                        _state = WmiState.Failed;
                        RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                    }
                }
                catch (ManagementException e)
                {
                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                }
                catch (System.UnauthorizedAccessException e)
                {
                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                }
            }
        }
        public void ResetAdapters(string pathToXMLFile)
        {
            // Load the Config XML
            XmlDocument oDoc = new XmlDocument();
            oDoc.Load(pathToXMLFile);

            string defaulInProcessHost = oDoc.DocumentElement.GetAttribute("defaultHost").ToString();
            string defaulIsoHost = oDoc.DocumentElement.GetAttribute("defaultIsoHost").ToString();

            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.UpdateOnly;

                //Look for the target WMI Class MSBTS_ReceiveHandler instance
                string strWQL = "SELECT * FROM MSBTS_ReceiveHandler";
                ManagementObjectSearcher searcherReceiveHandler = new ManagementObjectSearcher(new ManagementScope("root\\MicrosoftBizTalkServer"), new WqlObjectQuery(strWQL), null);

                string recName;
                string recHost;
                string sndName;
                string sndHost;

                if (searcherReceiveHandler.Get().Count > 0)
                    foreach (ManagementObject objReceiveHandler in searcherReceiveHandler.Get())
                    {
                        //Get the Adapter Name
                        recName = objReceiveHandler["AdapterName"].ToString();

                        // Get the Current Host
                        recHost = objReceiveHandler["HostName"].ToString();

                        // Find the Host Type
                        string strWQLHost = "SELECT * FROM MSBTS_HostInstanceSetting where HostName = '" + recHost + "'";
                        ManagementObjectSearcher searcherHostHandler = new ManagementObjectSearcher(new ManagementScope("root\\MicrosoftBizTalkServer"), new WqlObjectQuery(strWQLHost), null);

                        foreach (ManagementObject objHostHandler in searcherHostHandler.Get())
                        {
                            // Type 1 is In Process
                            if (objHostHandler["HostType"].ToString() == "1")
                            {
                                objReceiveHandler.SetPropertyValue("HostNameToSwitchTo", defaulInProcessHost);
                                objReceiveHandler.Put();
                            }
                            // Otherwise it is Isolated
                            else
                            {
                                objReceiveHandler.SetPropertyValue("HostNameToSwitchTo", defaulIsoHost);
                                objReceiveHandler.Put();
                            }
                        }

                        Console.WriteLine( "Receive Adapters: - " + recName + " \r\n");
                    }

                //Look for the target WMI Class MSBTS_SendHandler instance
                string strWQLsnd = "SELECT * FROM MSBTS_SendHandler2";
                ManagementObjectSearcher searcherSendHandler = new ManagementObjectSearcher(new ManagementScope("root\\MicrosoftBizTalkServer"), new WqlObjectQuery(strWQLsnd), null);

                if (searcherSendHandler.Get().Count > 0)
                    foreach (ManagementObject objSendHandler in searcherSendHandler.Get())
                    {
                        //Get the Adapter Name
                        sndName = objSendHandler["AdapterName"].ToString();

                        // Get the Current Host
                        sndHost = objSendHandler["HostName"].ToString();

                        // Find the Host Type
                        string strWQLHost = "SELECT * FROM MSBTS_HostInstanceSetting where HostName = '" + sndHost + "'";
                        ManagementObjectSearcher searcherHostHandler = new ManagementObjectSearcher(new ManagementScope("root\\MicrosoftBizTalkServer"), new WqlObjectQuery(strWQLHost), null);

                        foreach (ManagementObject objHostHandler in searcherHostHandler.Get())
                        {
                            // Type 1 is In Process
                            if (objHostHandler["HostType"].ToString() == "1")
                            {
                                objSendHandler.SetPropertyValue("HostNameToSwitchTo", defaulInProcessHost);
                                objSendHandler.Put();
                            }
                            // Otherwise it is Isolated
                            else
                            {
                                objSendHandler.SetPropertyValue("HostNameToSwitchTo", defaulIsoHost);
                                objSendHandler.Put();
                            }
                        }

                        Console.WriteLine( "Send Adapters: - " + sndName + " \r\n");
                    }

                Console.WriteLine( "Done");
            }
            catch (Exception ex)
            {
                Console.WriteLine( ex.Message);
            }
        }
		public ManagementPath Put (PutOptions options)
		{
			throw new NotImplementedException ();
		}
Beispiel #16
0
 public ManagementPath Put(PutOptions options)
 {
     throw new NotImplementedException();
 }
Beispiel #17
0
 public void CopyTo(ManagementOperationObserver watcher, string path, PutOptions options)
 {
     throw new NotImplementedException();
 }
Beispiel #18
0
 public ManagementPath CopyTo(string path, PutOptions options)
 {
     throw new NotImplementedException();
 }
Beispiel #19
0
        private void addIPPort()
        {
            var conn = new ConnectionOptions
            {
                EnablePrivileges = true,
                Impersonation = ImpersonationLevel.Impersonate
            };

            var mPath = new ManagementPath("Win32_TCPIPPrinterPort");

            var mScope = new ManagementScope(@"\\.\root\cimv2", conn)
            {
                Options =
                {
                    EnablePrivileges = true,
                    Impersonation = ImpersonationLevel.Impersonate
                }
            };

            var mPort = new ManagementClass(mScope, mPath, null).CreateInstance();

            var remotePort = 9100;

            try
            {
                if (IP != null && IP.Contains(":"))
                {
                    var arIP = IP.Split(':');
                    if (arIP.Length == 2)
                        remotePort = int.Parse(arIP[1]);
                }
            }
            catch (Exception ex)
            {
                Log.Error(LogName, "Could not parse port from IP");
                Log.Error(LogName, ex);
            }

            mPort.SetPropertyValue("Name", Port);
            mPort.SetPropertyValue("Protocol", 1);
            mPort.SetPropertyValue("HostAddress", IP);
            mPort.SetPropertyValue("PortNumber", remotePort);
            mPort.SetPropertyValue("SNMPEnabled", false);

            var put = new PutOptions
            {
                UseAmendedQualifiers = true,
                Type = PutType.UpdateOrCreate
            };
            mPort.Put(put);
        }
Beispiel #20
0
        /// <summary>
        /// Create a new Host instance.
        /// </summary>
        /// <param name="serverName">The server name.</param>
        /// <param name="hostName">The Host name.</param>
        /// <param name="userName">The username.</param>
        /// <param name="password">The password.</param>
        public static void CreateInstance(string serverName, string hostName, string userName, string password)
        {
            if (hostName == ".")
            {
                throw new ArgumentException("The 'hostName' may not be a period ('.'), use the actual host name.", "hostName");
            }

            PutOptions options = new PutOptions();
            options.Type = PutType.CreateOnly;
            ObjectGetOptions bts_objOptions = new ObjectGetOptions();
            using (ManagementClass bts_AdminObjClassServerHost = new ManagementClass(@"root\MicrosoftBizTalkServer", "MSBTS_ServerHost", bts_objOptions))
            {
                using (ManagementObject bts_AdminObjectServerHost = bts_AdminObjClassServerHost.CreateInstance())
                {
                    if (bts_AdminObjectServerHost == null)
                    {
                        throw new BizTalkExtensionsException("Could not create Management Object.");
                    }

                    bts_AdminObjectServerHost["ServerName"] = serverName;
                    bts_AdminObjectServerHost["HostName"] = hostName;
                    bts_AdminObjectServerHost.InvokeMethod("Map", null);
                    using (ManagementClass bts_AdminObjClassHostInstance = new ManagementClass(@"root\MicrosoftBizTalkServer", "MSBTS_HostInstance", bts_objOptions))
                    {
                        using (ManagementObject bts_AdminObjectHostInstance = bts_AdminObjClassHostInstance.CreateInstance())
                        {
                            if (bts_AdminObjectHostInstance == null)
                            {
                                throw new BizTalkExtensionsException("Could not create Management Object.");
                            }

                            bts_AdminObjectHostInstance["Name"] = string.Format(CultureInfo.CurrentCulture, "Microsoft BizTalk Server {0} {1}", hostName, serverName);
                            string user = userName;
                            string pwd = password;
                            object[] objparams = new object[3];
                            objparams[0] = user;
                            objparams[1] = pwd;
                            objparams[2] = true;
                            bts_AdminObjectHostInstance.InvokeMethod("Install", objparams);
                        }
                    }
                }
            }
        }
Beispiel #21
0
		public void CopyTo(ManagementOperationObserver watcher, ManagementPath path, PutOptions options)
		{
			int num;
			PutOptions putOption;
			if (watcher != null)
			{
				this.Initialize(false);
				ManagementScope managementScope = new ManagementScope(path, this.scope);
				managementScope.Initialize();
				if (options != null)
				{
					putOption = (PutOptions)options.Clone();
				}
				else
				{
					putOption = new PutOptions();
				}
				PutOptions putOption1 = putOption;
				if (watcher.HaveListenersForProgress)
				{
					putOption1.SendStatus = true;
				}
				WmiEventSink newPutSink = watcher.GetNewPutSink(managementScope, putOption1.Context, path.GetNamespacePath(8), base.ClassName);
				IWbemServices wbemServices = managementScope.GetIWbemServices();
				SecurityHandler securityHandler = managementScope.GetSecurityHandler();
				if (!base.IsClass)
				{
					num = managementScope.GetSecuredIWbemServicesHandler(wbemServices).PutInstanceAsync_(base.wbemObject, putOption1.Flags, putOption1.GetContext(), newPutSink.Stub);
				}
				else
				{
					num = managementScope.GetSecuredIWbemServicesHandler(wbemServices).PutClassAsync_(base.wbemObject, putOption1.Flags, putOption1.GetContext(), newPutSink.Stub);
				}
				if (securityHandler != null)
				{
					securityHandler.Reset();
				}
				if (num < 0)
				{
					watcher.RemoveSink(newPutSink);
					if (((long)num & (long)-4096) != (long)-2147217408)
					{
						Marshal.ThrowExceptionForHR(num);
					}
					else
					{
						ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
						return;
					}
				}
				return;
			}
			else
			{
				throw new ArgumentNullException("watcher");
			}
		}
		public ManagementPath CopyTo (string path, PutOptions options)
		{
			throw new NotImplementedException ();
		}
Beispiel #23
0
		public void CopyTo(ManagementOperationObserver watcher, string path, PutOptions options)
		{
			this.CopyTo(watcher, new ManagementPath(path), options);
		}
		public void CopyTo (ManagementOperationObserver watcher, string path, PutOptions options)
		{
			throw new NotImplementedException ();
		}
        /// <summary>
        ///    <para>Copies the object to a different location.</para>
        /// </summary>
        /// <param name='path'>The <see cref='System.Management.ManagementPath'/> to which the object should be copied.</param>
        /// <param name='options'>The options for how the object should be put.</param>
        /// <returns>
        ///    The new path of the copied object.
        /// </returns>
        public ManagementPath CopyTo(ManagementPath path, PutOptions options)
        {
            Initialize ( false ) ;

            ManagementScope destinationScope = null;
            
            // Build a scope for our target destination
            destinationScope = new ManagementScope(path, scope);
            destinationScope.Initialize();

            PutOptions o = (null != options) ? options : new PutOptions();
            IWbemServices wbemServices = destinationScope.GetIWbemServices();
            ManagementPath newPath = null;

            //
            // TO-DO : This code is almost identical to Put - should consolidate.
            //
            // Must do this convoluted allocation since the IWbemServices ref IWbemCallResult
            // has been redefined to be an IntPtr.  Due to the fact that it wasn't possible to
            // pass NULL for the optional argument.
            //
            IntPtr ppwbemCallResult            = IntPtr.Zero;
            IntPtr pwbemCallResult            = IntPtr.Zero;
            IWbemCallResult wbemCallResult    = null;
            SecurityHandler securityHandler    = null;
            int status                        = (int)ManagementStatus.NoError;

            try 
            {
                securityHandler = destinationScope.GetSecurityHandler();

                ppwbemCallResult = Marshal.AllocHGlobal(IntPtr.Size);
                Marshal.WriteIntPtr(ppwbemCallResult, IntPtr.Zero);        // Init to NULL.

                if (IsClass)
                {
                    status = scope.GetSecuredIWbemServicesHandler( wbemServices ).PutClass_(
                        wbemObject, 
                        o.Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY, 
                        o.GetContext(), 
                        ppwbemCallResult);
                }
                else
                {
                    status = scope.GetSecuredIWbemServicesHandler( wbemServices ).PutInstance_(
                        wbemObject, 
                        o.Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY, 
                        o.GetContext(), 
                        ppwbemCallResult);
                    
                }


                // Keep this statement here; otherwise, there'll be a leak in error cases.
                pwbemCallResult = Marshal.ReadIntPtr(ppwbemCallResult);

                //Use the CallResult to retrieve the resulting object path
                wbemCallResult = (IWbemCallResult)Marshal.GetObjectForIUnknown(pwbemCallResult);

                int hr;
                status = wbemCallResult.GetCallStatus_((int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE, out hr);

                if (status >= 0)
                    status = hr;

                if (status < 0)
                {
                    if ((status & 0xfffff000) == 0x80041000)
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                    else
                        Marshal.ThrowExceptionForHR(status);
                }

                newPath = GetPath(wbemCallResult);
                newPath.NamespacePath = path.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
            } 
            finally
            {
                if (securityHandler != null)
                    securityHandler.Reset();
                
                if (ppwbemCallResult != IntPtr.Zero)                    // Cleanup from allocations above.
                    Marshal.FreeHGlobal(ppwbemCallResult);
                
                if (pwbemCallResult != IntPtr.Zero)
                    Marshal.Release(pwbemCallResult);
                
                if (wbemCallResult != null)
                    Marshal.ReleaseComObject(wbemCallResult);
            }

            return newPath;
        }
		public void Put (ManagementOperationObserver watcher, PutOptions options)
		{
			throw new NotImplementedException ();
		}
Beispiel #27
0
		public ManagementPath CopyTo(ManagementPath path, PutOptions options)
		{
			int callStatus_;
			int num = 0;
			PutOptions putOption;
			this.Initialize(false);
			ManagementScope managementScope = new ManagementScope(path, this.scope);
			managementScope.Initialize();
			if (options != null)
			{
				putOption = options;
			}
			else
			{
				putOption = new PutOptions();
			}
			PutOptions putOption1 = putOption;
			IWbemServices wbemServices = managementScope.GetIWbemServices();
			ManagementPath namespacePath = null;
			IntPtr zero = IntPtr.Zero;
			IntPtr intPtr = IntPtr.Zero;
			IWbemCallResult objectForIUnknown = null;
			SecurityHandler securityHandler = null;
			try
			{
				securityHandler = managementScope.GetSecurityHandler();
				zero = Marshal.AllocHGlobal(IntPtr.Size);
				Marshal.WriteIntPtr(zero, IntPtr.Zero);
				if (!base.IsClass)
				{
					callStatus_ = this.scope.GetSecuredIWbemServicesHandler(wbemServices).PutInstance_(base.wbemObject, putOption1.Flags | 16, putOption1.GetContext(), zero);
				}
				else
				{
					callStatus_ = this.scope.GetSecuredIWbemServicesHandler(wbemServices).PutClass_(base.wbemObject, putOption1.Flags | 16, putOption1.GetContext(), zero);
				}
				intPtr = Marshal.ReadIntPtr(zero);
				objectForIUnknown = (IWbemCallResult)Marshal.GetObjectForIUnknown(intPtr);
				callStatus_ = objectForIUnknown.GetCallStatus_(-1, out num);
				if (callStatus_ >= 0)
				{
					callStatus_ = num;
				}
				if (callStatus_ < 0)
				{
					if (((long)callStatus_ & (long)-4096) != (long)-2147217408)
					{
						Marshal.ThrowExceptionForHR(callStatus_);
					}
					else
					{
						ManagementException.ThrowWithExtendedInfo((ManagementStatus)callStatus_);
					}
				}
				namespacePath = this.GetPath(objectForIUnknown);
				namespacePath.NamespacePath = path.GetNamespacePath(8);
			}
			finally
			{
				if (securityHandler != null)
				{
					securityHandler.Reset();
				}
				if (zero != IntPtr.Zero)
				{
					Marshal.FreeHGlobal(zero);
				}
				if (intPtr != IntPtr.Zero)
				{
					Marshal.Release(intPtr);
				}
				if (objectForIUnknown != null)
				{
					Marshal.ReleaseComObject(objectForIUnknown);
				}
			}
			return namespacePath;
		}
Beispiel #28
0
        public Boolean install(long maxWait)
        {
            long waited = 0L;
            int port = 9100;
            if (isComplete())
            {
                if (maxWait > 0)
                {
                    //if ( strFile.Length == 0 || File.Exists(strFile))
                    //{
                        if (strIP != null && strIP.Length > 0 )
                        {
                            if (strIP.Contains(":"))
                            {
                                String[] arIP = strIP.Split(new char[] { ':' });
                                if (arIP.Length == 2)
                                {
                                    strIP = arIP[0];
                                    try
                                    {
                                        port = Int32.Parse( arIP[1] );
                                    }
                                    catch
                                    {

                                    }
                                }
                            }

                            ConnectionOptions conn = new ConnectionOptions();
                            conn.EnablePrivileges = true;
                            conn.Impersonation = ImpersonationLevel.Impersonate;

                            ManagementPath mPath = new ManagementPath("Win32_TCPIPPrinterPort");

                            ManagementScope mScope = new ManagementScope(@"\\.\root\cimv2", conn);
                            mScope.Options.EnablePrivileges = true;
                            mScope.Options.Impersonation = ImpersonationLevel.Impersonate;

                            ManagementObject mPort = new ManagementClass(mScope, mPath, null).CreateInstance();

                            mPort.SetPropertyValue("Name", "IP_" + strIP);
                            mPort.SetPropertyValue("Protocol", 1);
                            mPort.SetPropertyValue("HostAddress", strIP);
                            mPort.SetPropertyValue("PortNumber", port);
                            mPort.SetPropertyValue("SNMPEnabled", false);

                            PutOptions put = new PutOptions();
                            put.UseAmendedQualifiers = true;
                            put.Type = PutType.UpdateOrCreate;
                            mPort.Put(put);
                        }

                        Process proc;
                        Boolean blIsIPP = false;

                        if (strPort.Trim().ToLower().StartsWith("ipp://"))
                        {
                            // iprint installation
                            proc = new Process();
                            proc.StartInfo.FileName = @"c:\windows\system32\iprntcmd.exe";
                            proc.StartInfo.Arguments = " -a no-gui \"" + strPort + "\"";
                            proc.StartInfo.CreateNoWindow = true;
                            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                            proc.Start();
                            blIsIPP = true;
                        }
                        else if (strAlias.Trim().ToLower().StartsWith("\\\\"))
                        {
                            // Add per machine printer connection
                            proc = Process.Start("rundll32.exe", " printui.dll,PrintUIEntry /ga /n " + strAlias);
                            proc.WaitForExit(120000);
                            // Add printer network connection, download the drivers from the print server
                            proc = Process.Start("rundll32.exe", " printui.dll,PrintUIEntry /in /n " + strAlias);
                            proc.WaitForExit(120000);
                            bounceSpooler();
                        }
                        else
                        {
                            // Normal Installation
                            proc = Process.Start("rundll32.exe", getInstallArguments());
                        }

                        while (!proc.HasExited)
                        {
                            sleep(100);
                            waited += 100;
                            if (waited > maxWait)
                            {
                                proc.Kill();
                                strError = "Max install time exceeded (" + maxWait + ")";
                                return false;
                            }
                        }

                        if (blIsIPP)
                        {
                            strError = "IPP Return codes unknown";
                            return true;
                        }

                        if (proc.ExitCode == 0)
                        {
                            strError = "";
                            return true;
                        }
                    //}
                    //else
                        //strError = "Printer Definition file was not found!";
                    //strError = "Strfile:" + strFile + ".";
                }
                else
                    strError = "Max wait time was less than zero!";
            }
            else
                strError = "Printer information is incomplete";
            return false;
        }
Beispiel #29
0
		private void ConnectSetWmi()
		{
			ManagementObject value;
			SetWmiInstance setWmiInstance = (SetWmiInstance)this.wmiObject;
			this.state = WmiState.Running;
			this.RaiseWmiOperationState(null, WmiState.Running);
			if (setWmiInstance.InputObject == null)
			{
				ManagementPath managementPath = null;
				if (setWmiInstance.Class == null)
				{
					managementPath = new ManagementPath(setWmiInstance.Path);
					if (!string.IsNullOrEmpty(managementPath.NamespacePath))
					{
						if (setWmiInstance.namespaceSpecified)
						{
							InvalidOperationException invalidOperationException = new InvalidOperationException("NamespaceSpecifiedWithPath");
							this.internalException = invalidOperationException;
							this.state = WmiState.Failed;
							this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
							return;
						}
					}
					else
					{
						managementPath.NamespacePath = setWmiInstance.Namespace;
					}
					if (!(managementPath.Server != ".") || !setWmiInstance.serverNameSpecified)
					{
						if (!managementPath.IsClass)
						{
							if (!setWmiInstance.flagSpecified)
							{
								setWmiInstance.PutType = PutType.UpdateOrCreate;
							}
							else
							{
								if (setWmiInstance.PutType != PutType.UpdateOnly && setWmiInstance.PutType != PutType.UpdateOrCreate)
								{
									InvalidOperationException invalidOperationException1 = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath");
									this.internalException = invalidOperationException1;
									this.state = WmiState.Failed;
									this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
									return;
								}
							}
						}
						else
						{
							if (!setWmiInstance.flagSpecified || setWmiInstance.PutType == PutType.CreateOnly)
							{
								setWmiInstance.PutType = PutType.CreateOnly;
							}
							else
							{
								InvalidOperationException invalidOperationException2 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath");
								this.internalException = invalidOperationException2;
								this.state = WmiState.Failed;
								this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
								return;
							}
						}
					}
					else
					{
						InvalidOperationException invalidOperationException3 = new InvalidOperationException("ComputerNameSpecifiedWithPath");
						this.internalException = invalidOperationException3;
						this.state = WmiState.Failed;
						this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
						return;
					}
				}
				else
				{
					if (setWmiInstance.flagSpecified && setWmiInstance.PutType != PutType.CreateOnly)
					{
						InvalidOperationException invalidOperationException4 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath");
						this.internalException = invalidOperationException4;
						this.state = WmiState.Failed;
						this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
						return;
					}
					setWmiInstance.PutType = PutType.CreateOnly;
				}
				if (managementPath != null && (!(managementPath.Server == ".") || !setWmiInstance.serverNameSpecified))
				{
					this.computerName = managementPath.Server;
				}
				ConnectionOptions connectionOption = setWmiInstance.GetConnectionOption();
				try
				{
					if (setWmiInstance.Path == null)
					{
						ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, setWmiInstance.Namespace), connectionOption);
						ManagementClass managementClass = new ManagementClass(setWmiInstance.Class);
						managementClass.Scope = managementScope;
						value = managementClass.CreateInstance();
					}
					else
					{
						managementPath.Server = this.computerName;
						ManagementScope managementScope1 = new ManagementScope(managementPath, connectionOption);
						if (!managementPath.IsClass)
						{
							ManagementObject managementObject = new ManagementObject(managementPath);
							managementObject.Scope = managementScope1;
							try
							{
								managementObject.Get();
							}
							catch (ManagementException managementException1)
							{
								ManagementException managementException = managementException1;
								if (managementException.ErrorCode == ManagementStatus.NotFound)
								{
									int num = setWmiInstance.Path.IndexOf(':');
									if (num != -1)
									{
										int num1 = setWmiInstance.Path.Substring(num).IndexOf('.');
										if (num1 != -1)
										{
											string str = setWmiInstance.Path.Substring(0, num1 + num);
											ManagementPath managementPath1 = new ManagementPath(str);
											ManagementClass managementClass1 = new ManagementClass(managementPath1);
											managementClass1.Scope = managementScope1;
											managementObject = managementClass1.CreateInstance();
										}
										else
										{
											this.internalException = managementException;
											this.state = WmiState.Failed;
											this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
											return;
										}
									}
									else
									{
										this.internalException = managementException;
										this.state = WmiState.Failed;
										this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
										return;
									}
								}
								else
								{
									this.internalException = managementException;
									this.state = WmiState.Failed;
									this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
									return;
								}
							}
							value = managementObject;
						}
						else
						{
							ManagementClass managementClass2 = new ManagementClass(managementPath);
							managementClass2.Scope = managementScope1;
							value = managementClass2.CreateInstance();
						}
					}
					if (setWmiInstance.Arguments != null)
					{
						IDictionaryEnumerator enumerator = setWmiInstance.Arguments.GetEnumerator();
						while (enumerator.MoveNext())
						{
							value[enumerator.Key as string] = enumerator.Value;
						}
					}
					PutOptions putOption = new PutOptions();
					putOption.Type = setWmiInstance.PutType;
					if (value == null)
					{
						InvalidOperationException invalidOperationException5 = new InvalidOperationException();
						this.internalException = invalidOperationException5;
						this.state = WmiState.Failed;
						this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
					}
					else
					{
						value.Put(this.results, putOption);
					}
				}
				catch (ManagementException managementException3)
				{
					ManagementException managementException2 = managementException3;
					this.internalException = managementException2;
					this.state = WmiState.Failed;
					this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
				}
				catch (COMException cOMException1)
				{
					COMException cOMException = cOMException1;
					this.internalException = cOMException;
					this.state = WmiState.Failed;
					this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
				}
				catch (UnauthorizedAccessException unauthorizedAccessException1)
				{
					UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1;
					this.internalException = unauthorizedAccessException;
					this.state = WmiState.Failed;
					this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
				}
			}
			else
			{
				ManagementObject value1 = null;
				try
				{
					PutOptions putType = new PutOptions();
					if (setWmiInstance.InputObject.GetType() != typeof(ManagementClass))
					{
						if (!setWmiInstance.flagSpecified)
						{
							setWmiInstance.PutType = PutType.UpdateOrCreate;
						}
						else
						{
							if (setWmiInstance.PutType != PutType.UpdateOnly && setWmiInstance.PutType != PutType.UpdateOrCreate)
							{
								InvalidOperationException invalidOperationException6 = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath");
								this.internalException = invalidOperationException6;
								this.state = WmiState.Failed;
								this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
								return;
							}
						}
						value1 = (ManagementObject)setWmiInstance.InputObject.Clone();
					}
					else
					{
						if (!setWmiInstance.flagSpecified || setWmiInstance.PutType == PutType.CreateOnly)
						{
							value1 = ((ManagementClass)setWmiInstance.InputObject).CreateInstance();
							setWmiInstance.PutType = PutType.CreateOnly;
						}
						else
						{
							InvalidOperationException invalidOperationException7 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath");
							this.internalException = invalidOperationException7;
							this.state = WmiState.Failed;
							this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
							return;
						}
					}
					if (setWmiInstance.Arguments != null)
					{
						IDictionaryEnumerator dictionaryEnumerator = setWmiInstance.Arguments.GetEnumerator();
						while (dictionaryEnumerator.MoveNext())
						{
							value1[dictionaryEnumerator.Key as string] = dictionaryEnumerator.Value;
						}
					}
					putType.Type = setWmiInstance.PutType;
					if (value1 == null)
					{
						InvalidOperationException invalidOperationException8 = new InvalidOperationException();
						this.internalException = invalidOperationException8;
						this.state = WmiState.Failed;
						this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
					}
					else
					{
						value1.Put(this.results, putType);
					}
				}
				catch (ManagementException managementException5)
				{
					ManagementException managementException4 = managementException5;
					this.internalException = managementException4;
					this.state = WmiState.Failed;
					this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
				}
				catch (COMException cOMException3)
				{
					COMException cOMException2 = cOMException3;
					this.internalException = cOMException2;
					this.state = WmiState.Failed;
					this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
				}
				catch (UnauthorizedAccessException unauthorizedAccessException3)
				{
					UnauthorizedAccessException unauthorizedAccessException2 = unauthorizedAccessException3;
					this.internalException = unauthorizedAccessException2;
					this.state = WmiState.Failed;
					this.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
				}
			}
		}
Beispiel #30
0
		public ManagementPath CopyTo(string path, PutOptions options)
		{
			return this.CopyTo(new ManagementPath(path), options);
		}
        private void CreateOrUpdate()
        {
            PutOptions options = new PutOptions { Type = PutType.UpdateOrCreate };
            using (ManagementClass instance = new ManagementClass(this.Scope, new ManagementPath("MSBTS_AdapterSetting"), null))
            {
                ManagementObject btsHostSetting = instance.CreateInstance();
                if (btsHostSetting == null)
                {
                    Log.LogError("There was a failure creating the MSBTS_AdapterSetting instance");
                    return;
                }

                btsHostSetting["Name"] = this.AdaptorName;
                btsHostSetting["Comment"] = this.Comment ?? string.Empty;
                btsHostSetting["MgmtCLSID"] = this.MgmtCLSID;
                btsHostSetting.Put(options);
                this.explorer.SaveChanges();
            }
        }
Beispiel #32
0
 public void Put(ManagementOperationObserver watcher, PutOptions options)
 {
     throw new NotImplementedException();
 }
Beispiel #33
0
        public override void Add()
        {
            Log.Entry(LogName, "Attempting to add printer:");
            Log.Entry(LogName, string.Format("--> Name = {0}", Name));
            Log.Entry(LogName, string.Format("--> IP = {0}", IP));
            Log.Entry(LogName, string.Format("--> Port = {0}", Port));

            if (string.IsNullOrEmpty(IP) || !Name.StartsWith("\\\\")) return;

            if (IP.Contains(":"))
            {
                var arIP = IP.Split(':');
                if (arIP.Length == 2)
                {
                    IP = arIP[0];
                    Port = arIP[1];
                }
            }

            var conn = new ConnectionOptions
            {
                EnablePrivileges = true,
                Impersonation = ImpersonationLevel.Impersonate
            };

            var mPath = new ManagementPath("Win32_TCPIPPrinterPort");

            var mScope = new ManagementScope(@"\\.\root\cimv2", conn)
            {
                Options =
                {
                    EnablePrivileges = true,
                    Impersonation = ImpersonationLevel.Impersonate
                }
            };

            var mPort = new ManagementClass(mScope, mPath, null).CreateInstance();

            if (mPort != null)
            {
                mPort.SetPropertyValue("Name", "IP_" + IP);
                mPort.SetPropertyValue("Protocol", 1);
                mPort.SetPropertyValue("HostAddress", IP);
                mPort.SetPropertyValue("PortNumber", Port);
                mPort.SetPropertyValue("SNMPEnabled", false);

                var put = new PutOptions
                {
                    UseAmendedQualifiers = true,
                    Type = PutType.UpdateOrCreate
                };
                mPort.Put(put);
            }

            if (!Name.StartsWith("\\\\")) return;

            // Add per machine printer connection
            var proc = Process.Start("rundll32.exe", " printui.dll,PrintUIEntry /ga /n " + Name);
            if (proc != null) proc.WaitForExit(120000);
            // Add printer network connection, download the drivers from the print server
            proc = Process.Start("rundll32.exe", " printui.dll,PrintUIEntry /in /n " + Name);
            if (proc != null) proc.WaitForExit(120000);
        }
        private void CreateOrUpdate()
        {
            if (string.IsNullOrEmpty(this.WindowsGroup))
            {
                Log.LogError("WindowsGroup is required.");
                return;
            }
            
            PutOptions options = new PutOptions { Type = PutType.UpdateOrCreate };
            using (ManagementClass instance = new ManagementClass(this.Scope, new ManagementPath("MSBTS_HostSetting"), null))
            {
                ManagementObject btsHostSetting = instance.CreateInstance();
                if (btsHostSetting == null)
                {
                    Log.LogError("There was a failure creating the MSBTS_HostSetting instance");
                    return;
                }

                btsHostSetting["Name"] = this.HostName;
                btsHostSetting["HostType"] = this.hostType;
                btsHostSetting["NTGroupName"] = this.WindowsGroup;
                btsHostSetting["AuthTrusted"] = this.Trusted;
                btsHostSetting["MgmtDbServerOverride"] = this.DatabaseServer;
                btsHostSetting["IsHost32BitOnly"] = this.Use32BitHostOnly;

                if (this.hostType == BizTalkHostType.InProcess)
                {
                    btsHostSetting.SetPropertyValue("HostTracking", this.Tracking);
                    btsHostSetting.SetPropertyValue("IsDefault", this.Default);
                }

                if (!string.IsNullOrEmpty(this.AdditionalHostSettings))
                {
                    string[] additionalproperties = this.AdditionalHostSettings.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string s in additionalproperties)
                    {
                        string[] property = s.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                        btsHostSetting[property[0]] = property[1];
                    }
                }

                btsHostSetting.Put(options);
                this.explorer.SaveChanges();
            }
        }
        /// <summary>
        ///    <para>Commits the changes to the object asynchronously and
        ///       using the specified options.</para>
        /// </summary>
        /// <param name='watcher'>A <see cref='System.Management.ManagementOperationObserver'/> used to handle the progress and results of the asynchronous operation.</param>
        /// <param name=' options'>A <see cref='System.Management.PutOptions'/> used to specify additional options for the commit operation.</param>
        public void Put(ManagementOperationObserver watcher, PutOptions options)
        {
            if (null == watcher)
                throw new ArgumentNullException("watcher");
            else
            {
                Initialize ( false ) ;

                PutOptions o = (null == options) ?
                    new PutOptions() : (PutOptions)options.Clone();
                
                // If someone has registered for progress, make sure we flag it
                if (watcher.HaveListenersForProgress)
                    o.SendStatus = true;

                IWbemServices wbemServices = scope.GetIWbemServices();
                WmiEventSink sink = watcher.GetNewPutSink(scope, 
                    o.Context, scope.Path.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY), ClassName);

                // Add ourselves to the watcher so we can update our state
                sink.InternalObjectPut += 
                    new InternalObjectPutEventHandler(this.HandleObjectPut);

                SecurityHandler securityHandler    = null;
                // Assign to error initially to insure internal event handler cleanup
                // on non-management exception.
                int status                        = (int)ManagementStatus.Failed;

                securityHandler = scope.GetSecurityHandler();

                if (IsClass)
                {
                    status = scope.GetSecuredIWbemServicesHandler( wbemServices ).PutClassAsync_(
                        wbemObject, 
                        o.Flags, 
                        o.GetContext(),
                        sink.Stub);
                }
                else
                {
                    status = scope.GetSecuredIWbemServicesHandler( wbemServices ).PutInstanceAsync_(
                        wbemObject, 
                        o.Flags, 
                        o.GetContext(),
                        sink.Stub);
                }

                
                if (securityHandler != null)
                    securityHandler.Reset();

                if (status < 0)
                {
                    sink.InternalObjectPut -= new InternalObjectPutEventHandler(this.HandleObjectPut);
                    watcher.RemoveSink(sink);
                    if ((status & 0xfffff000) == 0x80041000)
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                    else
                        Marshal.ThrowExceptionForHR(status);
                }
            }
        }