How to fetch all roles of systemuser? - dynamic

I am trying to pull all roles assigned to a systemuser. I think I require to use associated entities but I am not sure how should I proceed with the approach.
Here is my code snippet:
Uri organizationUri = new Uri(this.ConnectionString);
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = ConfigUserName;
credentials.UserName.Password = ConfigPassword;
Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy orgProxy = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
IOrganizationService _service = (IOrganizationService)orgProxy;
Microsoft.Xrm.Sdk.Entity account = new Microsoft.Xrm.Sdk.Entity("systemuser");
QueryExpression query = new QueryExpression
{
EntityName = account.LogicalName,
ColumnSet = new ColumnSet(true)
};
DataCollection<Microsoft.Xrm.Sdk.Entity> users = _service.RetrieveMultiple(query).Entities;
// fetch assigned roles of users

Here is my implementation to pull all roles of specific user
QueryExpression query = new QueryExpression();
query.EntityName = "role";
query.ColumnSet = new ColumnSet(true);
LinkEntity role = new LinkEntity();
role.LinkFromEntityName = "role";
role.LinkFromAttributeName = "roleid";
role.LinkToEntityName = "systemuserroles";
role.LinkToAttributeName = "roleid";
LinkEntity userRoles = new LinkEntity();
userRoles.LinkFromEntityName = "systemuserroles";
userRoles.LinkFromAttributeName = "systemuserid";
userRoles.LinkToEntityName = "systemuser";
userRoles.LinkToAttributeName = "systemuserid";
ConditionExpression conditionExpression = new ConditionExpression();
conditionExpression.AttributeName = "systemuserid";
conditionExpression.Operator = ConditionOperator.Equal;
conditionExpression.Values.Add(userId);
userRoles.LinkCriteria = new FilterExpression();
userRoles.LinkCriteria.Conditions.Add(conditionExpression);
role.LinkEntities.Add(userRoles);
query.LinkEntities.Add(role);
DataCollection<Microsoft.Xrm.Sdk.Entity> userRoles = _service.RetrieveMultiple(query).Entities;
return userRoles;

There is a sample on the MSDN for checking users security roles, should help you finish this off.
Sample: Determine Whether a User has a Role

The following Linq query using the generated early-bound CRM entities will do what you're after:
var query = from user in context.SystemUserSet
join userRoles in context.SystemUserRolesSet on user.SystemUserId equals userRoles.SystemUserId
join role in context.RoleSet on userRoles.RoleId equals role.RoleId
where user.DomainName == '<username>'
select role;
Information on generating early-bound entities can be found here: CrmSvcUtil usage

Related

how to add Customer Name

$hostedPaymentData = new HostedPaymentData();
$hostedPaymentData->customerEmail = $this->customer_email;
$hostedPaymentData->customerPhoneMobile = $this->customer_mobile_phone;
$hostedPaymentData->addressesMatch = false;
How to add customer name in hosted payment data
The following all work, the comments are the POST variables they populate when requesting the HPP.
// HPP_NAME
$hostedPaymentData->customerName = 'asdf hjkl';
// HPP_CUSTOMER_FIRSTNAME
$hostedPaymentData->customerFirstName = 'asdf';
// HPP_CUSTOMER_LASTNAME
$hostedPaymentData->customerLastName = 'hjkl';

How to manually hash a password using Asp.Net Core 2.2 / IdentityServer4 / SP.NET Core Identity

I am migrating tens of thousands of users from an old website that didn't have a password in the database to this new web application, however, when I try to import the users using the async method, it ends up taking several days to the point where I just ended up cancelling it after a few days.
Now I have resorted to just creating new users directly from _context.Users.Add and assigning their roles, which i can do without a problem.. However, I can't seem to figure out how to create a generic password (all the same password) as these users will just be given a password to view a livestream (doesn't need to be super secure), but I still need the security part for the admin accounts that handle other stuff through the client/admin side UI. If a user signs in, I will have it automatically enter the default password for them.
For some reason though, I cannot get the password hasher to work correctly, as when I sign in, it says that the password is wrong...
This is what I'm using to generate the password and create the users...
var appUser = new ApplicationUser() {
Id = GenerateId(),
AccessFailedCount = 0,
Email = user[1],
PasswordHash = "",
FullName = "Standard User",
UserName = user[1],
PhoneNumber = user[8],
FirstName = user[2],
LastName = user[3],
JoinMailingList = user[4],
Country = user[5],
City = user[6],
StateRegion = user[7]
};
_context.Users.Add(appUser);
var options = new PasswordHasherOptions();
options.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2;
var hasher = new PasswordHasher < ApplicationUser > ();
appUser.PasswordHash = hasher.HashPassword(appUser, "Default8!");
var role = _context.Roles.FirstOrDefault(r => r.Name == "user");
if (role != null) {
var userRole = new IdentityUserRole < string > ();
userRole.RoleId = role.Id;
userRole.UserId = appUser.Id;
_context.UserRoles.Add(userRole);
}
}
_context.SaveChanges();
Can anyone help me out with how I'm supposed to Hash a password to store into the database?
If a user signs in, I will have it automatically enter the default password for them.
If you are using .net core Identity, you can use UserManager.CreateAsync to create the specified user in the backing store with given password:
public virtual System.Threading.Tasks.Task<Microsoft.AspNetCore.Identity.IdentityResult> CreateAsync (TUser user, string password);
Code below is for your reference:
var user = new ApplicationUser { UserName = "wx2#hotmail.com", Email = "wx2#hotmail.com" };
var result = await _userManager.CreateAsync(user, "YourPassWord");
if (result.Succeeded)
{
}
The Identity system will help create the password hash and store in the database . If you still need to manually hash the password , see IPasswordHasher interface .
Edit:
If you want to directly insert/update via database context, you should set correct NormalizedUserName and SecurityStamp to make the system work:
ApplicationUser applicationUser = new ApplicationUser();
Guid guid = Guid.NewGuid();
applicationUser.Id = guid.ToString();
applicationUser.UserName = "wx#hotmail.com";
applicationUser.Email = "wx#hotmail.com";
applicationUser.NormalizedUserName = "wx#hotmail.com";
_context.Users.Add(applicationUser);
var hasedPassword = _passwordHasher.HashPassword(applicationUser, "YourPassword");
applicationUser.SecurityStamp = Guid.NewGuid().ToString();
applicationUser.PasswordHash = hasedPassword;
_context.SaveChanges();
As an addition, if you just want to Update the Password field of an given User:
var oldUser = await _userManager.GetUserAsync(User);
var result = await _userManager.ChangePasswordAsync(oldUser,
updateUserVm.CurrentPassword,
updateUserVm.NewPassword);
And an example to the Question "How I'm supposed to Hash a password?". You could Hash a registered Users Password with the UserManager-Referenced PasswordHasher like this:
ApplicationUser user = _userManager.Users...;
user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, newPassword);
I write my class PasswordHasher based on .net6 PasswordHasher docs latest version (V3) in this stackoverflow answer :
https://stackoverflow.com/a/72429730/9875486

Table Cloud Storage gives exception The remote server returned an error: (404) Not Found.

I am having an issue with Querying Azure Table Storage-
public List<SubCategoryModel> GetSubCategories()
{
string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connStr);
CloudTableClient client = storageAccount.CreateCloudTableClient();
CloudTable table = client.GetTableReference("SubCategories");
List<SubCategoryModel> subCategoryModels = new List<SubCategoryModel>();
TableQuery<SubCategoryEntity> subCategoriesQuery = table.CreateQuery<SubCategoryEntity>();
var query = (from subCategory in subCategoriesQuery
select subCategory).AsTableQuery();
var subCategories = query.Execute();
foreach (SubCategoryEntity entity in subCategories)
{
SubCategoryModel subCategoryModel = new SubCategoryModel();
subCategoryModel.CATEGORYID = entity.CategoryId;
subCategoryModel.DESCRIPTION = entity.Description;
subCategoryModel.SUBCATEGORY = entity.SubCategoryName;
subCategoryModel.SUBCATEGORYID = entity.SubCategoryId;
subCategoryModels.Add(subCategoryModel);
}
return subCategoryModels;
}
web.config:
<add name="ConnString" connectionString="UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://127.0.0.1"></add>
Oops My Bad...I was getting the error because my Table Name was SubCategory.
And I had SubCategories Written in code.
My Bad. Fixed it. Yes!!

how to update a column in force.com explorer

SELECT Name, ProfileId, Id, Username FROM User this is the select query to retrive data in Force.com explorer
Now I wan't to update a column how can I do this? update key word it self not working here please give the solution for this.
thanks in advance
In Salesforce you not write to update query same as in SQL.
Please use update method to update column of an object.
More information and sample please read following documents.
https://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_update.htm
I found Solution it's working fine now, If any one haveing doubts ask me for Create,Update,Get functionalities
private void UpdateProfileId(string Id)
{
SforceService sfs = new SforceService();
var login = sfs.login(ConfigurationManager.AppSettings["username"],ConfigurationManager.AppSettings["password"]);
sfs.Url = login.serverUrl;
sfs.SessionHeaderValue = new SessionHeader();
sfs.SessionHeaderValue.sessionId = login.sessionId;
var userinfo = login.userInfo;
QueryResult qr = null;
sfs.QueryOptionsValue = new salesforce.QueryOptions();
User[] UpdateUser = new User[1];
User objuser = new User();
objuser.Id = Id;
objuser.ProfileId = "00e90000001CcTnAAK";
UpdateUser[0] = objuser;
try
{
SaveResult[] saveResults = sfs.update(UpdateUser);
foreach (SaveResult saveResult in saveResults)
{
if (saveResult.success)
{
Console.WriteLine("Successfully updated Account ID: " +saveResult.id);
}
}
}
}

How to use the exported variables of another commonjs module without declare them again?

Suppose I have a module models.js:
exports.User = mongoose.model('User', UserSchema);
exports.Question = mongoose.model('Question', QuestionSchema);
exports.Answer = mongoose.model('Answer', AnswerSchema);
exports.Comment = mongoose.model('Comment', CommentSchema);
Now I want to use it in another file:
var models = require('./models');
var User = models.User;
var Question = models.Question;
var Answer = models.Answer;
var Comment = models.Comment
// then use them
var user = new User();
It is boring that I have to declare all the models I defined in models.js.
Is there any way to simplify it, that I don't need to declare the models again:
var models = require('./models');
// !!! do some magic
var user = new User();
Curious why don't you want to simply do with no magic needed - what is issue with simple ..
var models = require('./models');
var user = new models.User();