Saturday, 21 May 2016

Generating CRM proxy class for early binding

CrmSvcUtil.exe is a command-line code generation tool in that generates early-bound 

Microsoft Dynamics CRM 2015 provides an extension to the CrmSvcUtil.exe command-line tool, called theMicrosoft.Xrm.Client.CodeGeneration extension, which you can use to generate the data context and data transfer object classes for your Microsoft Dynamics CRM organization.

Download the SDK and Microsoft.Xrm.Client.CodeGeneration dll should be in bin folder

Integrated Authentication Example

  1. CrmSvcUtil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration"
  2. /url:http://crm/Contoso/XRMServices/2011/Organization.svc
  3. /out:"Xrm.cs"
  4. /namespace:Xrm
  5. /servicecontextname:XrmServiceContext
  6. /servicecontextprefix:Xrm

Active Directory Authentication  Example

  1. CrmSvcUtil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration"
  2. /url:http://crm/Contoso/XRMServices/2011/Organization.svc
  3. /domain:contoso
  4. /username:administrator
  5. /password:pass@word1
  6. /out:"Xrm.cs"
  7. /namespace:Xrm
  8. /servicecontextname:XrmServiceContext
  9. /servicecontextprefix:Xrm

Live ID (CRM Online) Authentication

  1. /url:http://myorg.api.crm.dynamics.com/XRMServices/2011/Organization.svc
  2. /out:"Xrm.cs"
  3. /username:user@hotmail.com
  4. /password:pass@word1
  5. /deviceid:mydeviceid
  6. /devicepassword:mydevicepassword
  7. /namespace:Xrm
  8. /servicecontextname:XrmServiceContext
  9. /servicecontextprefix:Xrm

Claims Authentication (IFD, Active Directory) 

  1. CrmSvcUtil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration"
  2. /url:https://crm:555/Contoso/XRMServices/2011/Organization.svc
  3. /username:administrator
  4. /password:pass@word1
  5. /out:"Xrm.cs"
  6. /namespace:Xrm
  7. /servicecontextname:XrmServiceContext
  8. /servicecontextprefix:Xrm

Thursday, 15 January 2015

Integration of MSCRM with TIBCO ESB

Requirements for integrating Dynamics CRM with the other systems  is to use Tibco Enterprise Service Bus as the only communication layer.


The communication with Tibco ESB is the main integration point for Dynamics CRM. It must replace SAP CRM endpoints and also support a new communication channel with SAP IS-U.

1.       Outbound communication from Dynamics CRM
In order to perform web service calls to an external system, the plugin extension capabilities of Dynamics CRM are used. Plugins are pieces of custom C# code that are triggered on a specific system event and implement custom business logic. The integration approach uses plugins to communicate with TIBCO ESB.
The advantages of using plugins for integration purposes include the following:
        Make use of the power of .NET libraries;
        Support both synchronous and asynchronous execution. If ran asynchronously, plugins execute behind the scenes and do not interact with user activities;
        Provide out of the box logging mechanism inside the CRM for auditing and error logging;
        Can be configured to run in various Steps of the execution pipeline within CRM: pre-event and pre-validation, pre-event and pre-operation, and post-event;
        Provide the triggering entity data in the execution context, both pre and post operation, eliminating the need for additional data queries.
In order to implement the integration with TIBCOESB post a request XML to a Queue or Topic and get a response, the integration approach uses the .NET EMS library provided together with the Tibco documentation. The library handles the authentication mechanism and provides strong classes for establishing a communication with Tibco

1.       Inbound communication to Dynamics CRM
For the inbound integration with Dynamics CRM there are two possible approaches to be considered:
A.      TIBCO calling the MS CRM web services:
        Pro: no custom connector, reduced risk of error;
        Cons: custom TIBCO adapter needed for the CRM authentication through ADFS, higher implementation cost.
B.      Using a custom WCF service to mediate the communication between TIBCO and MS CRM:
        Pro: fast implementation, performance scalability options, interoperability with other technologies;
        Cons: additional custom WCF component to maintain.

///<summary>
/// Sent a request XML to a Tibco Queue
///</summary>
privatevoid SendRequest()
        {
            Connection connection = null;
try
            {
                ConnectionFactory connectionFactory = new ConnectionFactory(serverUrl);
                connection = connectionFactory.CreateConnection(userName, password);
                Session session = connection.CreateSession(false, 1);
                Destination destination = session.CreateQueue(requestQueue);
                MessageProducer messageProducer = session.CreateProducer(null);
                TextMessage textMessage = session.CreateTextMessage(RequestMessage);
if (!string.IsNullOrEmpty(correlationId))
                {
                    textMessage.CorrelationID = correlationId;
                }
                Destination replyTo = session.CreateQueue(responseQueue);
                textMessage.ReplyTo = replyTo;
                messageProducer.Send(destination, textMessage);
            }
catch (EMSException ex)
            {
                tracingService.Trace(ex.Message, newobject[0]);
throw ex;
            }
finally
            {
                connection.Close();
            }
        }

///<summary>
/// Retrieve the synchronous reponse XML from a Tibco Queue
///</summary>
privatevoid GetSyncResponse()
        {
int num = 1;
bool flag = false;
            Connection connection = null;
            Message message = null;
try
            {
                ConnectionFactory connectionFactory = new ConnectionFactory(serverUrl);
                connection = connectionFactory.CreateConnection(userName, password);
                Session session = connection.CreateSession(false, num);
                Destination destination = session.CreateQueue(responseQueue);
string text = "JMSCorrelationID = '" + correlationId + "'";
                MessageConsumer messageConsumer = session.CreateConsumer(destination, text);
                connection.Start();
while (!flag)
                {
                    ReplyMessage = messageConsumer.Receive().ToString();
if (message == null)
                    {
break;
                    }
if (num == 2 || num == 23 || num == 24)
                    {
                        message.Acknowledge();
                    }
                    flag = true;
                }
            }
catch (Exception ex)
            {
                tracingService.Trace(ex.Message, newobject[0]);
throw ex;
            }
finally
            {
                connection.Close();
            }
        }

///<summary>
///  Retrieve the asynchronous XML reponse from a Tibco Queue
///</summary>
privatevoid GetASyncResponse()
        {
            Connection connection = null;
try
            {
                ConnectionFactory connectionFactory = new ConnectionFactory(serverUrl);
                connection = connectionFactory.CreateConnection(userName, password);
                Session session = connection.CreateSession(false, 1);
                Destination destination = session.CreateQueue(responseQueue);
Console.WriteLine("Subscribing to destination: " + responseQueue);
string text = "JMSCorrelationID = '" + correlationId + "'";
                MessageConsumer messageConsumer = session.CreateConsumer(destination, text);
                messageConsumer.MessageHandler += new EMSMessageHandler(_HandleMessage);
                connection.Start();

while (true)
                {
lock (stateLock)
                    {
if (stop)
                        {
                            connection.Stop();
break;
                        }
Thread.Sleep(2000);
                    }
                }
            }
catch (Exception ex)
            {
                tracingService.Trace(ex.Message, newobject[0]);
throw ex;
            }
        }

///<summary>
/// Asynchronous message handler
///</summary>
///<param name="sender"></param>
///<param name="arg"></param>
privatevoid _HandleMessage(object sender, EMSMessageEventArgs arg)
        {
try
            {
                stop = true;
                ReplyMessage = ((TextMessage)arg.Message).Text;
                msg = arg.Message;
            }
catch (Exception ex)
            {
                tracingService.Trace(ex.Message, newobject[0]);
throw ex;
            }
        }


Friday, 6 December 2013

Create a WPF appication and display Account record in grid Ms Crm

1. Create a Grid in WPF application in window.Xaml


  <Grid>
        <Grid Height="287" HorizontalAlignment="Left" Margin="0,12,0,0" Name="grid1" VerticalAlignment="Top" Width="503">
{ create a Label  Create Account } 

            <Label Content="Create Account" Height="28" HorizontalAlignment="Left" Margin="6,33,0,0" Name="label1" VerticalAlignment="Top" Width="109" />
{ Create a Button and on click display account connecting to mscrm online }

            <Button Content="Display Account" Height="23" HorizontalAlignment="Left" Margin="179,34,0,0" Name="button1" VerticalAlignment="Top" Width="266" Click="button1_Click" />
{Create a colom in Grid }
            <DataGrid Height="171" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="4,109,0,0" Name="account" VerticalAlignment="Top" Width="497"  >
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Path= Name}" Header="Name" />
                    <DataGridTextColumn Binding="{Binding Path= FirstName}" Header="fName" />
                    <DataGridTextColumn Binding="{Binding Path= emailAddress}" Header="lName" />
                    <DataGridTextColumn Binding="{Binding Path= lName}" Header="emailAdrress" />
                    <DataGridTextColumn Binding="{Binding Path= fName}" Header="First Name" />
                    <DataGridTextColumn Binding="{Binding Path= phnNum}" Header="Phone Number" />
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Grid>


2.) In window.xaml.cs

public partial class MainWindow : Window
    {
        IOrganizationService org;   // add a microsoft.xrm.sdk.dll
        EntityCollection ent = new EntityCollection();
        public MainWindow()
        {
            InitializeComponent();
            org =  GetOrganizationSerivice();
           
        }

        #region GetProxy
        public OrganizationServiceProxy GetProxy()
        {
            string strUrl = string.Empty;
            strUrl = "Organization url mscrm online" ;

            Uri organizationUri = new Uri(strUrl);
            Uri homeRealUri = null;
            ClientCredentials credentials = new ClientCredentials();
            credentials.UserName.UserName = "username" ;
            credentials.UserName.Password = "password";
           // credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
            OrganizationServiceProxy proxyService = new OrganizationServiceProxy(organizationUri, homeRealUri, credentials, null);
            proxyService.EnableProxyTypes();
            return proxyService;
        }

        static IOrganizationService GetOrganizationSerivice()
        {
           
            string strUrl = string.Empty;
            strUrl = "mscrm online";
            ClientCredentials credential = new ClientCredentials();
            credential.UserName.UserName = "user name";
            credential.UserName.Password = "password";
           // credential.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            OrganizationServiceProxy proxy = new OrganizationServiceProxy(new Uri(strUrl), null, credential, null);
            return proxy as IOrganizationService;
        }


        #endregion

        public class AccountList
        {
create property to bind data in grid .

            public int id{get; set;}
            public string Name { get; set; }
            public string FirstName{ get; set; }
            public string emailAddress { get; set; }
            public string lName { get; set; }
            public string fName { get; set; }
            public string phnNum { get; set; }
        }


        private void button1_Click(object sender, RoutedEventArgs e)
        {
           
        
            QueryExpression query = new QueryExpression();
            query.EntityName = "account";
            ColumnSet columnSet = new ColumnSet();
            columnSet.AllColumns = true;
            //columnSet.Columns.Add("name");
            query.ColumnSet = columnSet;
            query.Distinct = true;
           ent = org.RetrieveMultiple(query);
            List<AccountList> AllParts = new List<AccountList>();
            AccountList rr = new AccountList();
          
            foreach (Entity en in ent.Entities)
            {
                rr = new AccountList { Name = en.Attributes["name"].ToString(), lName = "Apple" };
//using above property to bind data to CRM.
           AllParts.Add(rr);
             }
            account.ItemsSource = AllParts;

            account.Items.Refresh();
          
        }

       
    }

Monday, 4 November 2013

Trigger plugin on assignment of security role mscrm

Triggering a plugin on adding of security role
if xyz security role is assigned to user then add user to a team.

step 1: Register a plugin  on message Associate , primary and secondary entity as none
step2:   AssignUserRoles as a message and primary entity as a Role

public void Execute(IServiceProvider serviceProvider)
        {
            // Extract the tracing service for use in debugging sandboxed plug-ins.
            // If you are not registering the plug-in in the sandbox, then you do
            // not have to add any tracing service related code.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));

             // The InputParameters collection contains all the data passed in the message request.
verify plugin message is associate or
        if (context.MessageName=="Associate" || context.MessageName== "AssignUserRole")       
        {
            // Obtain the target entity from the input parameters.

            EntityReference entity = (EntityReference)context.InputParameters["Target"];
        
            // Verify that the target entity represents an entity type you are expecting.
            // For example, an user entity If not, the plug-in was not registered correctly.
            if (entity.LogicalName.ToUpper() != "SYSTEMUSER")
                return;

            // Obtain the organization service reference which you will need for
            // web service calls.
            IOrganizationServiceFactory serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                Guid userId = context.InitiatingUserId;
                Guid businessUnitId = getBuid(service);
                //get roles of a  user
                Entity role = new Entity();
                role.LogicalName = "role";

                Entity systemUserRoles = new Entity();
                systemUserRoles.LogicalName = "systemuserroles";
//query expression to fetch security role associated to a user
as we have Guid  of initiating user
                QueryExpression query = new QueryExpression()
                {
                    Distinct = false,
                    EntityName = role.LogicalName,
                    ColumnSet = new ColumnSet("name")
                };
               
                query.AddLink(systemUserRoles.LogicalName, "roleid", "roleid").
                LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, userId);


                //query expression to execute the role
                EntityCollection entRoles = service.RetrieveMultiple(query);

                //get role name
                List<string> rolesname = new List<string>();
                foreach (Entity roles in entRoles.Entities)
                {

                    rolesname.Add(roles.Attributes["name"].ToString());
                }

                //create a team if not exist
                Entity team = new Entity("team");
               // team.Id = new Guid();
                team["name"] ="Team1";
                team["businessunitid"] = new EntityReference("businessunit", businessUnitId);
                team["administratorid"] = new EntityReference("systemuser", context.UserId);
             
// Create the team in Microsoft Dynamics CRM if not exist.
                QueryExpression qp = new QueryExpression();
                qp.EntityName = "team";
                qp.ColumnSet = new ColumnSet();
                qp.ColumnSet.AddColumns("teamid", "name");
                qp.Criteria.AddCondition("name",ConditionOperator.Equal,"Team1");
               EntityCollection ent = service.RetrieveMultiple(qp);
               Guid teamid = Guid.Empty;

                foreach(Entity enti in ent.Entities)
                {
                    teamid = (Guid)enti["teamid"];
                }

               if (ent.Entities.Count == 0)
               {
                   service.Create(team);
               }
                // Plug-in business logic goes here.
               foreach(string rolesnames in rolesname)
               {
                 if( rolesnames == "System Administrator")
                 {
                
                     //create a members to a team

                     AddMembersTeamRequest addMembereTeamRequest = new AddMembersTeamRequest();
                     addMembereTeamRequest.TeamId = teamid;
                     Guid[] arrayMembers = new Guid[1];
                     arrayMembers[0] = userId;
                     addMembereTeamRequest.MemberIds = arrayMembers;
                     AddMembersTeamResponse addMembersTeamresp = (AddMembersTeamResponse)service.Execute(addMembereTeamRequest);

                 }
               }
               
            }