public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String DisplayName = request.Inputs["Display Name"].AsString(); String Description = request.Inputs["Description"].AsString(); String InformativeURL = request.Inputs["Informative URL"].AsString(); String LocaleID = request.Inputs["LocaleID"].AsString(); String UpdatesList = request.Inputs["Updates List (CSV)"].AsString(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CM2012Interop.connectSCCMServer(SCCMServer, userName, password); using (connection) { try { IResultObject col = CM2012Interop.createSCCMAuthorizationList(connection, DisplayName, Description, InformativeURL, LocaleID, UpdatesList); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } } catch (Exception ex) { response.LogErrorMessage(ex.Message); } response.Publish("Number of Packages", ObjCount); } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String objID = request.Inputs["CI_ID"].AsString(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CMInterop.connectSCCMServer(SCCMServer, userName, password); using (connection) { String[] propertyNameChoices = CMInterop.getSCCMObjectPropertyNames(connection, "SMS_AuthorizationList"); foreach (String propertyName in propertyNameChoices) { if ((request.Inputs.Contains(propertyName + " : Property Type")) && (request.Inputs.Contains(propertyName + " : Property Value"))) { CMInterop.modifySCCMAuthorizationList(connection, objID, request.Inputs[(propertyName + " : Property Type")].AsString(), propertyName, request.Inputs[(propertyName + " : Property Value")].AsString()); } } IResultObject col = null; col = CMInterop.getSCCMAuthorizationList(connection, "CI_ID LIKE '" + objID + "'"); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Authorization Lists", ObjCount); } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String filter = request.Inputs["Filter Query"].AsString(); String objClass = request.Inputs["Class"].AsString(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CMInterop.connectSCCMServer(SCCMServer, userName, password); using (connection) { IResultObject col = CMInterop.getSCCMObject(connection, objClass, filter); CMInterop.removeSCCMObject(connection, filter, objClass); foreach (IResultObject obj in col) { ObjCount++; } response.Publish("Number of Objects", ObjCount); } }
/// <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 void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String objID = request.Inputs["Package ID"].AsString(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CM2012Interop.connectSCCMServer(SCCMServer, userName, password); try { String[] propertyNameChoices = CM2012Interop.getSCCMObjectPropertyNames(connection, "SMS_SoftwareUpdatesPackage"); foreach (String propertyName in propertyNameChoices) { if ((request.Inputs.Contains(propertyName + " : Property Type")) && (request.Inputs.Contains(propertyName + " : Property Value"))) { CM2012Interop.modifySCCMSoftwareUpdatesPackage(connection, objID, request.Inputs[(propertyName + " : Property Type")].AsString(), propertyName, request.Inputs[(propertyName + " : Property Value")].AsString()); } } IResultObject col = CM2012Interop.getSCCMSoftwareUpdatesPackage(connection, "PackageID LIKE '" + objID + "'"); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Packages", ObjCount); } finally { connection.Close(); connection.Dispose(); } }
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; } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String objID = request.Inputs["Advertisement ID"].AsString(); DateTime startTime = request.Inputs["Start Time"].AsDateTime(); int dayDuration = request.Inputs["Day Duration"].AsInt32(); int hourDuration = request.Inputs["Hour Duration"].AsInt32(); int minuteDuration = request.Inputs["Minute Duration"].AsInt32(); bool isGMT = request.Inputs["Is GMT"].AsBoolean(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CMInterop.connectSCCMServer(SCCMServer, userName, password); using (connection) { CMInterop.modifySCCMAdvertisementAddAssignmentScheduleNonReccuring(connection, objID, isGMT, dayDuration, hourDuration, minuteDuration, startTime); IResultObject col = CMInterop.getSCCMAdvertisement(connection, "AdvertisementID LIKE '" + objID + "'"); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Advertisements", ObjCount); } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String filter = request.Inputs["Filter Query"].AsString(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CMInterop.connectSCCMServer(SCCMServer, userName, password); using (connection) { IResultObject col = CMInterop.getSCCMObject(connection, "SMS_R_System", filter); List <system> systemCollection = new List <system>(); foreach (IResultObject obj in col) { ObjCount++; systemCollection.Add(new system(obj)); } if (systemCollection != null) { response.WithFiltering().PublishRange(getObjects(systemCollection)); } response.Publish("Number of Systems", ObjCount); CMInterop.removeSCCMObject(connection, filter, "SMS_R_System"); } }
public void Design(IActivityDesigner designer) { WqlConnectionManager connection = CM2012Interop.connectSCCMServer(settings.SCCMSERVER, settings.UserName, settings.Password); designer.AddInput("Advertisement ID").WithDefaultValue("ABC00000"); designer.AddInput("BATTERY_POWER").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("RUN_FROM_CD").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("DOWNLOAD_FROM_CD").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("RUN_FROM_LOCAL_DISPPOINT").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("DOWNLOAD_FROM_LOCAL_DISPPOINT").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("DONT_RUN_NO_LOCAL_DISPPOINT").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("DOWNLOAD_FROM_REMOTE_DISPPOINT").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("RUN_FROM_REMOTE_DISPPOINT").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("DOWNLOAD_ON_DEMAND_FROM_LOCAL_DP").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("DOWNLOAD_ON_DEMAND_FROM_REMOTE_DP").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("BALLOON_REMINDERS_REQUIRED").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("RERUN_ALWAYS").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("RERUN_NEVER").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("RERUN_IF_FAILED").WithDefaultValue(false).WithBooleanBrowser(); designer.AddInput("RERUN_IF_SUCCEEDED").WithDefaultValue(false).WithBooleanBrowser(); designer.AddCorellatedData(typeof(advertisement)); designer.AddOutput("Number of Advertisements"); }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String pkgID = request.Inputs["Existing Package ID"].AsString(); String prgName = request.Inputs["Existing Program Name"].AsString(); String prgOSMaxVersion = request.Inputs["New Max Version"].AsString(); String prgOSMinVersion = request.Inputs["New Min Version"].AsString(); String prgOSName = request.Inputs["New Name"].AsString(); String prgOSPlatform = request.Inputs["New Platform"].AsString(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CM2012Interop.connectSCCMServer(SCCMServer, userName, password); using (connection) { CM2012Interop.modifySCCMProgramSupportedPlatforms(connection, pkgID, prgName, prgOSMaxVersion, prgOSMinVersion, prgOSName, prgOSPlatform); IResultObject col = CM2012Interop.getSCCMProgram(connection, "PackageID LIKE '" + pkgID + "' AND ProgramName LIKE '" + prgName + "'"); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Programs", ObjCount); } }
/// <summary> /// IResultObject disposal version 2. Manual call of Dipose. /// </summary> /// <param name="wqlConnection"></param> private void IResultObjectExecuteQueryDisposalV2(WqlConnectionManager wqlConnection) { try { // As an example, get all SMS_Package objects. // ExecuteQuery returns IResultObject which is a WqlQueryResultsObject using (IResultObject queryResults = wqlConnection.QueryProcessor.ExecuteQuery("SELECT * FROM SMS_Package")) { // WqlQueryResultsObject.GetEnumerator() is implemented as: // yield return (object) new WqlResultObject(this.ConnectionManager, this.ConnectionManager.NamedValueDictionary, managementObject); foreach (IResultObject item in queryResults) { string packageName = item["Name"].StringValue; Console.WriteLine("Package: " + packageName); // Must call Dispose on each item enumerated item.Dispose(); } } } catch (SmsException) { // Error handling. } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String pkgName = request.Inputs["New Package Name"].AsString(); String pkgDescription = request.Inputs["New Package Description"].AsString(); int pkgSourceFlag = (int)request.Inputs["New Package Source Flag"].AsUInt32(); String pkgSourcePath = request.Inputs["New Package Source Path"].AsString(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CM2012Interop.connectSCCMServer(SCCMServer, userName, password); using (connection) { IResultObject col = CM2012Interop.createSCCMPackage(connection, pkgName, pkgDescription, pkgSourceFlag, pkgSourcePath); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Packages", ObjCount); } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String objID = request.Inputs["Collection ID"].AsString(); String ruleName = request.Inputs["Rule Name"].AsString(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CM2012Interop.connectSCCMServer(SCCMServer, userName, password); using (connection) { CM2012Interop.removeSCCMCollectionMember(connection, objID, ruleName); IResultObject col = null; col = CM2012Interop.getSCCMCollection(connection, "CollectionID LIKE '" + objID + "'"); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Collections", ObjCount); } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String pkgID = request.Inputs["Existing Package ID"].AsString(); String prgName = request.Inputs["New Program Name"].AsString(); String prgComment = request.Inputs["New Program Comment"].AsString(); String prgCommandLine = request.Inputs["New Program Command Line"].AsString(); int prgMaxRunTime = (int)request.Inputs["New Program Max Runtime"].AsUInt32(); String prgWorkingDirectory = request.Inputs["New Program Working Directory"].AsString(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CMInterop.connectSCCMServer(SCCMServer, userName, password); using (connection) { IResultObject col = CMInterop.createSCCMProgram(connection, pkgID, prgName, prgComment, prgCommandLine, prgMaxRunTime, prgWorkingDirectory); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Programs", ObjCount); } }
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> public Boolean Disconnect(WqlConnectionManager wqlConnection) { System.Diagnostics.StackFrame sf; sf = new System.Diagnostics.StackFrame(); string methodName = sf.GetMethod().Name; try { _log.Write(_className, methodName, _serverCode, "Starting the function " + methodName); _log.Write(_className, methodName, _serverCode, "Closing WQL connection " + _serverName); wqlConnection.Close(); wqlConnection.Dispose(); _log.Write(_className, methodName, _serverCode, "WQL Connection Opening " + _serverName + " OK"); return(true); } catch (Exception ex) { _log.Write(_className, methodName, "Exception", "WARNING : Error closing WQL connection"); _log.Write(_className, methodName, "Exception", ex.Message.ToString()); throw new Exception("WARNING : " + ex.Message.ToString()); } finally { _log.Write(_className, methodName, _serverCode, "End of the function " + methodName); } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String objID = request.Inputs["Collection ID"].AsString(); String contentIDList = request.Inputs["Content ID List (CSV)"].AsString(); bool refreshDPs = request.Inputs["Refresh DPs"].AsBoolean(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CM2012Interop.connectSCCMServer(SCCMServer, userName, password); using (connection) { CM2012Interop.modifySCCMSoftwareUpdatesPackageRemoveCIs(connection, objID, contentIDList, refreshDPs); IResultObject col = null; col = CM2012Interop.getSCCMSoftwareUpdatesPackage(connection, "PackageID LIKE '" + objID + "'"); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Collections", ObjCount); } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String objID = request.Inputs["Collection ID"].AsString(); String ruleName = request.Inputs["Rule Name"].AsString(); String wqlQuery = request.Inputs["WQL Query"].AsString(); String limitCollectionID = String.Empty; if (request.Inputs.Contains("Collection ID to Limit Query To")) { limitCollectionID = request.Inputs["Collection ID to Limit Query To"].AsString(); } //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CMInterop.connectSCCMServer(SCCMServer, userName, password); using (connection) { CMInterop.addSCCMCollectionRule(connection, objID, ruleName, wqlQuery, limitCollectionID); IResultObject col = null; col = CMInterop.getSCCMCollection(connection, "CollectionID LIKE '" + objID + "'"); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Collections", ObjCount); } }
public void RemoveCMApplicationCategory(string appName, string categoryName) { SmsProvider smsProvider = new SmsProvider(); WqlConnectionManager connectionManager = smsProvider.Connect(SiteServer); ObservableCollection <CMApplicationCategory> applicationCategories = GetCMApplicationCategories(false); string appQuery = string.Format("SELECT * FROM SMS_ApplicationLatest WHERE (IsHidden = 0) AND (LocalizedDisplayName = '{0}')", appName); IResultObject appQueryResult = connectionManager.QueryProcessor.ExecuteQuery(appQuery); if (appQueryResult != null) { foreach (IResultObject app in appQueryResult) { ArrayList appCategories = new ArrayList(app["CategoryInstance_UniqueIDs"].StringArrayValue); CMApplicationCategory applicationCategory = applicationCategories.Where(c => c.LocalizedCategoryInstanceName == categoryName).First(); if (appCategories.Contains(applicationCategory.CategoryInstance_UniqueID)) { appCategories.Remove(applicationCategory.CategoryInstance_UniqueID); app["CategoryInstance_UniqueIDs"].StringArrayValue = (string[])appCategories.ToArray(typeof(string)); app.Put(); } else { MessageBox.Show(appName + " doesn't contain " + categoryName); } } } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; int referenceID = (int)request.Inputs["Reference Computer Resource ID"].AsUInt32(); int destinationID = (int)request.Inputs["Destination Computer Resource ID"].AsUInt32(); //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CMInterop.connectSCCMServer(SCCMServer, userName, password); using (connection) { CMInterop.associateComputer(connection, referenceID, destinationID); IResultObject col = null; col = CMInterop.getSCCMComputer(connection, Convert.ToString(destinationID), "", ""); if (col != null) { response.WithFiltering().PublishRange(getObjects(col)); } response.Publish("Number of Systems", ObjCount); } }
private IEnumerable <DistributionPoint> getObjects(IResultObject objList, WqlConnectionManager connection) { foreach (IResultObject obj in objList) { ObjCount++; yield return(new DistributionPoint(obj)); } }
/// <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); } }
/// <summary> /// Dispose an IResultObject returned from another method. /// </summary> /// <param name="wqlConnection"></param> private void IResultObjectDisposalOfReturnValue(WqlConnectionManager wqlConnection) { // Call method that returns an IResultObject - we are responsible for calling Dispose. using (IResultObject item = IResultObjectReturnSmsPackage(wqlConnection)) { string packageName = item["Name"].StringValue; Console.WriteLine("Package: " + packageName); } }
public void Execute(IActivityRequest request, IActivityResponse response) { SCCMServer = settings.SCCMSERVER; userName = settings.UserName; password = settings.Password; String varType = request.Inputs["Variable Name"].AsString(); MachineName = request.Inputs["Machine Name"].AsString(); String resourceID = String.Empty; if (request.Inputs.Contains("Resource ID")) { resourceID = request.Inputs["Resource ID"].AsString(); } //Setup WQL Connection and WMI Management Scope WqlConnectionManager connection = CMInterop.connectSCCMServer(SCCMServer, userName, password); using (connection) { //Get Computer Object IResultObject computerObj = null; IResultObject col = null; if (resourceID.Equals(String.Empty)) { col = CMInterop.getSCCMComputer(connection, "", MachineName, ""); } else { col = CMInterop.getSCCMComputer(connection, resourceID, "", ""); } foreach (IResultObject c in col) { computerObj = c; if (computerObj != null) { //Get Variables from Comoputer Object List <IResultObject> variableCollection = CMInterop.getSCCMComputerVariables(connection, computerObj["ResourceID"].IntegerValue.ToString()); if (variableCollection != null) { response.WithFiltering().PublishRange(getComputerVariables(variableCollection)); response.Publish("Number of Machine Variables", variableCollection.Count); } response.Publish("Number of Machine Variables", 0); } else { response.LogErrorMessage("Could Not Find Computer " + MachineName); } } } }
/// <summary> /// Update the Application object /// </summary> internal static void Save(Application app, string server) { WqlConnectionManager connection = CMConnection.Connect(server); ApplicationFactory applicationFactory = new ApplicationFactory(); AppManWrapper applicationWrapper = AppManWrapper.Create(connection, applicationFactory) as AppManWrapper; applicationWrapper.InnerAppManObject = app; applicationFactory.PrepareResultObject(applicationWrapper); applicationWrapper.InnerResultObject.Put(); }
public void Design(IActivityDesigner designer) { WqlConnectionManager connection = CM2012Interop.connectSCCMServer(settings.SCCMSERVER, settings.UserName, settings.Password); designer.AddInput("Netbios Name").WithDefaultValue("computerName"); designer.AddInput("SM Bios GUID").NotRequired(); designer.AddInput("MAC Address").NotRequired(); designer.AddCorellatedData(typeof(system)); designer.AddOutput("Number of Systems"); }
private IEnumerable <collection> getObjects(IResultObject objList, WqlConnectionManager connection) { foreach (IResultObject obj in objList) { IResultObject tempObjCol = CMInterop.getSCCMCollection(connection, "CollectionID LIKE '" + obj["parentCollectionID"].StringValue + "'"); foreach (IResultObject o in tempObjCol) { ObjCount++; yield return(new collection(o)); } } }
/// <summary> /// The main entry point for the wrapper. Uncomment the snippets you wish to run here. /// </summary> public void Run() { var computer = ""; var userName = ""; var password = ""; Console.WriteLine("Site server you want to connect to (press Return for this computer): "); computer = Console.ReadLine(); Console.WriteLine(); if (string.IsNullOrEmpty(computer) || computer == ".") { computer = Dns.GetHostName(); userName = ""; password = ""; } else { Console.WriteLine("Please enter the user name (press Return for current user): "); userName = Console.ReadLine(); if (!string.IsNullOrEmpty(userName)) { Console.WriteLine("Please enter your password: "); password = ReturnPassword(); } } // Make connection to provider. WqlConnectionManager wqlConnection = Connect(computer, userName, password); if (wqlConnection == null) { return; } // // Call snippets - uncomment required snippets. // // // Fundamentals // //IResultObjectExecuteQueryDisposalV1(wqlConnection); //IResultObjectExecuteQueryDisposalV2(wqlConnection); //IResultObjectDisposalOfReturnValue(wqlConnection); //LazyPropertyFromQuery(wqlConnection); // Disconnect wqlConnection.Close(); wqlConnection.Dispose(); }
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 Main() { InitializeComponent(); scope = Connect("\\"+server); active_ACF2 = new List<ACF2>(); rejections = new List<Rejections>(); _backgroundWorker = new BackgroundWorker(); _backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork); _backgroundWorker.WorkerReportsProgress = true; _backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted); _backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged); _backgroundWorker2 = new BackgroundWorker(); _backgroundWorker2.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork); _backgroundWorker2.WorkerReportsProgress = true; _backgroundWorker2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted); _backgroundWorker2.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged); }
/// <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; } }
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; }
public void QueryACF2s(WqlConnectionManager connection,String[] ACF2s,int subThread) { try { int i = 1; foreach (String id in ACF2s) { int counter = 0; List<NodeItem> nodes = new List<NodeItem>(); IResultObject query = scope.QueryProcessor.ExecuteQuery (@"Select distinct SMS_R_SYSTEM.NetbiosName, SMS_R_SYSTEM.OperatingSystemNameandVersion, SMS_R_SYSTEM.CreationDate, SMS_SITE.SiteName, SMS_R_SYSTEM.Active, SMS_R_SYSTEM.LastLogonUserName, SMS_R_SYSTEM.employeeId, SMS_R_SYSTEM.AgentTime, SMS_R_SYSTEM.AgentName, SMS_G_SYSTEM_COMPUTER_SYSTEM.Model, SMS_G_SYSTEM_SYSTEM_CONSOLE_USER.NumberOfConsoleLogons, SMS_G_SYSTEM_SYSTEM_CONSOLE_USER.TotalUserConsoleMinutes, SMS_G_SYSTEM_SYSTEM_CONSOLE_USAGE.TotalConsoleTime, SMS_G_SYSTEM_SYSTEM_CONSOLE_USER.LastConsoleUse from SMS_G_SYSTEM_SYSTEM_CONSOLE_USER INNER JOIN SMS_R_SYSTEM on SMS_R_SYSTEM.ResourceID = SMS_G_SYSTEM_SYSTEM_CONSOLE_USER.ResourceID LEFT JOIN SMS_G_SYSTEM_SYSTEM_CONSOLE_USAGE on SMS_G_SYSTEM_SYSTEM_CONSOLE_USAGE.ResourceID = SMS_G_SYSTEM_SYSTEM_CONSOLE_USER.ResourceID LEFT JOIN SMS_G_SYSTEM_SYSTEM_ENCLOSURE on SMS_G_SYSTEM_SYSTEM_ENCLOSURE.ResourceID = SMS_R_SYSTEM.ResourceID INNER JOIN SMS_G_SYSTEM_COMPUTER_SYSTEM on SMS_G_SYSTEM_COMPUTER_SYSTEM.ResourceID = SMS_R_SYSTEM.ResourceID left join SMS_Site on SMS_Site.SiteCode=SMS_R_SYSTEM.SMSAssignedSites Where SMS_R_SYSTEM.employeeId = '" + id + @"' Or SMS_R_SYSTEM.LastLogonUserName = '******' AND SMS_G_SYSTEM_SYSTEM_CONSOLE_USAGE.TotalConsoleTime != 0"); foreach (IResultObject o in query) { foreach (IResultObject thing in o) { Dictionary<String, String> results = new Dictionary<string, string>(); List<IResultObject> obj = thing.GenericsArray; foreach (IResultObject obj2 in obj) { foreach (KeyValuePair<string, string> kvpPair in obj2.PropertyList) { //Console.WriteLine(kvpPair.Value + " " + kvpPair.Key); results.Add(kvpPair.Key, kvpPair.Value); } } NodeItem item = populateItemWin7(results); if (item != null) { nodes.Add(item); counter++; } //Console.WriteLine(); } } /*The above query will not produce any US results * Try and find all results for that user */ if (counter == 0) { query = scope.QueryProcessor.ExecuteQuery("Select * From SMS_R_SYSTEM left join SMS_Site on SMS_Site.SiteCode=SMS_R_SYSTEM.SMSAssignedSites where NetbiosName = '" + id + "' OR LastLogonUserName = '******'"); foreach (IResultObject o in query) { foreach (IResultObject thing in o) { Dictionary<String, String> results = new Dictionary<string, string>(); List<IResultObject> obj = thing.GenericsArray; foreach (IResultObject obj2 in obj) { foreach (KeyValuePair<string, string> kvpPair in obj2.PropertyList) { results.Add(kvpPair.Key, kvpPair.Value); } } nodes.Add(populateItemWinXP(results)); counter++; //Console.WriteLine(); } } } Sorter sorter = new Sorter(); nodes = sorter.removeDuplicateNodes(nodes); //PERFORM SELECTION LOGIC AND INSERT INTO active ACF2 //Console.WriteLine("Making Selections"); if (counter > 0) { String log = ""; //Way to return two variables to keep track of selection logging //Key will contain the list of Nodes //Value will contain the log KeyValuePair<List<NodeItem>,String> selections = sorter.selectBest(nodes,id,safety, log); nodes = sorter.sortByDescendingDate(nodes); lock (active_ACF2) { active_ACF2.Add(new ACF2 { ID = id, Nodes = nodes, SelectedNodes = selections.Key, log = selections.Value }); } } else { //Add node to rejection list lock (rejections) { rejections.Add(new Rejections { ID = id }); } } //Console.WriteLine("Selections have been made"); counter++; lock (sem) { completed++; String[] objects = new String[3]; objects[0] = completed.ToString(); objects[1] = id; objects[2] = totalACF2s.ToString(); if (subThread == 1) _backgroundWorker.ReportProgress((100 * completed) / totalACF2s, objects); else _backgroundWorker2.ReportProgress((100 * completed) / totalACF2s, objects); } i++; } } catch (SmsException ex) { Console.WriteLine("Failed to query List: " + ex.Message); //throw; } catch (Exception ex) { Console.WriteLine("Error occured: " + ex.Message); //throw; } }
private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { Settings form = new Settings(server,safety); DialogResult result = form.ShowDialog(); if (result == DialogResult.OK) { String value = form.get_Safety(); if (value == "") safety = 0; else safety = Convert.ToInt32(value); if(scope != null) scope.Close(); server = form.get_Server(); scope = Connect("\\"+server); exportRejection_List = form.export_Rejection(); exportNode_List = form.export_NodeList(); exportSelection_Log = form.export_Logging(); form.Dispose(); } else { form.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(); } }
/// <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> /// 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(); } }