Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

Posted on by 1,530

I am using Microsoft Dynamics CRM 2016 SDK. 

I am getting the following error messages.

The type or namespace name 'SecurityPrincipal' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'TargetOwnedAccount' could not be found (are you missing a using directive or an assembly reference?)

Here's my code.

using Microsoft.Crm.Sdk.Messages;

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using Microsoft.Xrm.Tooling.Connector;
using System.Configuration;
using System.Net;
using System.ServiceModel.Description;


namespace CrmSecurityRole
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri crmUrl = new Uri(ConfigurationManager.AppSettings["CrmServerUrl"]);
            string userName = ConfigurationManager.AppSettings["UserName"];
            string password = ConfigurationManager.AppSettings["Password"];

            IOrganizationService service;
            // Get the CRM connection string and connect to the CRM Organization

            ClientCredentials credentials = new ClientCredentials();
            credentials.UserName.UserName = userName;
            credentials.UserName.Password = password;

            credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            service = new OrganizationServiceProxy(crmUrl, null, credentials, null);

            // Create the SecurityPrincipal Object
            SecurityPrincipal principal = new SecurityPrincipal();

            principal.Type = SecurityPrincipalType.User;

            // PrincipalId is the Guid of the user to whom access is being granted
            principal.PrincipalId = new Guid("7B222F98-F48A-4AED-9D09-77A19CB6EE82");

            // Create the PrincipalAccess Object
            PrincipalAccess principalAccess = new PrincipalAccess();

            // Set the PrincipalAccess Object's Properties
            principalAccess.Principal = principal;

            // Gives the principal access to read
            principalAccess.AccessMask = AccessRights.ReadAccess;

            // Create the Target Object for the Request
            TargetOwnedAccount target = new TargetOwnedAccount();

            // EntityId is the Guid of the account access is being granted to
            target.EntityId = new Guid("6A92D3AE-A9C9-4E44-9FA6-F3D5643753C1");

            // Create the Request Object
            GrantAccessRequest grant = new GrantAccessRequest();

            // Set the Request Object's properties
            grant.PrincipalAccess = principalAccess;
            grant.Target = target;

            // Execute the Request
            GrantAccessResponse granted = (GrantAccessResponse)service.Execute(grant);

        }
    }
}

*This post is locked for comments

  • rthompson Profile Picture
    rthompson 1,530 on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Thanks Akhil,

    I found it.

    C:\...\SDK\SampleCode\CS\BusinessDataModel\UsersAndRoles

  • Verified answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Hi Thompson,

    Role and User are established as N:N relationships. So you will have to use the Associate method of the Organization Service class. In your case as a security role is already established, you will first have to disassociate the existing security role. Please remember that, in order to do both associate and disassociate you'd need the roleid(GUID of role) and the user guid as well.

    *An important caveat whilst retrieving the roleid - Roles are repeated across Business units, so you should be using the business unit in your filter expression whilst retrieving the roleid if your organization has more than one business unit.

    If you have downloaded the SDK for CRM, go through the samples folder and you should see sample class for Roles (Don't remember the exact name of the class - It's probably called Role.cs/SecurityRole.cs/Users.cs)

     

    PLEASE MARK THIS RESPONSE AS SUGGESTED IF YOU ARE SATISFIED WITH MY ANSWER.

  • rthompson Profile Picture
    rthompson 1,530 on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Okay.

    That's why I can not find it.

    Can you lead me to the best practice on how to change the role of a user using a plugin.

    I want to  change the user permission when a case is being saved.  I would like to make the change on the post operation.

    I have not been able to find a good example on how to do this.

    Thanks

  • Suggested answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Hi Thompson,

    I doubt that you are referring to obsolete code.

    Security Principal and TargetOwnedAccount were part of CRM 4.0. I highly doubt if they are still valid anymore.

  • rthompson Profile Picture
    rthompson 1,530 on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Okay.

    Now that I understand early and late binding.  I am still trying to understand why the 2 classes do not appear in the namespace Microsoft.Crm.Sdk.Messages.

    The type or namespace name 'SecurityPrincipal' could not be found (are you missing a using directive or an assembly reference?)

    The type or namespace name 'TargetOwnedAccount' could not be found (are you missing a using directive or an assembly reference?)

    SDK 2016

    0525.sdk.JPG

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Well, each has its own pros and cons. Performance wise late bound is better because CRM converts Early bound to late bound internally as the CLR only understands late bound.

    Please refer to this article. (https://msdn.microsoft.com/en-us/library/gg509027.aspx#Performance)  

    Use early-bound types

    Use the Entity class when your code must work on entities and attributes that aren’t known at the time the code is written. In addition, if your custom code works with thousands of entity records, use of the Entity class results in slightly better performance than the early-bound entity types. However, this flexibility has a disadvantage because you cannot verify entity and attribute names at compile time. If your entities are already defined at code time and slight performance degradation is acceptable, you should use the early-bound types that you can generate by using the CrmSvcUtil tool. More information: Use the early bound entity classes in code

  • Suggested answer
    Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Hi,

    There is no limitations for using LateBound or EarlyBound entities to develop any application / plugin for Dynamics 365.

    I prefer LateBound entity structure, because it's not depended anything and if you add a new attribute to Dynamics 365 entity, you can easily add this to your code block.

    If you use EarlyBound entity structure, you have to re-generate earlybound class to get your new attribute inside your code.

    in C#;

    LateBound

    - works like Dictionary (entity["firstname"] = "Emre"; )

    - probably (if you're new bee) you can do mistakes when typing entity / attribute names or attribute types

    EarlyBound

    - it's a C# class and contains all attributes as Property (for exp. Account.Name)

    - you can not do any mistake when typing entity / attribute names or attribute types

    - few developers telling EarlyBound improves runtime performance, but I don't have any idea and test results.

    - it requirement additional space in your code. if you do mistake to get all entities / atributes inside your EarlyBound class, probably it'll approx. 10 MB class.

  • rthompson Profile Picture
    rthompson 1,530 on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Before I go down this road.  Any suggestion on what is the right way to go?

  • Suggested answer
    Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Hi,

    Probably your code (or sample code that you copied) using EarlyBound class structure. If you want to use EarlyBound class structure in your code/solution, you need to create this EarlyBound class. You can use XrmToolBox 's Early Bound Generator plugin (https://www.xrmtoolbox.com/plugins/DLaB.Xrm.EarlyBoundGenerator/) or directly use CrmSvcUtil.exe inside console, details are here https://msdn.microsoft.com/en-us/library/gg327844.aspx 

    You can also find "latebound" sample code https://github.com/emregulcan/xrmlibrary.2016/blob/dc1ffeaa5239c5b7da6b06fa79d534c4848a5409/XrmLibrary.EntityHelpers/Common/CommonHelper.cs#L330-L338 

  • rthompson Profile Picture
    rthompson 1,530 on at
    RE: Using console program to change user role can't find SecurityPrincipal or TargetOwnedAccount

    Still getting the same error messages.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans