Unable to Create a systemuser in Dynamics CRM 365 online - c#

On update field of contact record I want to create a systemuser(user) in dynamics crm 365 online.but I’m getting error like "usersettings With Id = 5fe33120-607f-e811-a95c-000d3af29269 Does Not Exist"
This is the below code I'm trying to create a user
Entity getEntity = (Entity)context.InputParameters["Target"];
string str = getEntity.Attributes["new_isaeon"].ToString();
if (str != null && str == "True")
{
// http://localhost:51625/api/Users
Entity sysuser = new Entity("systemuser");
sysuser.Attributes["fullname"] = "hsk";
sysuser.Attributes["internalemailaddress"] = "projectservice_9#crmdemo.dynamics.com";
sysuser.Attributes["domainname"] = "projectservice_9#crmdemo.dynamics.com";
Guid getGuid = new Guid("700F2217-786A-E811-A95A-000D3AF2793E");
sysuser.Attributes["businessunitid"] = new EntityReference("businessunit", getGuid);
sysuser.FormattedValues["accessmode"] = "Read-Write";
Guid getuserid = service.Create(sysuser);
}
can anyone help me on this thanks.

Update: Recently we started importing users in CRM online directly using OOB CSV import (this is new for me too), it will succeed, and later on when license assigned for same user - this wont create another user record, instead it will map the Azure object GUID to the existing user record based on username/domain name/email. This is more useful when creating stub users without license or roles quickly.
In Dynamics 365 CRM online, system users record creation/enabling flow happens from O365 Admin portal end. Read more
Steps go like this:
Security group has to be created in Active directory & mapped in O365 Admin portal for any CRM Org
Users has to be added in that AD Security group
All the users from SG will be replicated as system users in CRM instance
In O365 Admin portal, on assigning CRM license (Basic/Pro) against the user - the system user record will be enabled in CRM
In CRM side, we will assign Security role to complete user on-boarding
We cannot create system user using SDK directly because of above manual steps outside CRM online. Can be created using PowerShell like answered in community.

//Use below code to create User in D365
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace PowerApps.Samples
{
public partial class SampleProgram
{
static void Main(string[] args)
{
JObject azureUser = new JObject();
JObject retrievedResult;
string queryOptions = string.Empty;
string domainName = string.Empty;
try
{
Console.WriteLine("Please enter domain name.");
domainName = Console.ReadLine();
string connectionString = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;
using (HttpClient client = SampleHelpers.GetHttpClient(
connectionString,
SampleHelpers.clientId,
SampleHelpers.redirectUrl,
"v9.1"))
{
queryOptions = "systemusers?$select=domainname&$filter=domainname eq '" + domainName + "'";
HttpResponseMessage retrieveResponse = client.GetAsync(client.BaseAddress.AbsoluteUri + queryOptions,
HttpCompletionOption.ResponseHeadersRead).Result;
if (retrieveResponse.IsSuccessStatusCode) //200
{
retrievedResult = JObject.Parse(retrieveResponse.Content.ReadAsStringAsync().Result);
string outputDomainname = (string)retrievedResult.SelectToken("value[0].domainname");
Console.WriteLine("Domain: " + outputDomainname);
if (outputDomainname == null)
{
Console.WriteLine("Adding user to Azure AD..");
HttpRequestMessage createrequest = new HttpRequestMessage(HttpMethod.Post,
client.BaseAddress + "systemusers");
Console.WriteLine("Enter first name");
azureUser.Add("firstname", Console.ReadLine());
Console.WriteLine("Enter last name");
azureUser.Add("lastname", Console.ReadLine());
Console.WriteLine("Enter internal email address");
azureUser.Add("internalemailaddress", Console.ReadLine());
azureUser.Add("isdisabled", false);
azureUser.Add("caltype", 7);
azureUser.Add("businessunitid#odata.bind", "/businessunits(8c44c8ac-f6a3-ea11-a812-000d3a0a74cb)");
createrequest.Content = new StringContent(azureUser.ToString());
createrequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
HttpResponseMessage createResponse = client.SendAsync(createrequest, HttpCompletionOption.ResponseHeadersRead).Result;
if (createResponse.IsSuccessStatusCode)
{
Console.WriteLine("Account created");
}
else
{
throw new Exception(string.Format("Failed to Post Records", createResponse.ReasonPhrase));
}
}
}
else
{
Console.WriteLine("Failed to retrieve domain: {0}",
retrieveResponse.ReasonPhrase);
throw new Exception(string.Format("Failed to retrieve domain: {0}", retrieveResponse.Content));
}
}
}
catch (Exception ex)
{
SampleHelpers.DisplayException(ex);
throw ex;
}
finally
{
Console.WriteLine("Press <Enter> to exit the program.");
Console.ReadLine();
}
}
}
}

Related

Add Site Collection Admin using SharePoint CSOM and .Net 6

I'm struggeling to understand how to use SharePoint CSOM to add a user as Site Collection Admin.
So far this code works for a Global Admin to add a user as Site Colleciton Admin, eventhough the Global Admin is not included as Site Admin.
I've tried to run the code as normal user which is only Site Collection Admin, to add another user as Site Colleciton Admin. But then I get some errors:
If I use the SharePoint Admin URL to get the Access Token, then the code crash on row #48 as 401 "Unauthorized"
If I use the Site Collection URL to get the Access Token, I get error when trying to get the acces token saying that Site is doesn't exist on the environment.
If I use the root site URL ("https://domain-admin.sharepoint.com/) to get the Access Token, then the code crash on row #51 as 401 "Unauthorized".
I'm using the PnP.PowerShell code as reference: https://github.com/pnp/powershell/blob/dev/src/Commands/Admin/SetTenantSite.cs#L547-L574
And my process is pretty much the same as here: MSAL AD token not valid with SharePoint Online CSOM
But I don't have clear if it's a issue of access token or the CSOM commands I use.
Does anyone has any idea how to move forward?
btw, I guess if I use the Global Admin account I only need to use tenant.SetSiteAdmin(siteCollection, userEmail, true);. I read somewhere that even for global admin I need EnsureUser(userEmail);, but so far the code seems working without it.
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
namespace ScriptTester
{
internal class Program
{
static async Task Main(string[] args)
{
await AddUserAdmin();
}
public static async Task AddUserAdmin()
{
string siteAdmin = "https://domain-admin.sharepoint.com/";
string siteRoot = "https://domain.sharepoint.com/";
string siteCollection = "https://domain.sharepoint.com/sites/SiteName/";
string userEmail = "_email";
string accessToken = await GetAccessToken(siteRoot);
using (var context = new Microsoft.SharePoint.Client.ClientContext(siteRoot))
{
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;
};
var tenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(context);
try
{
addLog("Try using tenant context");
tenant.SetSiteAdmin(siteCollection, userEmail, true);
tenant.Context.ExecuteQueryRetry();
}
catch (Exception ex)
{
addLog("Failed using Tenant context");
addLog(ex.Message);
using (var site = tenant.Context.Clone(siteCollection))
{
var user = site.Web.EnsureUser(userEmail);
user.Update();
user.IsSiteAdmin= true;
site.Load(user);
site.ExecuteQueryRetry();
tenant.SetSiteAdmin(siteCollection, userEmail, true);
tenant.Context.ExecuteQueryRetry();
}
}
}
}
public static async Task<string> GetAccessToken(string siteUrl)
{
string tenantId = "xxxx-xxxx-xxxx-xxxx-xxx";
string clientId = "xxxx-xxxx-xxxx-xxxx-xxx";
Uri authority = new Uri($"https://login.microsoftonline.com/{tenantId}");
string redirectUri = "http://localhost";
string defaultPermissions = siteUrl + "/.default";
string[] scopes = new string[] { defaultPermissions };
var app = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithRedirectUri(redirectUri)
.Build();
AuthenticationResult result;
result = await app.AcquireTokenInteractive(scopes)
.WithUseEmbeddedWebView(false)
.ExecuteAsync();
return result.AccessToken;
}
}
}
I will recommend you to use PnP Core component to access site collection and add admin. Please refer to the following code
string siteUrl = "https://xxx.sharepoint.com/";
string userName = "xxxx#xxx.onmicrosoft.com";
string password = "*******";
AuthenticationManager authManager = new AuthenticationManager();
try
{
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
List<UserEntity> admins = new List<UserEntity>();
UserEntity admin = new UserEntity();
admin.LoginName = "nirmal";
admins.Add(admin);
clientContext.Site.RootWeb.AddAdministrators(admins, true);
Console.WriteLine("User added as Site Collection Admin");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}

Bring up Sharepoint prompt in .NET5

We used to be able to log into SharePoint Online using the SharePointOnlineCredentials class eg here.
This class is not available in .NET5 and I don't have the necessary Azure permissions to configure the application in Azure AD as described here
I'd like a C# program bring up a prompt, so the user can log into Sharepoint manually. Once the user has done this the program will do what it needs to do. Is there some C# code that will bring up the Sharepoint online login prompt?
I've downloaded Pnp and CSOM. This code contains the following errors.
The name 'GetSecureString' does not exist in the current context
No overload for method 'GetContext' takes 3 arguments
'Program.GetContext(Uri, string, SecureString)': not all code paths return a value
The name 'context' does not exist in the current context
using System;
using System.Security;
using Microsoft.SharePoint.Client;
using System.Threading.Tasks;
using PnP.Framework;
namespace ConsoleApplication1
{
class Program
{
public static async Task Main(string[] args)
{
Uri site = new Uri("https://contoso.sharepoint.com/sites/siteA");
string user = "joe.doe#contoso.onmicrosoft.com";
SecureString password = GetSecureString($"Password for {user}");
// Note: The PnP Sites Core AuthenticationManager class also supports this
using (var authenticationManager = new AuthenticationManager())
using (var context = authenticationManager.GetContext(site, user, password))
{
context.Load(context.Web, p => p.Title);
await context.ExecuteQueryAsync();
Console.WriteLine($"Title: {context.Web.Title}");
}
}
public ClientContext GetContext(Uri web, string userPrincipalName,
SecureString userPassword)
{
context.ExecutingWebRequest += (sender, e) =>
{
// Get an access token using your preferred approach
string accessToken = MyCodeToGetAnAccessToken(new Uri($"
{web.Scheme}://{web.DnsSafeHost}"), userPrincipalName, new
System.Net.NetworkCredential(string.Empty, userPassword).Password);
// Insert the access token in the request
e.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
}
}
}

Microsoft Graph API query involving externalUserState C#

Hi I'm trying to write a simple console app which I intend to make into a batch file and get a list of external users who were invited by email have and now they have guest accounts in our Azure tenant and they have redeemed the url that was sent to them in email. When they redeem, their extenalUserState sets to "Accepted". I want to find which ones have that status.
I was told that I have to point to beta version of the API and not v.1.0 of the graph endpoint.
I have the following rudimentary code I have written looking at various examples I could find on GitHub/MS documentation for API etc.
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace CreateAzureADUser
{
class Program
{
static string TenantDomain;
static string TenantId;
static string ClientId;
static string ClientSecret;
static void Main(string[] args)
{
GetUsers();
//Console.WriteLine("------------------------------------------\n\n");
//GetGroupsAndMembers();
//CreateAzureADUserNow();
}
private static void GetUsers()
{
var graphServiceClient = CreateGraphServiceClient();
var users = graphServiceClient.Users.Request().Filter("userType eq 'Guest' and startswith(mail,'phs')")
.Select("id,mail,OnPremisesExtensionAttributes,userType,displayName,externalUserState")
.GetAsync()
.Result;
Console.WriteLine("Users found: {0}", users.Count);
Console.WriteLine();
foreach (var item in users)
{
Console.WriteLine("displayName: {3} \nuser id: {0} \nuser email: {1} \nExtensionAttribute8: {2}\n", item.Id, item.Mail, item.OnPremisesExtensionAttributes.ExtensionAttribute8, item.DisplayName);
}
}
public static GraphServiceClient CreateGraphServiceClient()
{
TenantDomain = "mycompanytenant.onmicrosoft.com";
TenantId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
ClientId = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
ClientSecret = "zzzzzzzzzzzz";
var clientCredential = new ClientCredential(ClientId, ClientSecret);
var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/mycompanytenant.onmicrosoft.com");
var authenticationResult = authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", clientCredential).Result;
var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authenticationResult.AccessToken);
return Task.FromResult(0);
});
// Use this for v.1.0 endpoint
//return new GraphServiceClient(delegateAuthProvider);
// Use this for connecting to beta endpoint
return new GraphServiceClient("https://graph.microsoft.com/beta", delegateAuthProvider);
}
}
}
When I run through the debugger, I do not see "ExternalUserState" as an attribute on the users that are returned.
How to access ExternalUserState attribute on the guest user object?
You're using the SDK so you're using Graph v1.0, not the Beta. The SDKs are all generated from v1.0 metadata so beta properties and methods simply do not exist in the models.
From time to time there is a beta build pushed out to GitHub but it is generally a few versions behind. Currently, the latest beta SDK available seems to be v1.12.0 (for reference, the current SDK is v1.15).

Get all members/users from TFS via REST API

I tried to get all members/users of TFS with the REST API and the .NET client libraries.
It works, but I get a maximum number of 50 identitys. Does anyone know, how I get all users, not only 50? (I prefer avoiding to use the old API, how it is suggested in this question)
Here is my code:
VssCredentials credentials = new VssCredentials();
VssConnection connection = new VssConnection(new Uri(url), credentials);
IdentityMruHttpClient identityMruHttpClient = connection.GetClient<IdentityMruHttpClient>();
List<IdentityRef> members = identityMruHttpClient.GetIdentityMruAsync(ProjectName).Result;
There is a REST API User Entitlements - List which can retrieve the user list from VSTS (Visual Studio Team Services), but it's only available for VSTS.
There isn't such a REST API to retrieve the user list from on-premise TFS (TFS 2017 in your scenario).
So, for now you can use the client API you mentioned above to retrieve the user list. Tested on my side, I can retrieve all the identities (more than 50 ) with below code:
You can also check the user list from userlist.txt file which under ..\..\ \bin\Debug\
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using System.Linq;
using System.IO;
namespace Getuserlist
{
class Program
{
static void Main(string[] args)
{
TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri("http://server:8080/tfs"));
IIdentityManagementService ims = tcs.GetService<IIdentityManagementService>();
TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "Project Collection Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None);
TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None);
using (StreamWriter file = new StreamWriter("userlist.txt"))
foreach (TeamFoundationIdentity id in ids)
{
if (id.Descriptor.IdentityType == "System.Security.Principal.WindowsIdentity")
{ Console.WriteLine(id.DisplayName); }
//{ Console.WriteLine(id.UniqueName); }
file.WriteLine("[{0}]", id.DisplayName);
}
var count = ids.Count(x => ids.Contains(x));
Console.WriteLine(count);
Console.ReadLine();
}
}
}

(13) The merchant login ID or password is invalid or the account is inactive

I want to implement Authorize .net payment gateway in my website using asp.net. I am a beginner in this. Can someone give me a sample code from where I can be redirected to the Authorize.net page to complete payment process.
I have created a sandbox account.
Redirection URL - https://test.authorize.net/gateway/transact.dll but I get an error
(13) The merchant login ID or password is invalid or the account is inactive.
My account is active and in test mode.
My Code:
protected void Button_pay_Click(object sender, EventArgs e)
{
string value = TextBox_amt.Text;
decimal d = decimal.Parse(value);
Run("abc", "abcq234", d);
}
public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, decimal amount)
{
Console.WriteLine("Create an Accept Payment Transaction Sample");
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = ApiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = ApiTransactionKey,
};
var opaqueData = new opaqueDataType
{
dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT",
dataValue = "119eyJjb2RlIjoiNTBfMl8wNjAwMDUyN0JEODE4RjQxOUEyRjhGQkIxMkY0MzdGQjAxQUIwRTY2NjhFNEFCN0VENzE4NTUwMjlGRUU0M0JFMENERUIwQzM2M0ExOUEwMDAzNzlGRDNFMjBCODJEMDFCQjkyNEJDIiwidG9rZW4iOiI5NDkwMjMyMTAyOTQwOTk5NDA0NjAzIiwidiI6IjEuMSJ9"
};
var billingAddress = new customerAddressType
{
firstName = "John",
lastName = "Doe",
address = "123 My St",
city = "OurTown",
zip = "98004"
};
//standard api call to retrieve response
var paymentType = new paymentType { Item = opaqueData };
// Add line Items
var lineItems = new lineItemType[2];
lineItems[0] = new lineItemType { itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(15.00) };
lineItems[1] = new lineItemType { itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(450.00) };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // charge the card
amount = amount,
payment = paymentType,
billTo = billingAddress,
lineItems = lineItems
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse.messages != null)
{
Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId);
Console.WriteLine("Response Code: " + response.transactionResponse.responseCode);
Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code);
Console.WriteLine("Description: " + response.transactionResponse.messages[0].description);
Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
}
else
{
Console.WriteLine("Failed Transaction.");
if (response.transactionResponse.errors != null)
{
Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
}
}
}
else
{
Console.WriteLine("Failed Transaction.");
if (response.transactionResponse != null && response.transactionResponse.errors != null)
{
Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
}
else
{
Console.WriteLine("Error Code: " + response.messages.message[0].code);
Console.WriteLine("Error message: " + response.messages.message[0].text);
}
}
}
else
{
Console.WriteLine("Null Response.");
}
return response;
}
Aparajita you must check with the API credentials for sandbox in Authorize.Net account
This comes up often and the reasons are always the same:
You are using your production credentials but hitting the sandbox endpoints
You are using your sandbox credentials but are hitting the production endpoints
The credentials you are using are incorrect
Verifying which endpoint you are actually hitting.
If you are testing against the production environment, verify that the URL you have in your code is the actual production URL (or if you are using a framework, the configuration is set to production).
The correct URL for production is https://api2.authorize.net/xml/v1/request.api.
The correct URL for testing is https://apitest.authorize.net/xml/v1/request.api
Verify your credentials
If you are sure that you are hitting the correct endpoint you then need to verify that you are using the correct credentials for that environment.
Make sure you are using the API login and transaction key and not the console login and password. They are not the same thing. Only the API login and transaction key will work when accessing the APIs. You can get these after logging in to the console.
Double check that the API login is correct in the console.
If the API login is correct, from within the customer console generate a new transaction key to verify that you have the correct one.
Make sure that the credentials are not accidentally entered incorrectly in your code. Make sure all of the characters are there. Also, the credentials are case sensitive. Make sure you did not capitalize or lowercase those values.
If you need to verify your login credentials work set up a MVCE that hits the endpoint you are trying to reach with your API credentials. It should be a simple script that makes a basic API call. This will make it easy to debug why you are getting this error.
Test mode is not the sandbox
It is common to confuse test mode with the sandbox environment. Test mode in production uses the production environment and production credentials. Using the sandbox credentials or URLs will not work.
I used this sample project to solve my problem. This is in TEST Mode.
https://github.com/AuthorizeNet/sdk-dotnet/tree/master/CoffeeShopWebApp

Categories

Resources