Friday, May 5, 2017

User Device Affinity (UDA) in C#

With the demise of Silver Light, you might want to keep it just so you can do UDA for the users.  Well here is some code you can use to create a webpage, much like I did to go around that issue.


Here is some straight code:

First you need to search for the user you want to add:
Create a Text box named UserSelected
Now search for the user based on the name, this will also contain their userID so it helps with the searches.


string strQuery = "Select * from SMS_R_User where Name like '%" + UserSelected.Trim() + "%'";
IResultObject UsersFound = SCCMconnection.QueryProcessor.ExecuteQuery(strQuery);


Now you can move through the list and add them to the radio button if you like.


foreach (IResultObject UserFound in UsersFound)
{
dt.Rows.Add(CreateRow(UserFound["UniqueUserName"].StringValue.Trim(), UserFound["Name"].StringValue.Trim(), dt));
dv = new DataView(dt);
}
UniqueUserName-  This is what SCCM needs in order to add the user domain\userid
UserFound["Name"] - this is used for our searches because it looks like this (userID\domain  Username ResourceID)
Next you can create a search for the machine,

SMS_CM_RES_COLL_XY000017 - This is your collection of machines you wish to search, this could be your AllWorkstations collection


Select ResourceID,Name from SMS_CM_RES_COLL_XY000017 where name like '%" + FindComputerTxtBox.Text.Trim() + "%'";


Once you find it add it to a drop down box. 
Now with both the user and the Machine we can set the UDA.  Be sure your Security on the Service Account performing the action has access to set User Device Affinity.

Dictionary<string, object> addUDAParameters = new Dictionary<string, object>();
addUDAParameters.Add("MachineResourceId", ResourceIDVariable);
addUDAParameters.Add("UserAccountName", "domain\userid";
addUDAParameters.Add("SourceId", "2");  //Administrative change
addUDAParameters.Add("TypeId", "1");
IResultObject UDA = SCCMconnection.ExecuteMethod("SMS_UserMachineRelationship", "CreateRelationship", addMembershipRuleParameters);




Depending on what you use the Application Catalog for, you can use this code on a website and remove SilverLight.