Menu Close

Blog

Slide 1

Microsoft Business Applications Blogposts, YouTube Videos and Podcasts

Helping Businesses with Technology

Slide 2

Microsoft Business Applications Blogposts, YouTube Videos and Podcasts

Helping Businesses with Technology

Slide 3

Microsoft Business Applications Blogposts, YouTube Videos and Podcasts

Helping Businesses with Technology

previous arrow
next arrow

BULK UPDATE OF ACCOUNT RECORDS WITH PRIMARY CONTACT EMAIL VALUE

My customer had a requirement of bulk update  of account records with email “string” , based on the primary contact email value.

Scenario : Account Records don’t have a email value from primary contact’s record.

So I have chosen to write a plugin to bulk update.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
namespace MallaSolutions
{
    public class UpdateAccounts : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context =
        (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Get a reference to the Organization service.
            IOrganizationServiceFactory factory =
        (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);
            Entity entity;
            if (context.InputParameters != null)
            {
                entity = (Entity)context.InputParameters[“Target”];
                string fetchXML = @”<fetch distinct=’false’ mapping=’logical’ output-format=’xml-platform’ version=’1.0′>
                                  <entity name=’account’>
                                    <attribute name=’accountid’ />
                                    <attribute name=’emailaddress1′ />
                                    <order descending=’false’ attribute=’emailaddress1′ />
                                    <filter type=’and’>
                                      <condition attribute=’primarycontactid’ operator=’not-null’ />
                                    </filter>
                                    <link-entity name=’contact’ to=’primarycontactid’ from=’contactid’ alias=’PrimaryContact’ link-type=’outer’ visible=’false’>
                                      <attribute name=’emailaddress1′ alias=’contactEmailAddress’ />
                                    </link-entity>
                                  </entity>
                                </fetch>”;
                EntityCollection entityCollection = service.RetrieveMultiple(new FetchExpression(fetchXML));
                for (int i = 0; i < entityCollection.Entities.Count; i++)
                {
                    AliasedValue contactemailaddress = entityCollection.Entities[i].GetAttributeValue<AliasedValue>(“contactEmailAddress”);
                    if (contactemailaddress != null)
                    {
                        Entity account = new Entity(“account”);
                        account.Attributes[“accountid”] = entityCollection.Entities[i].Attributes[“accountid”];
                        account.Attributes[“emailaddress1”] = entityCollection.Entities[i].GetAttributeValue<AliasedValue>(“contactEmailAddress”).Value.ToString();
                        service.Update(account);
                    }
                }
            }
            else
            {
                return;
            }
        }
    }
}

====================================================================
Plugin Registration tool steps:


Message: Update
Primary Entity : Account
Filtering attributes : address1_city
event: post-opeartion
execution mode: Asynchronus
deployment: Server

I have registered asynchronous mode as the system will have performance impact if it is selected as Synchronous mode and it will time out after 2 min, as in my case , I am using dynamics 365 online.

We can increase time limit of plugin if it is dynamics 365 onpremise.

I hope this helps:-)
Cheers guys….

Share this:

CUSTOM WORKFLOW ACTIVITY SAMPLE CODE FOR DYNAMICS 365

Here is a simple scenario

1) Create two fileds
a) DOB,
b) AGE

2) Calculate AGE based on DOB selected..

So we need to write a simple custom workflow as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using System.Activities;
using Microsoft.Xrm.Sdk.Workflow;


namespace CustomWorkflowActivity
{
    public class CalculateAge : CodeActivity
    {
        [Input(“Date of Birth”)]
        public InArgument<DateTime> DOB { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            ITracingService tracingService = (ITracingService)context.GetExtension<ITracingService>();
            IWorkflowContext workflowContext = (IWorkflowContext)context.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)context.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

            DateTime dtDOB = DOB.Get(context);
            int CalculateAge = Convert.ToInt32(DateTime.Now.Subtract(dtDOB).TotalDays)/365;
            Age.Set(context, CalculateAge);
        }
        [Output(“Age”)]
        public OutArgument<Int32> Age { get; set; }
    }
}

======================================================================
After creating Custom workflow then use the custom workflow activity in the processes section to calculate the Age of the contact..
I hope this helps…
Happy CRMing:-)
↜Ҝ
Share this:

DYNAMICS 365 INTEGRATION WITH WEB APPLICATION (ASP.NET) AND RETRIEVING DATA AND SHOWING IN GRID

Follow the steps as below:

First Create an ASP.NET WEBSITE from Visual Studio
Goto File> New > Website > Add a webform > 
then it will create an aspx page file then add a “GridView” to the aspx page. Inside the ASPX.CS class add the below code 

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.ServiceModel.Description;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;


public partial class Accounts : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        IOrganizationService service = GetCRMService();
        QueryExpression query = new QueryExpression(“account”);
        query.ColumnSet.AllColumns = true;
        query.Criteria.AddCondition(“name”, ConditionOperator.NotEqual, “ksllls”);
        EntityCollection collection = service.RetrieveMultiple(query);

        DataTable dt = new DataTable();
        dt.Columns.Add(“name”);
        dt.Columns.Add(“accountnumber”);
        foreach(Entity entity in collection.Entities)
        {
            DataRow dr = dt.NewRow();
            dr[“name”] = entity.Attributes[“name”].ToString();
            if(entity.Contains(“accountnumber”))
            { 
            dr[“accountnumber”] = entity.Attributes[“accountnumber”].ToString();
            }
            dt.Rows.Add(dr);
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }


    public IOrganizationService GetCRMService()
    {
        string UserName = “mam@santechnology.onmicrosoft.com”;
        string Password = “devisri123”;
        ClientCredentials Credentials = new ClientCredentials();
        IOrganizationService Service;
        Credentials.UserName.UserName = UserName;
        Credentials.UserName.Password = Password;

        Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
        //This URI need to be updated to match the servername and organisation for the environment

        string CRMServer = ConfigurationManager.AppSettings[“crmserverurl”].ToString();
        Uri OrganizationUri = new Uri(CRMServer);
        Uri HomeRealmUri = null;

        // OrgaizationServiceProxy  ServiceProxy

        using(OrganizationServiceProxy ServiceProxy = new OrganizationServiceProxy(OrganizationUri,HomeRealmUri,Credentials,null))
        {
             Service = (IOrganizationService)ServiceProxy;
        }
        return Service;
    }
}

=======================================================================
 Screen shot of the Visual studio website application..

Account.aspx code:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Accounts.aspx.cs” Inherits=”Accounts” %>

<!DOCTYPE html>

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
    <title></title>
</head>

<body>
    <form id=”form1″ runat=”server”>
    <div>
    <asp:gridview ID=”GridView1″ runat=”server”></asp:gridview>
    </div>
    </form>
</body>
</html>

=======================================================================
WEB.CONFIG CODE



<?xml version=”1.0″?>

<!–
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  –>

<configuration>
<appSettings>
  <add key =”crmserverurl” value=”https://santechnology.api.crm11.dynamics.com/XRMServices/2011/Organization.svc”/>
</appSettings>
    <system.web>
      <compilation debug=”true” targetFramework=”4.5″ />
      <httpRuntime targetFramework=”4.5″ />
    </system.web>


</configuration>

=======================================================================

The Output will be as shown on the screen shot:


=======================================================================

Here we go, then we will be able to see the accounts based on the queryexpression condition:

I hope this code might helps someone out there..

Happy CRM:-)
🔄

🔵🌹💮
Share this: