Azure AD Graph API ApproleAssignment does not allow zero GUID - azure-ad-graph-api

I am getting an error when trying to add AppRoleAssignment for a user:
{"odata.error":{"code":"Request_BadRequest","message":{"lang":"en","value":"One or more properties are invalid."},"date":"2017-10-21T14:49:42","requestId":"3aacf13e-5620-40da-8fd0-fb2d4130f171","values":null}}
When i use an actual ApproleId, everything works fine. However, when i set
AppRoleAssignment.Id = new Guid(); i get the above error;
This does not make sense, because the documentation says that this is allowed
by setting zero GUID and the same has been stressed in other posts on SO.
What am i missing here?
Full code:
AppRoleAssignment appRoleAssignment = new AppRoleAssignment()
{
Id = new Guid(),
ResourceId = Guid.Parse(servicePrincipal.ObjectId),
PrincipalId = Guid.Parse(user.ObjectId),
PrincipalType = "User"
};
user.AppRoleAssignments.Add(appRoleAssignment);
await user.UpdateAsync();

Based on my experience, there are two scenarios we may get this issue.
First, if there is customize roles in the service principal you want to assign the default role.
Second, if we have already assigned the default role to that person before.
Please check whether you are in one of these two scenarios and let me know if you still have the problem about this issue.

Related

Moodle - update_moduleinfo - invalid course module id

I'm currently building a new moodle plugin. I'm using add_moduleinfo and update_moduleinfo. To add a new attandance atictivity in a course and update it later on.
Sadly I'm facing the issue that update_moduleinfo always throws an "invalid course module id" error. I already checked the cm entry in my database to ensure im using the right module instance.
I dont really know what to do.
$cm = get_coursemodule_from_instance($moduleName, $activityID, $course->id);
$moduleinfo = update_moduleinfo($cm, $moduleinfo, $course); <-- Error
Thats how I try to update the entry.
I also found that post. Didn't help anything.
Moodle - Invalid course module ID
I found the issue myself:
$moduleinfo->introeditor['format'] = FORMAT_HTML;
$moduleinfo->introeditor['text'] = "INTRO TEXT";
$moduleinfo->coursemodule = $cm->id;
list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
In order to use this function the above mentioned properties need to exist in order to perform a update.

Realm: creating a new Role and adding a User to it fails

I'm trying to wrap my head around object-level access control permissions with Realm Cloud (using query-based sync). What I want, is that one object (say, a Task in my example below), can be viewed by a set of multiple users.
So, I create the task, create a role for it with the name "task:\(task.taskId)", add the current user to that role, create a new permission for that role, and finally add it to the task.
let task = Task()
task.name = "A task!"
try? realm.write {
realm.add(task)
let taskRole = realm.create(PermissionRole.self, value: ["task:\(task.taskId)"])
let permissionUser = realm.object(ofType: PermissionUser.self, forPrimaryKey: SyncUser.current!.identity!)!
taskRole.users.append(permissionUser)
let permission = task.permissions.findOrCreate(forRole: taskRole)
permission.canRead = true
permission.canUpdate = true
permission.canDelete = true
}
The idea being that at a later point another user can be added to the same role, with having access to the Task, and nobody else.
Almost everything is working, except that the user is not actually being added to the role. When I look in Realm Studio, I can see that the task is created, the role is created, the permission is created and it's added to the task, but the role has no users at all.
What am I doing wrong? And are there better examples or docs? I find the official docs to be very sparse.
I'm wondering about how you have permissions set up. Are you sure you have permission to read that PermissionUser, and modify that PermissionRole?

Why is my update in my plugin on my custom entity not occurring?

I'm writing an auto number plugin for MS Dynamics CRM 2015. It works on the creation of an opportunity, when a new number needs to be generated. The current number is stored in another entity, which is retrieved at the time of creating the opportunity and then adds 1. The auto number entity is then updated with the new number (except it isn't as this isn't working at the moment).
At the moment the number is retrieved and 1 is added to it and is used in the opportunity correctly. However, as the update to the auto number entity does not occur when another opportunity is created it gets the same number as the previous one.
Here's my plugin code so far:
protected void ExecuteGenerateOpportunityAutoNumber(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName == OPPORTUNITY_ENTITY_NAME)
{
if (!entity.Attributes.Contains(OPPORTUNITY_REF_ID))
{
try
{
string newId = RetrieveAndUpdateLastId(service);
entity.Attributes.Add(OPPORTUNITY_REF_ID, newId);
}
catch (FaultException ex)
{
throw new InvalidPluginExecutionException("GenerateOpportunityAutoNumber plugin error: ", ex);
//tracingService.Trace("GenerateOpportunityAutoNumber plugin error: {0}", ex.Message);
}
}
}
}
}
The RetrieveAndUpdateLastId method code is below:
private string RetrieveAndUpdateLastId(IOrganizationService service)
{
lock (lastIdentifierLock)
{
string result = null;
ColumnSet cols = new ColumnSet();
cols.AddColumns(LAST_REF_LAST_VALUE, LAST_REF_PRIMARY_KEY);
QueryExpression query = new QueryExpression();
query.ColumnSet = cols;
query.EntityName = LAST_REF_ENTITY_NAME;
EntityCollection ec = service.RetrieveMultiple(query);
if (ec.Entities.Count >= 1)
{
foreach (Entity identifier in ec.Entities)
{
if (identifier.Attributes.Contains(LAST_REF_LAST_VALUE))
{
int? lastValue = identifier[LAST_REF_LAST_VALUE] as int?;
if (lastValue != null)
{
string newValue = (lastValue.Value + 1).ToString().PadLeft(7, '0');
result = String.Format("SN{0}", newValue); //This is clearly happening as I'm getting the next number back.
identifier[LAST_REF_LAST_VALUE] = lastValue.Value + 1;
//Tried this also:
//identifier.Attributes.Remove(LAST_REF_LAST_VALUE);
//identifier.Attributes.Add(LAST_REF_LAST_VALUE, lastValue.Value + 1);
service.Update(identifier); //This doesn't seem to be happening.
break;
}
}
}
}
return result;
}
}
No error is thrown but the update of the auto number just isn't happening. I've checked the user I'm running this as has the required update privileges on the auto number entity as well. Any ideas?
UPDATE
After debugging I found that it was throwing an error that the Principal user is missing the prvWrite privilege. This would explain why the update isn't happening, but now raises another issue. I've setup the plugin to run as a specific user (one with the correct privileges), but the Guid of the 'Principal user' in the error was of the calling user. Why would it run as the calling user when I've set it up to use a specific user?
UPDATE 2
I think I may have found the issue but wonder if anyone else can confirm / shed some more light on this. It seems that according to this, the issue may lie with the user not being in a specific AD group, specifically
User account (A) needs the privilege prvActOnBehalfOfAnotherUser,
which is included in the Delegate role.
Alternately, for Active Directory directory service deployments only,
user account (A) under which the impersonation code is to run can be
added to the PrivUserGroup group in Active Directory. This group is
created by Microsoft Dynamics CRM during installation and setup. User
account (A) does not have to be associated with a licensed Microsoft
Dynamics CRM user. However, the user who is being impersonated (B)
must be a licensed Microsoft Dynamics CRM user.
For my purposes I think the user I'm trying to run as needs to be in PrivUserGroup in AD (which it's not), otherwise it defaults to the calling user.
UPDATE 3
I've been able to identify 2 fundamental problems. The first is as explained above, in that the context always runs as the calling user. The 2nd is that when either giving the calling user system admin privileges OR creating the IOrganizationService with a null parameter it still doesn't update. HOWEVER, and this seems very odd, these 2 scenarios DO work when profiling the plugin. Why would this be?
UPDATE 4
It seems I may have resolved the issue, though I'm not certain (hence why I've not written an answer as yet). As per the documentation we've added the user to be impersonated into the PrivUserGroup. The plugin now works. However, I don't understand why this is needed. Also, is this best practice in this scenario or have I done something that should never be done?
On a related note I also unregistered the plugin before deploying it this time, so I'm now wondering if this solved this issue. To confirm I've now removed the user from the PrivUserGroup in AD, but this takes some time (not sure exactly how long) to filter through apparently. If it still works then it looks like this actually resolved it. Do you normally need to unregister a plugin before re-deploying it to make sure it works?
UPDATE 5
Ok, so this if my final update. I'm not marking this as the answer as I'm not 100% certain, but it appears that removing the assembly using the plugin registration tool may have done the trick. From everything I've read you shouldn't need to unregister a plugin to redeploy, so my perhaps my assembly was corrupt somehow and by removing it and creating it again using the new assembly solve the issue. Unfortunately I don't have the original assembly to test with.
I would suggest to debug your plugin. Following article contains a video that describes how to debug plugins using Plugin Debugger and Plugin Regitration Tool - http://blogs.msdn.com/b/devkeydet/archive/2015/02/17/debug-crm-online-plugins.aspx
Updated How to have 2 instances of IOrganizationService for user context and system:
Open Plugin.cs file.
Locate following code:
internal IOrganizationService OrganizationService
{
get;
private set;
}
Add following code after:
internal IOrganizationService SystemOrganizationService
{
get;
private set;
}
Find following code:
// Use the factory to generate the Organization Service.
this.OrganizationService = factory.CreateOrganizationService(this.PluginExecutionContext.UserId);
Add following code after:
this.SystemOrganizationService = factory.CreateOrganizationService(null);
Use this instance of IOrganizationService in the place where you need higher level of privileges.

Trying to change owner of account on CRM 4.0 using a plugin

I am creating a plugin for Microsoft Dynamics CRM 4 that will change the owner of the account entity according to the value of another lookup field. Now I have managed to get the GUID of the user that will be acting as the 'Owner' of the account. So far so good.
The problem arises when I try to change the owner. I am trying to use AssignRequest but it is not working. When I try to execute the request I get a SoapException on the C# Debugger, and the webservice outputs a dialog stating:
"The requested record was not found or you do not have sufficient permissions to view it"
Below is the code I am using:
TargetOwnedAccount target = new TargetOwnedAccount();
SecurityPrincipal assignee = new SecurityPrincipal();
assignee.Type = SecurityPrincipalType.User;
assignee.PrincipalId = context.InitiatingUserId;
target.EntityId = ownerGuid; //this is the GUID I am retrieving from the other lookup field
AssignRequest assign = new AssignRequest();
assign.Assignee = assignee;
assign.Target = target;
AssignResponse res = (AssignResponse)crmService.Execute(assign); //this is where i get the exception
I hope I haven't missed anything.
Any help would be much appreciated :)
Thanks
Ok i managed to solve this finally. It had been staring directly at my face :P
I was entering the wrong ID's at the wrong place. I needed to set the 'assignee.PrincipalId' to the 'ownerGuid' and then set the 'target.EntityId' to the current account id. The new code is as follows:
TargetOwnedAccount target = new TargetOwnedAccount();
SecurityPrincipal assignee = new SecurityPrincipal();
assignee.Type = SecurityPrincipalType.User;
assignee.PrincipalId = ownerGuid; //this is the GUID I am retrieving from the other lookup field
target.EntityId = ((Key)entity.Properties["accountid"]).Value;
AssignRequest assign = new AssignRequest();
assign.Assignee = assignee;
assign.Target = target;
AssignResponse res = (AssignResponse)crmService.Execute(assign);
Cant believe i spent 8 hours yesterday looking at it and then today I realised immediately :P

retrieving the default outlook email account using Redemption

just trying to work my way around using Redemption; I've got the following code to retrieve the RDOAccounts (Email accounts) from the default Profile:
Profiles profiles = (Profiles)Activator.CreateInstance(Type.GetTypeFromProgID("ProfMan.Profiles"));
Profile defaultProfile = profiles.DefaultProfile;
//open a RDOSession for this profile
RDOSession session = RedemptionLoader.new_RDOSession();
session.Logon(defaultProfile.Name);
RDOAccounts accounts = session.Accounts;
Where I'm stuck is trying to determine which of the RDOAccount objects is set as the default email account - there doesn't seem to be any property on the object that I can use to see whether it's the default or not.
Anyone done this before?
Use RDOSession.Accounts collection, in particular RDOAccounts.GetOrder method: http://www.dimastr.com/redemption/RDOAccounts.htm
I think this works - but if anyone's got a more elegant solution I'd love to hear it!
RDOAccount defaultAccount = session.GetDefaultFolder(rdoDefaultFolders.olFolderInbox).Store.StoreAccount;
Use RDOSession.Accounts collection, in particular RDOAccounts.GetOrder method.