public WqlConnectionManager Connect(string pServerName, string pUserName, string pPassword) { try { SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); if (System.Net.Dns.GetHostName().ToUpper() == pServerName.ToUpper()) { connection.Connect(pServerName); } else { connection.Connect(pServerName, pUserName, pPassword); } return(connection); } catch (SmsException ex) { Console.WriteLine("Failed to connect. Error: " + ex.Message); return(null); } catch (UnauthorizedAccessException ex) { Console.WriteLine("Failed to authenticate. Error: " + ex.Message); throw; } }
/// <summary> /// Connects the the SCCM site server. /// </summary> /// <param name="serverName"></param> /// <param name="userName"></param> /// <param name="userPassword"></param> /// <returns>WqlConnectionManager object or null if failed.</returns> public WqlConnectionManager Connect(string serverName, string userName, string userPassword) { try { Console.WriteLine("Connecting..."); var namedValues = new SmsNamedValuesDictionary(); var connection = new WqlConnectionManager(namedValues); if (string.IsNullOrEmpty(userName)) { connection.Connect(serverName); } else { connection.Connect(serverName, userName, userPassword); } return(connection); } catch (SmsException ex) { Console.WriteLine("Failed to Connect. Error: " + ex.Message); return(null); } catch (UnauthorizedAccessException ex) { Console.WriteLine("Failed to authenticate. Error:" + ex.Message); return(null); } }
public WqlConnectionManager Connect(string serverName) { try { SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); connection.Connect(serverName); return(connection); } catch (SmsException ex) { Trace.WriteLine(DateTime.Now + ": Unhandled expection thrown by SMS Provider: " + ex.ToString()); throw ex; } catch (UnauthorizedAccessException ex) { Trace.WriteLine(DateTime.Now + ": Unathorized access exception thrown: " + ex.ToString()); throw ex; } catch (Exception ex) { Trace.WriteLine(DateTime.Now + ": Unhandled expection thrown: " + ex.ToString()); throw ex; } }
public WqlConnectionManager Connect(string serverName) { try { //' Connect to SMS Provider SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); connection.Connect(serverName); return(connection); } catch (SmsException ex) { ConfigMgrWebService.WriteEventLog(String.Format("Unhandled expection thrown by SMS Provider: {0}", ex.Message), EventLogEntryType.Error); } catch (UnauthorizedAccessException ex) { ConfigMgrWebService.WriteEventLog(String.Format("Unathorized access exception thrown: {0}", ex.Message), EventLogEntryType.Error); } catch (Exception ex) { ConfigMgrWebService.WriteEventLog(String.Format("Unhandled expection thrown: {0}", ex.Message), EventLogEntryType.Error); } return(null); }
/// <summary> /// /// </summary> /// <returns></returns> public WqlConnectionManager Connect() { System.Diagnostics.StackFrame sf; sf = new System.Diagnostics.StackFrame(); string methodName = sf.GetMethod().Name; string userName; WqlConnectionManager connection = new WqlConnectionManager(); SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); try { _log.Write(_className, methodName, _serverCode, "Starting the function " + methodName); _log.Write(_className, methodName, _serverCode, "WQL connection in progress : " + _serverName + " | Site code : " + _serverCode); connection = new WqlConnectionManager(namedValues); if (!string.IsNullOrEmpty(_sccmUserDomain) & !string.IsNullOrEmpty(_sccmUser) & !string.IsNullOrEmpty(_sccmUserPassword)) { userName = _sccmUserDomain + "\\" + _sccmUser; _log.Write(_className, methodName, _serverCode, "Associated user : "******"WQL connection on " + _serverName + " OK"); return(connection); } catch (SmsException ex) { _log.Write(_className, methodName, "Exception", "WARNING : General connection failed"); _log.Write(_className, methodName, "Exception", ex.Message.ToString()); connection.Close(); connection.Dispose(); throw new Exception("WARNING : " + ex.Message.ToString()); } catch (UnauthorizedAccessException ex) { _log.Write(_className, methodName, "Exception", "WARNING : Authentication failed"); _log.Write(_className, methodName, "Exception", ex.Message.ToString()); connection.Close(); connection.Dispose(); throw new Exception("WARNING : " + ex.Message.ToString()); } catch (Exception ex) { _log.Write(_className, methodName, "Exception", "WARNING : DCOM Connection failed"); _log.Write(_className, methodName, "Exception", ex.Message.ToString()); connection.Close(); connection.Dispose(); throw new Exception("WARNING : " + ex.Message.ToString()); } finally { _log.Write(_className, methodName, _serverCode, "End of the function " + methodName); } }
public bool TestConnection(string serverName) { bool connectionStatus = true; try { SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); connection.Connect(serverName); } catch { connectionStatus = false; } return(connectionStatus); }
private void addCMDeviceVariable( int strResourceID, string strVariableName, string strVariableValue) { // Connect to CM Site SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); connection.Connect("CM01"); // Get the computer settings. IResultObject computerSettings = null; IResultObject computerSettingsQuery = connection.QueryProcessor.ExecuteQuery( "Select * from SMS_MachineSettings where ResourceId = '" + strResourceID + "'"); foreach (IResultObject settings in computerSettingsQuery) { settings.Get(); computerSettings = settings; } if (computerSettings == null) // It does not exist, so create it. { computerSettings = connection.CreateInstance(@"SMS_MachineSettings"); computerSettings["ResourceID"].IntegerValue = strResourceID; computerSettings["SourceSite"].StringValue = "PS1"; computerSettings.Put(); computerSettings.Get(); } // Create the computer variable. List<IResultObject> computerVariables = computerSettings.GetArrayItems("MachineVariables"); IResultObject computerVariable = connection.CreateEmbeddedObjectInstance("SMS_MachineVariable"); computerVariable["Name"].StringValue = strVariableName; computerVariable["Value"].StringValue = strVariableValue; computerVariable["IsMasked"].BooleanValue = false; // Add the computer variable to the computer settings. computerVariables.Add(computerVariable); computerSettings.SetArrayItems("MachineVariables", computerVariables); computerSettings.Put(); // Close Connection connection.Dispose(); }
private int CreateDevice(string strDeviceName, string strDeviceMacadress, string strLimtitingCollectionID) { try { if (strDeviceName == null && strDeviceMacadress == null) { throw new ArgumentNullException("DeviceName or MACAdress most be defined"); } SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); connection.Connect("CM01"); Dictionary<string, object> newDevice2 = new Dictionary<string, object>(); newDevice2.Add("NetbiosName", strDeviceName); newDevice2.Add("SMBIOSGUID", null); // For Future things newDevice2.Add("MACAddress", strDeviceMacadress); newDevice2.Add("OverwriteExistingRecord", false); // Create CM Device to site database IResultObject outParam = connection.ExecuteMethod("SMS_Site", "ImportMachineEntry", newDevice2); if (string.IsNullOrEmpty(strLimtitingCollectionID) == false) { IResultObject collection = connection.GetInstance("SMS_Collection.collectionID='" + strLimtitingCollectionID + "'"); IResultObject collectionRule = connection.CreateEmbeddedObjectInstance("SMS_CollectionRuleDirect"); collectionRule["ResourceClassName"].StringValue = "SMS_R_SYSTEM"; collectionRule["ResourceID"].IntegerValue = outParam["ResourceID"].IntegerValue; Dictionary<string, object> inParam2 = new Dictionary<string, object>(); inParam2.Add("collectionRule", collectionRule); // Add Device to specified collection. Empty will automatcally add device to All Systems collection.ExecuteMethod("AddMemberShipRule", inParam2); } return outParam["ResourceID"].IntegerValue; } catch (SmsException e) { Console.WriteLine("Failed to add the computer. " + e.Message); throw; } }
public WqlConnectionManager Connect(string serverName) { try { SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); connection.Connect(serverName); return(connection); } catch (SmsException ex) { MessageBox.Show("SmsException: " + ex.Message); } catch (UnauthorizedAccessException ex) { MessageBox.Show("Unauthorized access exception: " + ex.Message); } catch (Exception ex) { MessageBox.Show("Exception: " + ex.Message); } return(null); }
/// <summary> /// Get a connection to the Configuration Manager server /// </summary> internal static WqlConnectionManager Connect(string server) { try { SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); //connection.Connect(server, user, password); connection.Connect(server); return(connection); } catch (SmsException ex) { throw new ApplicationException("Failed to connect", ex); } catch (UnauthorizedAccessException ex) { throw new ApplicationException("Failed to authenticate", ex); } }
/// <summary> /// Get a connection to the Configuration Manager server /// </summary> internal static WqlConnectionManager Connect(string server) { try { SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); //connection.Connect(server, user, password); connection.Connect(server); return connection; } catch (SmsException ex) { throw new ApplicationException("Failed to connect", ex); } catch (UnauthorizedAccessException ex) { throw new ApplicationException("Failed to authenticate", ex); } }
public WqlConnectionManager Connect(string serverName) { try { SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); if (System.Net.Dns.GetHostName().ToUpper() == serverName.ToUpper()) { // Connect to local computer. connection.Connect(serverName); } else { // Connect to remote computer. connection.Connect(serverName); } return connection; } catch (SmsException e) { MessageBox.Show("Failed to Connect.\nPlease check the server address you are attempting.\n\n Error: " + e.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); return null; } catch (UnauthorizedAccessException e) { MessageBox.Show("Failed to authenticate.\nPlease ensure you have access.\n\n Error:" + e.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); return null; } }
public WqlConnectionManager Connect(string serverName) { try { SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); if (System.Net.Dns.GetHostName().ToUpper() == serverName.ToUpper()) { // Connect to local computer. connection.Connect(serverName); } else { // Connect to remote computer. connection.Connect(serverName); } return(connection); } catch (SmsException e) { MessageBox.Show("Failed to Connect.\nPlease check the server address you are attempting.\n\n Error: " + e.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); return(null); } catch (UnauthorizedAccessException e) { MessageBox.Show("Failed to authenticate.\nPlease ensure you have access.\n\n Error:" + e.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); return(null); } }
private int getResourceId(string strComputerName) { // Connect to CM Site SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); connection.Connect("CM01"); // Get Computer Name IResultObject ComputerResourceIDQuery = connection.QueryProcessor.ExecuteQuery( "Select ResourceID from SMS_R_System where name = '" + strComputerName + "' AND AgentName = 'Manual Machine Entry'"); foreach (IResultObject ComputerResourceInfo in ComputerResourceIDQuery) { ComputerResourceInfo.Get(); ComputerResourceID = ComputerResourceInfo["ResourceId"].IntegerValue; } connection.Dispose(); return ComputerResourceID; }
private string getCmCollection(string strCollectionName, int strResourceID, string strRuleName) { // Connect to CM Site SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary(); WqlConnectionManager connection = new WqlConnectionManager(namedValues); connection.Connect("CM01"); // Create DirectMembership rules IResultObject addDeviceToCollection = connection.CreateInstance("SMS_CollectionRuleDirect"); addDeviceToCollection["ResourceClassName"].StringValue = strCollectionName; addDeviceToCollection["Comment"].StringValue = null; addDeviceToCollection["OwnedByThisSite"].BooleanValue = true; addDeviceToCollection["LimitToCollectionID"].StringValue = null; // Add Rule to Collection Dictionary<string, object> addMembershipRuleParameters = new Dictionary<string, object>(); addMembershipRuleParameters.Add("collectionRule", newStaticRule); IResultObject staticID = newCollection return strCollectionName; }
/// <summary> /// Overloaded Constructor to establish a connection to a specified SMS-Provider (servername) /// </summary> /// <param name="serverName">Name of the SMS-Provider</param> public WQLHelper(string serverName) { _smsValues = new SmsNamedValuesDictionary(); _wqlConnectionManager = new WqlConnectionManager(_smsValues); _wqlConnectionManager.Connect(serverName); }
/// <summary> /// Create a computer system account in SCCM. /// </summary> /// <param name="computerName">The name of the computer.</param> /// <param name="macAddress">The MAC Address of the computer.</param> public static void CreateComputer(string computerName, string macAddress) { WqlConnectionManager connection = null; try { var namedValues = new SmsNamedValuesDictionary(); connection = new WqlConnectionManager(namedValues); var inParams = new Dictionary<string, object> { {"NetbiosName", computerName}, {"MACAddress", macAddress.Replace('-', ':')}, {"OverwriteExistingRecord", true} }; if (Dns.GetHostName().Equals(Properties.Resources.SCCMServerName, StringComparison.CurrentCultureIgnoreCase)) { connection.Connect(Properties.Resources.SCCMServerUPN); } else { connection.Connect(Properties.Resources.SCCMServerUPN, Properties.Resources.SCCMAccountName, Properties.Resources.sccm); } connection.ExecuteMethod("SMS_Site", "ImportMachineEntry", inParams); } catch (Exception ex) { throw new Exception("An error occurred in CreateComputer.\n" + ex.Message); } finally { connection?.Dispose(); } }
/// <summary> /// Gets a list of computer models whos name satisfies the query. /// </summary> /// <param name="queryPattern">The query to use to filter wanted computers. Wildcard character is %.</param> /// <returns>Returns a list of computer models.</returns> public static List<Computer> GetComputersByPattern(string queryPattern) { WqlConnectionManager connection = null; try { var namedValues = new SmsNamedValuesDictionary(); connection = new WqlConnectionManager(namedValues); if (Dns.GetHostName().Equals(Properties.Resources.SCCMServerName, StringComparison.CurrentCultureIgnoreCase)) { connection.Connect(Properties.Resources.SCCMServerUPN); } else { connection.Connect(Properties.Resources.SCCMServerUPN, Properties.Resources.SCCMAccountName, Properties.Resources.sccm); } var queryComputers = new List<Computer>(); var result = connection.QueryProcessor.ExecuteQuery("Select ResourceID From SMS_R_System Where Name like '" + queryPattern + "'"); foreach (IResultObject computer in result) { queryComputers.Add(GetComputer((uint)computer.Properties["ResourceID"].IntegerValue)); } return queryComputers; } catch (Exception ex) { throw new Exception("An Error occurred in GetComputersByPattern.\n" + ex.Message); } finally { connection?.Dispose(); } }
/// <summary> /// Gets the collections that a computer system belongs to in SCCM. /// </summary> /// <param name="resourceId">The Resource ID of the computer.</param> /// <returns>Returns a list of SCCM collection models.</returns> public static List<Collection> GetComputerCollections(string resourceId) { WqlConnectionManager connection = null; try { var namedValues = new SmsNamedValuesDictionary(); //smart connect, if running on localserver, then no creds needed; otherwise, use creds. connection = new WqlConnectionManager(namedValues); if (Dns.GetHostName().Equals(Properties.Resources.SCCMServerName, StringComparison.CurrentCultureIgnoreCase)) { connection.Connect(Properties.Resources.SCCMServerUPN); } else { connection.Connect(Properties.Resources.SCCMServerUPN, Properties.Resources.SCCMAccountName, Properties.Resources.sccm); } string query = $"select Distinct SMS_Collection.* from SMS_FullCollectionMembership inner join SMS_Collection on SMS_Collection.CollectionID = SMS_FullCollectionMembership.CollectionID where SMS_FullCollectionMembership.ResourceID like {resourceId}"; var collections = new List<Collection>(); foreach (IResultObject curCollection in connection.QueryProcessor.ExecuteQuery(query)) { collections.Add(new Collection() { CollectionID = curCollection.Properties["CollectionID"].StringValue, CollectionVariablesCount = curCollection.Properties["CollectionVariablesCount"].IntegerValue, Comment = curCollection.Properties["Comment"].StringValue, LimitToCollectionID = curCollection.Properties["LimitToCollectionID"].StringValue, LimitToCollectionName = curCollection.Properties["LimitToCollectionName"].StringValue, MemberClassName = curCollection.Properties["MemberClassName"].StringValue, MemberCount = curCollection.Properties["MemberCount"].StringValue, Name = curCollection.Properties["Name"].StringValue }); } return collections; } catch (Exception ex) { throw new Exception("An error occurred in GetComputerCollections.\n" + ex.Message); } finally { connection?.Dispose(); } }
/// <summary> /// Deletes computers that satisfy a given pattern in their name. /// </summary> /// <param name="queryPattern">The pattern to filter computers for deletion. Wildcard character is %.</param> /// <param name="whatif">if true, runs the logic without actually deleting the computers.</param> /// <returns>Returns the number of computers that were (or would have been -- if whatif is true) deleted.</returns> public static int DeleteComputersByPattern(string queryPattern, bool whatif = false) { WqlConnectionManager connection = null; try { var namedValues = new SmsNamedValuesDictionary(); connection = new WqlConnectionManager(namedValues); if (Dns.GetHostName().Equals(Properties.Resources.SCCMServerName, StringComparison.CurrentCultureIgnoreCase)) { connection.Connect(Properties.Resources.SCCMServerUPN); } else { connection.Connect(Properties.Resources.SCCMServerUPN, Properties.Resources.SCCMAccountName, Properties.Resources.sccm); } var iDeleted = 0; foreach (IResultObject computer in connection.QueryProcessor.ExecuteQuery("Select ResourceID From SMS_R_System Where Name like '" + queryPattern + "'")) { if (!whatif) computer.Delete(); iDeleted++; } return iDeleted; } catch (Exception ex) { throw new Exception("An error occurred in DeleteComputersByPattern.\n" + ex.Message); } finally { connection?.Dispose(); } }
/// <summary> /// Delete a computer system account from sccm. /// </summary> /// <param name="computerName">The name of the computer.</param> /// <returns>Returns true if the computer was successfully deleted. Otherwise returns false.</returns> public static void DeleteComputerByName(string computerName) { WqlConnectionManager connection = null; try { var namedValues = new SmsNamedValuesDictionary(); //Smart Wql connection. Will find out if this logic is running on the same computer that it's connecting to. //if it is, then it'll connect without credentials. otherwise, it'll use credentials. connection = new WqlConnectionManager(namedValues); if (Dns.GetHostName().Equals(Properties.Resources.SCCMServerName, StringComparison.CurrentCultureIgnoreCase)) { connection.Connect(Properties.Resources.SCCMServerUPN); } else { connection.Connect(Properties.Resources.SCCMServerUPN, Properties.Resources.SCCMAccountName, Properties.Resources.sccm); } var computer = connection.QueryProcessor.ExecuteQuery("Select ResourceID From SMS_R_System Where Name = '" + computerName + "'"); computer.Delete(); } catch (Exception ex) { throw new Exception("Exception in Global.cs -> DeleteComputerByName.\n" + ex.Message); } finally { connection?.Dispose(); } }