Showing posts with label Dynamics 365. Show all posts
Showing posts with label Dynamics 365. Show all posts

How to call AddUserToRecordTeam action using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Nothing special, but I'm posting here a simple JS function that calls the AddUserToRecordTeam action using web API. It took some time for me, especially in setting/fixing the parameters. Posting here reference.

    /*
    entityId: Guid of entity record
    entityLogicalName: Logical name of the entity, like lead/contact etc
    userId: Guid of the systemuser 
    templateId: team template id
    */
    function createAccessTeam(entityId,entityLogicalName,userId,templateId)
    {
        var parameters = {
            Record: { [entityLogicalName+"id"]: entityId, "@odata.type": "Microsoft.Dynamics.CRM."+entityLogicalName },
            TeamTemplate:{ "teamtemplateid": templateId, "@odata.type": "Microsoft.Dynamics.CRM.teamtemplate" }
        };
        var req = new XMLHttpRequest();
        req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/systemusers("+userId+")/Microsoft.Dynamics.CRM.AddUserToRecordTeam", true);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function() {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    var results = JSON.parse(this.response);
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send(JSON.stringify(parameters));
    }
Below is an example to call the above function:
var entityId="db4633b7-56d1-e811-a979-000d3af3e0db";
var entityLogicalName="lead",
var userId ="db4633b7-56d1-e811-a979-000d3af3e0db"
var templateId="45CED4C4-A971-EB11-A812-000D3AF39D99"
createAccessTeam(entityId,entityLogicalName,userId,templateId);

Distribute Campaign Activity via “Email via Mail Merge”

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

We can distribute our campaign activity by “Email, Email via Mail Merge, Letter, Letter via mail merge, Fax, Fax via mail merge, phone call etc.”. When our channel is “[Email, Letter, Fax] via Mail Merge” then we cannot distribute the campaign activity in dynamics CRM web client, we need to distribute it from outlook client for dynamics CRM.

Create Mail Merge templates

Installing Outlook Client

Overview of Distributing Campaign Activity via “Email via Mail Merge” in CRM Outlook client.

Create a campaign activity with channel “Email via Mail Merge”. 




















If you try to distribute this campaign activity in Dynamics CRM web client then below alert will be shown.


















So, here we need to distribute this Campaign activity in Outlook client for CRM. Go to Marketing | Marketing | Campaigns. Select your campaign record and double click to open.
















Go down in your campaign form, open the campaign activity from the “Campaign Activity” sub Grid.


















Click Distribute Campaign Activity button, a dialog will appear, select your Mail Merge template and click download.






















The mail merge template will open in Microsoft word. Here you can change the content, preview document for each recipient. Click Finish & Merge | Send Email Messages.




















Merge to E-mail dialog will be shown, put your subject line. And click ok.
























Another dialog will be shown where you have more options. Click Ok to proceed.



















When activities are tracked in CRM, below alert will be shown.













When see in Activities pane in the campaign activity, the emails will be there against each member in marketing list.


















Here I have just open one email record to just confirm the content of the email.













Campaign Response

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

In Microsoft Dynamics CRM, campaign responses are records of the communication you receive from potential customers in response to a specific marketing campaign. There are four ways to create campaign responses:

Record campaign responses manually.

You can create responses manually by first creating an activity and then converting it, or by creating a new campaign response within a campaign record

Convert an existing activity to a campaign response.

When a potential customer responds to an activity created for them as part of a marketing campaign, you can convert the corresponding activity, such as a phone call, e-mail, or fax etc., to a campaign response. 

Import responses from a file, such as a Microsoft Office Excel workbook.

By importing campaign responses, you can capture a record of the responses received as part of campaign efforts performed outside Microsoft Dynamics CRM. When you import the file, you can specify that it contains campaign responses.

Automatically generate campaign responses.

When customers respond to e-mail activities in your campaign, you can choose to have Microsoft Dynamics CRM create the corresponding campaign response records automatically.
Configure Auto Campaign Response Settings by Admin
     1. Logon to Dynamics CRM with Administrator role.
     2. Go to Settings | Administration and click on “System Settings”
     3. Click on “Marketing” tab on System Settings dialog that gets launch

















Select “Yes” for “Create campaign responses for incoming e-mail” and click OK.
Also you need to enable email tracking. For enabling email tracking, go to Email tab.

























Overview of Auto Campaign Responses
Create a Campaign and add a marketing list, this marketing list targeted contacts and having two members.















Add a Campaign Activity and select email as channel.

Click on “Distribute Campaign Activity” button below dialog will appear, add subject and Description or use template.


























After clicking the distribute button, the email will be send to each member in the marketing list.

































The below highlighted email activities are created and sent to members in the marketing list.














Here you can see the responses when customers reply to the email.





















Here the customer received the email.


















Customer replied to this email.




















The campaign response is auto created when the customer replied to us.


















When you open the Response, you can close or convert it.

Make All fields read only

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Code Snippet for making all form fields read only.

function makeFieldsReadOnly() {
    var controls = Xrm.Page.ui.controls.get();
    for (var i in controls) {
        var control = controls[i];
        if (control.getDisabled && control.setDisabled && !control.getDisabled()) {
            control.setDisabled(true);
        }
    }
}

Hide Views based on User Roles in Dynamics CRM

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

There are many scenarios where one can need to hide views for user roles. Here is an example code to hide views on Account entity for specific roles.

Let us suppose that we need to hide "Inactive Accounts" and "Customers" views for Roles "Accounts Manager" & "CSR Manager".






























Here you need to write and register a plugin and add a plugin step as pre-operation on Message "RetrieveMultiple" of "savedquery" entity  as highlighted below:

Plugin code to hide specific views for specific roles:






















public void Execute(IServiceProvider sp)
{
   IPluginExecutionContext context = (IPluginExecutionContext)sp.GetService(typeof(IPluginExecutionContext));
   IOrganizationServiceFactory factory = (IOrganizationServiceFactory)sp.GetService(typeof(IOrganizationServiceFactory));
   IOrganizationService service = factory.CreateOrganizationService(context.UserId);     
   QueryExpression query = null;
    if (context.InputParameters.Contains("Query") && context.InputParameters["Query"] is QueryExpression)
            query = (QueryExpression)context.InputParameters["Query"];           
   if (query == null) return;
   if (query.EntityName != "savedquery") return;
   int entityTypeCode = 1;//Account
   string[] Roles = { "Account Manager", "CSR Manager" };
   string[] Views = { "Inactive Accounts", "Customers" };
   try
   {
      if (query.Criteria != null && query.Criteria.Conditions != null)
       {
          var rtcCondition = query.Criteria.Conditions.SingleOrDefault(c => c.AttributeName.Equals("returnedtypecode"));
          if (rtcCondition == null) return;
        
          int returnedtypecode = (int)rtcCondition.Values[0];          
          //Return if entity code is other than Account
          if (returnedtypecode != entityTypeCode) return;
          List<Role> LoginUserRoles = getUserRoles(context.InitiatingUserId, service);
          List<Role> desiredRoles = LoginUserRoles.Where(r => Roles.Contains(r.Name)).ToList();                 
          if(LoginUserRoles.Where(r => Roles.Contains(r.Name)).ToList().Count > 0)
           {
              ConditionExpression queryCondition = new ConditionExpression("name", ConditionOperator.NotIn, Views); 
              query.Criteria.Conditions.Add(queryCondition);
            } 
         }
     }
     catch (Exception ex)
     {
        throw new InvalidPluginExecutionException(ex.Message);
     }       
}
       
/// <summary>       
/// Get Login user roles    
/// </summary>    
/// <param name="userId">Login User (Initiating User)</param>  
/// <param name="service">IOrganizationService service</param>  
/// <returns></returns> 
private List<Role> getUserRoles(Guid userId, IOrganizationService service)
{
    Role role = null;
    List<Role> roles = null;
    var query = string.Format(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                                <entity name='role'>                                 
                                    <attribute name='name' /> 
                                    <attribute name='roleid' /> 
                                    <link-entity name='systemuserroles' from='roleid' to='roleid' visible='false' intersect='true'>
                                    <link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='ab'>
                                    <filter type='and'>
                                    <condition attribute='systemuserid' operator='eq' value='{0}' />
                                    </filter>
                                   </link-entity> 
                                  </link-entity>
                                 </entity>
                                </fetch>", userId.ToString());
     EntityCollection result = service.RetrieveMultiple(new FetchExpression(query));
     if (result != null && result.Entities.Count > 0)
      {
          roles = new List<Role>();
          foreach (Entity e in result.Entities)
          {
                    role = new Role();
                    role.RoleID = e.Id;
                    if (e.Contains("name") && e["name"] != null)
                        role.Name = e["name"].ToString();
                    roles.Add(role);
            }
       }
       return roles;
}
       
public class Role 
{
   public Guid RoleID { get; set; }
   public string Name { get; set; }
}

After registering the plugin, the "Inactive Accounts" and "Customers" views are no more visible for users having role in "Accounts Manager" and "CSR Manager".





























Thanks-