Esempio semplice di elenco, creazione, modifica ed eliminazione
Nell'esempio seguente viene illustrato un set di metodi molto semplici che usano la SMS_Package
classe per illustrare le operazioni List, Create, Modify ed Delete tramite il provider SMS. Si tratta di un'analisi della struttura di un programma di Configuration Manager di base. Esistono frammenti di metodo più utili in altre aree dell'SDK che eseguono attività specifiche.
Importante
Per semplificare l'esempio di codice, alcuni metodi vengono commentati, in quanto necessitano di informazioni aggiuntive (un identificatore di pacchetto esistente). Utilizzare il ListPackages
metodo per ottenere l'identificatore del pacchetto da utilizzare con i ModifyPackage
metodi e DeletePackage
.
Per elencare i pacchetti
Configurare una connessione al provider SMS.
Eseguire una query che popola una variabile con una raccolta di istanze di
SMS_Package
classe.Enumerare la raccolta ed elencare i pacchetti restituiti dalla query.
Per creare un pacchetto
Configurare una connessione al provider SMS.
Creare il nuovo oggetto pacchetto usando la
SMS_Package
classe .Popolare le nuove proprietà del pacchetto.
Salvare il pacchetto.
Per modificare un pacchetto
Configurare una connessione al provider SMS.
Caricare l'oggetto pacchetto esistente usando la
SMS_Package
classe .Modificare una proprietà del pacchetto.
Salvare il pacchetto.
Per eliminare un pacchetto
Configurare una connessione al provider SMS.
Caricare l'oggetto pacchetto esistente usando la
SMS_Package
classe .Eliminare il pacchetto usando il metodo delete.
Esempio
Il metodo di esempio seguente mostra set di metodi di base che usano SMS_Package
la classe per illustrare le operazioni List, Create, Modify ed Delete usando il provider SMS.
Per informazioni sulla chiamata del codice di esempio, vedere Chiamata di frammenti di codice Configuration Manager.
Nota
L'esempio seguente incorpora il codice chiamante nel codice. La maggior parte degli altri esempi in SDK mostra semplicemente un metodo con parametri.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Added the below Configuration Manager DLL references to support basic SMS Provider operations:
// C:\Program Files (x86)\Microsoft Endpoint Manager\AdminConsole\bin\Microsoft.ConfigurationManagement.ManagementProvider.dll
// C:\Program Files (x86)\Microsoft Endpoint Manager\AdminConsole\bin\AdminUI.WqlQueryEngine.dll
// Added the below Configuration Manager namespaces to support basic SMS Provider operations:
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;
//
// A set of very basic methods using the SMS_Package class to demonstrate List, Create, Modify and Delete operations using the SMS Provider.
//
// Note: To simplify the code example, some methods are commented out, as they need additional information (an existing package identifier).
// Use the ListPackages method to obtain the package identifier for use with the ModifyPackage and DeletePackage methods.
//
namespace BasicApp
{
class Program
{
static void Main(string[] args)
{
// Setup Objects
SnippetClass BasicCMAppSnippets = new SnippetClass();
// Setup a connection to the SMS Provider.
// Passing in <server name>, <domain\\account>, <password>.
WqlConnectionManager WMIConnection = BasicCMAppSnippets.Connect("CMLABSERVER", "CMLABSERVER\\cmlabuser", "password");
// List all packages (instances of SMS_Package).
BasicCMAppSnippets.ListPackages(WMIConnection);
// Create a new package.
// Note: This is not a useful package (too few properties), just a demonstration of creating a Configuration Manager object.
BasicCMAppSnippets.CreatePackage(WMIConnection, "New Package", "This is the new package.");
// Modifies a specific package (instance of SMS_Package).
// A valid PackageID needs to be passed to the ModifyPackage method - replace "ABC00000".
//BasicCMAppSnippets.ModifyPackage(WMIConnection, "ABC00000");
// Deletes a specific package (instance of SMS_Package).
// A valid PackageID needs to be passed to the DeletePackage method - replace "ABC00000".
//BasicCMAppSnippets.DeletePackage(WMIConnection, "ABC00000");
// Delay to keep the console output visible.
Console.ReadLine();
}
}
class SnippetClass
{
public WqlConnectionManager Connect(string serverName, string userName, string userPassword)
{
try
{
SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
WqlConnectionManager connection = new WqlConnectionManager(namedValues);
if (System.Net.Dns.GetHostName().ToUpper() == serverName.ToUpper())
{
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);
throw;
}
}
public void ListPackages(WqlConnectionManager connection)
{
try
{
// This query selects all packages (instances of SMS_Package).
string query = "SELECT * FROM SMS_Package";
// Run query, which populates 'listOfPackages' with a collection of package objects.
IResultObject listOfPackages = connection.QueryProcessor.ExecuteQuery(query);
// Output header for list of distribution points.
Console.WriteLine(" ");
Console.WriteLine("List of packages: ");
Console.WriteLine("-------------------");
// Enumerate through the collection of objects returned by the query.
foreach (IResultObject package in listOfPackages)
{
// Output the package name for each package object.
Console.WriteLine("Package ID: {0} Package Name: {1}", package["PackageID"].StringValue, package["Name"].StringValue);
}
}
catch (SmsException ex)
{
Console.WriteLine("Failed to list packages. Error: " + ex.Message);
throw;
}
}
public void CreatePackage(WqlConnectionManager connection, string newPackageName, string newPackageDescription)
{
try
{
// Create new package object.
IResultObject newPackage = connection.CreateInstance("SMS_Package");
// Populate new package properties.
newPackage["Name"].StringValue = newPackageName;
newPackage["Description"].StringValue = newPackageDescription;
// Save the new package and the new package properties.
newPackage.Put();
// The key value 'PackageID' is created on the put, so getting the package object to output the unique 'PackageID' ('Name' is not guaranteed to be unique).
newPackage.Get();
// Output new package name.
Console.WriteLine("Created Package ID: {0} Package Name: {1}", newPackage["PackageID"].StringValue, newPackage["Name"].StringValue);
}
catch (SmsException ex)
{
Console.WriteLine("Failed to create package. Error: " + ex.Message);
throw;
}
}
public void ModifyPackage(WqlConnectionManager connection, string existingPackageID)
{
try
{
// Get the specific package instance to modify (PackageID is a key value).
IResultObject packageToModify = connection.GetInstance(@"SMS_Package.PackageID='" + existingPackageID + "'");
// Modify a package properties (in this case description).
packageToModify["Description"].StringValue = "This package has been modified. " + packageToModify["Description"].StringValue;
// Save the new package and the new package properties.
packageToModify.Put();
}
catch (SmsException ex)
{
Console.WriteLine("Failed to delete package. Error: " + ex.Message);
throw;
}
}
public void DeletePackage(WqlConnectionManager connection, string existingPackageID)
{
try
{
// Get the specific package instance to delete (PackageID is a key value).
IResultObject packageToDelete = connection.GetInstance(@"SMS_Package.PackageID='" + existingPackageID + "'");
// Output package ID and name being deleted.
Console.WriteLine("Deleting Package ID: {0} Package Name: {1}", packageToDelete["PackageID"].StringValue, packageToDelete["Name"].StringValue);
// Delete the package.
packageToDelete.Delete();
}
catch (SmsException ex)
{
Console.WriteLine("Failed to delete package. Error: " + ex.Message);
throw;
}
}
}
}
Il metodo di esempio include i parametri seguenti:
Parametro | Tipo | Descrizione |
---|---|---|
connection |
-Gestito: WqlConnectionManager |
Connessione valida al provider SMS. |
newPackageName |
-Gestito: String |
Nome del nuovo pacchetto. |
newPackageDescription |
-Gestito: String |
Descrizione del nuovo pacchetto. |
existingPackageID |
-Gestito: String |
Identificatore del pacchetto esistente. Si tratta di un valore chiave per la SMS_Package classe e viene usato per restituire un'istanza specifica della SMS_Package classe . Il metodo ListPackages nell'esempio precedente restituisce i nomi e gli ID pacchetto delle istanze del pacchetto correnti. |
Compilazione del codice
L'esempio C# richiede:
Spazi dei nomi
Sistema
Microsoft.ConfigurationManagement.ManagementProvider
Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine
Assembly
adminui.wqlqueryengine
microsoft.configurationmanagement.managementprovider
mscorlib
Programmazione efficiente
Per altre informazioni sulla gestione degli errori, vedere Informazioni sugli errori di Configuration Manager.
Vedere anche
Panoramica della distribuzione softwareSMS_Package classe WMI del server