问题
I have a scenario in CRM where I created an MVC application that uploads a excel file, does some validation on the file, once the records are validated,it creates the new records in CRM, I need to know how can I handles the current logged in user in CRM so that that specific user performs the create and is then owner the records. I am currently using a CRM User which I created in AD, but I need this to be the logged in user who runs the process/app. Currently that CRM User owns all records upon upload, regardless which user uploaded. Please see my code below.
public ActionResult ImportDataToCRM(CRM_Embrace_IntegrationEntities1 db)
{
CrmConnection conn = new CrmConnection("CRM");
IOrganizationService service = new OrganizationService(conn);
WhoAmIRequest whoReq = new WhoAmIRequest();
WhoAmIResponse whoResp = (WhoAmIResponse)service.Execute(whoReq);
Guid userid = whoResp.UserId;
var cleanClaimsFromDB = db.CleanSupplierClaims.Select(x => x).ToList();
foreach (var claim in cleanClaimsFromDB)
{
new_supplierclaimsupdate CRMSupplierClaimsData = new new_supplierclaimsupdate()
{
new_Action = claim.Action.Trim(),
new_InvoiceNumebr = claim.Line_Number.Trim(),
new_TotalClaim = Convert.ToDecimal(claim.Total_Claim).ToString(),
new_Currency = claim.Currency.Trim(),
new_Supplier = claim.ClaimReference.Trim(),
OwnerId = new EntityReference(SystemUser.EntityLogicalName, userid),
};
service.Create(CRMSupplierClaimsData);
}
}
ConnectionString is:
<add name="CRM" connectionString="Url=https://serername/OrgName; Username=domain\CRM_User; Password=mypassword" />
I need this to be generic and not upload as CRM User but as the actual user who is running the application, please assist.
回答1:
Use the OrganizationServiceProxy CallerId property to set the user to pass on as the caller.
var service = new OrganizationService(conn);
var whoReq = new WhoAmIRequest();
var whoResp = (WhoAmIResponse)service.Execute(whoReq);
var cleanClaimsFromDB = db.CleanSupplierClaims.Select(x => x).ToList();
var service = organizationService as OrganizationService;
if (service != null)
{
var serviceProxy = service.InnerService as OrganizationServiceProxy;
if (serviceProxy == null) throw new InvalidCastException("invalid cast");
serviceProxy.CallerId = whoResp.UserId; //The user GUID you want to pass as the caller
}
var cleanClaimsFromDB = db.CleanSupplierClaims.Select(x => x).ToList();
foreach (var claim in cleanClaimsFromDB)
{
var CRMSupplierClaimsData = new new_supplierclaimsupdate()
{
new_Action = claim.Action.Trim(),
new_InvoiceNumebr = claim.Line_Number.Trim(),
new_TotalClaim = Convert.ToDecimal(claim.Total_Claim).ToString(),
new_Currency = claim.Currency.Trim(),
new_Supplier = claim.ClaimReference.Trim()
};
service.Create(CRMSupplierClaimsData);
}
来源:https://stackoverflow.com/questions/37570224/crm-dynamics-2013-how-to-pass-current-logged-as-the-record-owner