Add Computer in SCCM and import it to a specific Collection - c#

i would like to import a computer to a specific SCCM-collection.
I've found this method on the msdn:
public int AddNewComputer(
WqlConnectionManager connection,
string netBiosName,
string smBiosGuid,
string macAddress)
{
try
{
if (smBiosGuid == null && macAddress == null)
{
throw new ArgumentNullException("smBiosGuid or macAddress must be defined");
}
// Reformat macAddress to : separator.
if (string.IsNullOrEmpty(macAddress) == false)
{
macAddress = macAddress.Replace("-", ":");
}
// Create the computer.
Dictionary<string, object> inParams = new Dictionary<string, object>();
inParams.Add("NetbiosName", netBiosName);
inParams.Add("SMBIOSGUID", smBiosGuid);
inParams.Add("MACAddress", macAddress);
inParams.Add("OverwriteExistingRecord", false);
IResultObject outParams = connection.ExecuteMethod(
"SMS_Site",
"ImportMachineEntry",
inParams);
// Add to All System collection.
IResultObject collection = connection.GetInstance("SMS_Collection.collectionId='ABC0000A'");
IResultObject collectionRule = connection.CreateEmbeddedObjectInstance("SMS_CollectionRuleDirect");
collectionRule["ResourceClassName"].StringValue = "SMS_R_System";
collectionRule["ResourceID"].IntegerValue = outParams["ResourceID"].IntegerValue;
Dictionary<string, object> inParams2 = new Dictionary<string, object>();
inParams2.Add("collectionRule", collectionRule);
collection.ExecuteMethod("AddMembershipRule", inParams2);
return outParams["ResourceID"].IntegerValue;
}
catch (SmsException e)
{
Console.WriteLine("failed to add the computer" + e.Message);
throw;
}
}
Now, I try to call it with a button event:
private void button2_Click(object sender, EventArgs e)
{
AddNewComputer(PcNameBox.Text, MacAdrBox, PcNameBox.Text, CollectionDropDown.Text);
}
But I'm sorry, I don't no how to call the WQLConnectionManager on this point?! I know the object must be preset before "PcNameBox.Text". That's all :(
On another event, I call it like this:
SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
WqlConnectionManager connection = new WqlConnectionManager(namedValues);
connection.Connect(PrimarySiteServer);
But this Method is struggling me.
(It's only a hobby, pleave be indulgent)
Thanks in advance for a hint...
Chris

Google is your friend, friend:
https://msdn.microsoft.com/en-us/library/cc146404.aspx
Example below:
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())
{
// Connect to local computer.
connection.Connect(serverName);
}
else
{
// Connect to remote computer.
connection.Connect(serverName, userName, userPassword);
}
return connection;
}
catch (SmsException e)
{
Console.WriteLine("Failed to Connect. Error: " + e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("Failed to authenticate. Error:" + e.Message);
return null;
}
}

Related

Bluetooth connection getting read failed, socket might closed or timeout, read ret: -1

I am creating an app in Xamarin(Android app), that allows user to send data on his phone via bluetooth connection to another phone. When I click the button it should run the bluetooth getAllPairedDevices and then openConnection, but when it tries to connect it goes into throw exception.
This string sets data variable:
private string data = null;
This is my call button, that checks if any devices are paired:
Button btConnect = FindViewById<Button>(Resource.Id.connect);
btConnect.Click += (sender, e) =>
{
BluetoothManager manager = new BluetoothManager();
if (manager.getAllPairedDevices() != false)
{
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
while (true)
{
data = manager.getDataFromDevice();
}
});
thread.IsBackground = true;
thread.Start();
}
};
And then this is my bluetooth class:
public class BluetoothManager
{
// Unique ID for connecting
private const string UuidUniverseProfile = "00001101-0000-1000-8000-00805f9b34fb";
// Incoming bluetooth data from UART
private BluetoothDevice result;
// Input/Output stream of this communication
private BluetoothSocket mSocket;
// Convert byte[] to strings
private BufferedReader reader;
private System.IO.Stream mStream;
private InputStreamReader mReader;
public BluetoothManager()
{
reader = null;
}
private UUID getUUIDfromString()
{
return UUID.FromString(UuidUniverseProfile);
}
private void close(IDisposable connectedObject)
{
if (connectedObject == null) return;
try
{
connectedObject.Dispose();
}
catch (Exception ex)
{
throw ex;
}
connectedObject = null;
}
private void openDeviceConnection(BluetoothDevice btDevice)
{
try
{
// Getting socket from specific device
mSocket = btDevice.CreateRfcommSocketToServiceRecord(getUUIDfromString());
mSocket.Connect();
// Input stream
mStream = mSocket.InputStream;
// Output stream
//mStream.OutputStream;
mReader = new InputStreamReader(mStream);
reader = new BufferedReader(mReader);
System.Threading.Thread.Sleep(1000);
mSocket.Close();
}
catch (IOException ex)
{
close(mSocket);
close(mStream);
close(mReader);
throw ex;
}
}
public String getDataFromDevice()
{
return reader.ReadLine();
}
public bool getAllPairedDevices()
{
// Default android phone bluetooth
BluetoothAdapter btAdapter = BluetoothAdapter.DefaultAdapter;
var devices = btAdapter.BondedDevices;
if (devices != null && devices.Count > 0)
{
// All paired devices
foreach (BluetoothDevice mDevice in devices)
{
openDeviceConnection(mDevice);
}
return true;
}
else
{
return false;
}
}
}
Since I am new to Bluetooth communication I am not exactly sure where the problem is, I already checked multiple answers, and android.library but it is so complicated, so no luck.
Also a subquestion, how would you send a simple string via this setup?

After WCFService call End Further code does not execute on Client side

I want to show a message box on client side When a call is returned from service.
It is confirmed service runs and saves data into Database but call does not return.
I Google it but did not find a way
Here is my client code
private void button1_Click(object sender, EventArgs e)
{
try {
string ide = txt_id.Text;
int id = int.Parse(ide);
string city = txt_city.Text;
Service1Client client = new Service1Client();
if (client.insert(id, city))
{
client.Close();
MessageBox.Show("Your changes were saved");
}
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
Service code
public bool insert(int id,string city)
{
Ship s = new Ship
{
order_id = id,
shipcity = city,
order_date = DateTime.Now
};
ShipsDataContext od = new ShipsDataContext();
od.Ships.InsertOnSubmit(s);
try
{
od.SubmitChanges();
Console.ReadKey();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
You are waiting for console input:
Console.ReadKey();
Btw, that error handling is a problem because you are suppressing bugs (by discarding all error information) and in case of error you do nothing.

Skydrive wp7 App: GetAsync method stopped working

On my windows phone 7 Mango app I use the Microsoft.Live and Microsoft.Live.Controls references to download and upload on Skydrive. Logging in and uploading files works fine but whenever I call the "client.GetAsync("/me/skydrive/files");" on the LiveConnectClient the Callback result is empty just containing the error: "An error occurred while retrieving the resource. Try again later."
I try to retrieve the list of files with this method.
This error suddenly occured without any change on the source code of the app (I think..) which worked perfectly fine for quite a while until recently. At least I didn't change the code section for up- or downloading.
I tried out the "two-step verification" of Skydrive, still the same: can log in but not download.
Also updating the Live refercences to 5.5 didn't change anything.
Here is the code I use. The error occurs in the "getDir_Callback" in the "e" variable.
Scopes (wl.skydrive wl.skydrive_update) and clientId are specified in the SignInButton which triggers "btnSignin_SessionChanged".
private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
processing = true;
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(UploadCompleted);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadProgressChanged += new EventHandler<LiveDownloadProgressChangedEventArgs>(client_DownloadProgressChanged);
infoTextBlock.Text = "Signed in. Retrieving file IDs...";
client.GetAsync("me");
}
else
{
connected = false;
infoTextBlock.Text = "Not signed into Skydrive.";
client = null;
}
}
private void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
if (e.Error == null)
{
client.GetCompleted -= new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetCompleted += getDir_Callback;
client.GetAsync("/me/skydrive/files");
client_id = (string)e.Result["id"];
if (e.Result.ContainsKey("first_name") && e.Result.ContainsKey("last_name"))
{
if (e.Result["first_name"] != null && e.Result["last_name"] != null)
{
infoTextBlock.Text = "Hello, " +
e.Result["first_name"].ToString() + " " +
e.Result["last_name"].ToString() + "!";
}
}
else
{
infoTextBlock.Text = "Hello, signed-in user!";
}
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
processing = false;
}
public void getDir_Callback(object s, LiveOperationCompletedEventArgs e)
{
client.GetCompleted -= getDir_Callback;
//filling Dictionary with IDs of every file on SkyDrive
if (e.Result != null)
ParseDir(e);
if (!String.IsNullOrEmpty(e.Error.Message))
infoTextBlock.Text = e.Error.Message;
else
infoTextBlock.Text = "File-IDs loaded";
}
Yo shall use client.GetAsync("me/SkyDrive/files", null) in place of client.GetAsync("me");
This is my code and it works fine.
private void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
try
{
if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_GetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_UploadCompleted);
client.GetAsync("me/SkyDrive/files", null);
client.DownloadAsync("me/SkyDrive", null);
canUpload = true;
ls = e.Session;
}
else
{
if (client != null)
{
MessageBox.Show("Signed out successfully!");
client.GetCompleted -= client_GetCompleted;
client.UploadCompleted -= client_UploadCompleted;
canUpload = false;
}
else
{
canUpload = false;
}
client = null;
canUpload = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void client_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
try
{
List<System.Object> listItems = new List<object>();
if (e.Result != null)
{
listItems = e.Result["data"] as List<object>;
for (int x = 0; x < listItems.Count(); x++)
{
Dictionary<string, object> file1 = listItems[x] as Dictionary<string, object>;
string fileName = file1["name"].ToString();
if (fileName == lstmeasu[0].Title)
{
folderID = file1["id"].ToString();
folderAlredyPresent = true;
}
}
}
}
catch (Exception)
{
MessageBox.Show("An error occured in getting skydrive folders, please try again later.");
}
}
It miraculously works again without me changing any code. It seems to be resolved on the other end. I have no clue what was wrong.

C# UserPrincipal Object reference not set to an instance of an object

I am receiving the classic, Object reference not set to an instance of an object in my project when viewing the hosted website. Works when building a debug version locally.
Live
Example of code that is showing error message:
using System.DirectoryServices.AccountManagement;
protected void Page_Load(object sender, EventArgs e)
{
try
{
String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
username = username.Substring(3);
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "dc");
UserPrincipal user = UserPrincipal.FindByIdentity(pc, username);
string NTDisplayName = user.DisplayName;
//String NTUser = user.SamAccountName;
lblntuser.Text = NTDisplayName;
}
catch (Exception Ex)
{
lblntuser.Text = Ex.Message;
System.Diagnostics.Debug.Write(Ex.Message);
}
}
Try this:
protected void Page_Load(object sender, EventArgs e)
{
try
{
// you need to also take into account that someone could get to your
// page without having a Windows account.... check for NULL !
if (System.Security.Principal.WindowsIdentity == null ||
System.Security.Principal.WindowsIdentity.GetCurrent() == null)
{
return; // possibly return a message or something....
}
String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
// if the user name returned is null or empty -> abort
if(string.IsNullOrEmpty(username))
{
return;
}
username = username.Substring(3);
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "dc");
UserPrincipal user = UserPrincipal.FindByIdentity(pc, username);
// finding the user of course can also fail - check for NULL !!
if (user != null)
{
string NTDisplayName = user.DisplayName;
//String NTUser = user.SamAccountName;
lblntuser.Text = NTDisplayName;
}
}
catch (Exception Ex)
{
lblntuser.Text = Ex.Message;
System.Diagnostics.Debug.Write(Ex.Message);
}
}

How do I save the last folder selected by the user?

I have this and this only saves the last folder used when the user closes the application and re-opens it.
private void btnBrowse_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Reload();
fbFolderBrowser.SelectedPath = AppVars.LastSelectedFolder;
if (fbFolderBrowser.ShowDialog() == DialogResult.OK)
{
Properties.Settings.Default.LastSelectedFolder = fbFolderBrowser.SelectedPath.ToString();
Properties.Settings.Default.Save();
}
}
Every time the user selects a folder, I want to save that path. Then, when he clicks the browse button again, I want the default path to be his last selection.
The above is not working. It only saves the last path selected and goes back to it only if I restart the app. How would I go about saving the last path in the same app session?
You need to reload the settings:
Properties.Settings.Default.Reload();
Note that this only works when not running in Debug mode (AFAIK).
I'm gonna post my code here, because none of the answers I had seen addressed all the issues. This will save the location and re-load the settings for a file Browse dialog (file and folder browse dialogs are slightly different when getting path)... the answers above seem to be for the session only(?). Updated with new method to avoid config settings be lost with an update of clickonce app...
Code:
public class ConfigSettingsDictionary
{
public Dictionary<String, String> ConfigSettings = new Dictionary<String, String>();
}
ConfigSettingsDictionary MyConfigurationSettings = new ConfigSettingsDictionary();
private void SaveConfig()
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
foreach (var pair in MyConfigurationSettings.ConfigSettings)
{
sw.WriteLine(pair.Key + "=" + pair.Value);
}
}
}
private void LoadConfig()
{
if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
var settingdata = System.IO.File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config");
for (var i = 0; i < settingdata.Length; i++)
{
var setting = settingdata[i];
var sidx = setting.IndexOf("=");
if (sidx >= 0)
{
var skey = setting.Substring(0, sidx);
var svalue = setting.Substring(sidx + 1);
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(skey))
{
MyConfigurationSettings.ConfigSettings.Add(skey, svalue);
}
}
}
}
}
private void UpdateConfig(Dictionary<String, String> keyvaluepairs)
{
foreach (var pair in keyvaluepairs)
{
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(pair.Key))
{
MyConfigurationSettings.ConfigSettings.Add(pair.Key, pair.Value);
}
else
{
MyConfigurationSettings.ConfigSettings[pair.Key] = pair.Value;
}
}
}
then I use it like this (this saves the folder chosen in a file browse dialog and also the file chosen):
string lastused = "";
if (MyConfigurationSettings.ConfigSettings.ContainsKey("openFileDialog2_last_used"))
{
MyConfigurationSettings.ConfigSettings.TryGetValue("openFileDialog2_last_used", out lastused);
}
if (lastused != "")
{
openFileDialog2.InitialDirectory = lastused;
}
else
{
openFileDialog2.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
string filestring = "";
if (template_filename == "")
{
try
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
filestring = openFileDialog2.FileName;
String chosenPath = Path.GetDirectoryName(openFileDialog2.FileName);
Dictionary<String, String> settings_to_save = new Dictionary<String, String>();
settings_to_save.Add("openFileDialog2_last_used", chosenPath);
settings_to_save.Add("openFileDialog2_last_used_template_file", filestring);
UpdateConfig(settings_to_save);
}
else return;
}
catch (Exception ex)
{
MessageBox.Show("There was an error.", "Invalid File", MessageBoxButtons.OK);
return;
}
private void YOURFORMNAME_Load(object sender, EventArgs e)
{
// Load configuration file
LoadConfig();
}
private void YOURFORMNAME_FormClosing(object sender, FormClosingEventArgs e)
{
// Save configuration file
SaveConfig();
}

Categories

Resources