Thursday 7 January 2016

how to create appointment programmatically In CRM.

Create Appointment using CRM plugin

Description:-

In this example we explain that how to create appointment programmatically In CRM. Or create appointment in calendar using CRM plugin.

In previous example we already explain that how to create lead in CRM and transfer this lead data to SQL server external database using CRM plugin when lead is created same flow is occurred in appointment when new appointment is created in CRM then this appointment is automatically inserted to the external SQL database through web service using CRM plugin.

I have already realized that the CRM plugin is not fired for appointment when appointment is created in CRM and I also search this one why plugin is not fired for appointment. The question in my mind was that if plugin was fired for lead after creation of lead in CRM then why it is not working for appointment because same code only fields is changed like appointment fields instead of lead fields.

So finally I got the solution that is must remember before create the plugin for the appointment. Always set the plugin in child pipeline otherwise it will not fire. Look the below image for register plugin in child pipeline.

Register plugin in Child Pipeline


 Plugin Code:-

namespace kiritAppointmentPligin.Plugins
{
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using kiritAppointmentPligin.Plugins.ServiceReference1;

    /// <summary>
    /// PreValidateAppointmentCreate Plugin.
    /// </summary>   
    public class PreValidateAppointmentCreate: IPlugin
    {
      
        public void Execute(IServiceProvider serviceprovider)
        {
            try
            {
                ITracingService tracingService =
                  (ITracingService)serviceprovider.GetService(typeof(ITracingService));


                IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));

                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {

                    Entity entity = (Entity)context.InputParameters["Target"];

                    IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));

                    //Service = access to data for modification
                    IOrganizationService service = factory.CreateOrganizationService(context.UserId);

                    // Adding Basic Http Binding and its properties.
                    BasicHttpBinding myBinding = new BasicHttpBinding();
                    myBinding.Name = "BasicHttpBinding_Service";
                    myBinding.Security.Mode = BasicHttpSecurityMode.None;
                    myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                    myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                    myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;


                    myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                    myBinding.OpenTimeout = new TimeSpan(0, 10, 0);
                    myBinding.SendTimeout = new TimeSpan(0, 10, 0);
                    myBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);

                    EndpointAddress endPointAddress = new EndpointAddress(@"http://capella:7093");
                    WebServiceSoapClient my = new WebServiceSoapClient(myBinding, endPointAddress);

                    my.Open();
                    string optionalAttendeesName, requiredAttendeesName;
                    optionalAttendeesName= requiredAttendeesName= null;
                    EntityCollection requiredAttendees = new EntityCollection();
                    requiredAttendees = entity.GetAttributeValue<EntityCollection>("requiredattendees");
                 
                    for (int i = 0; i < requiredAttendees.Entities.Count; i++)
                    {
                        requiredAttendeesName = ((EntityReference)((EntityCollection)entity["requiredattendees"]).Entities[i].Attributes["partyid"]).Name;
                        requiredAttendeesName += requiredAttendeesName;

                    }
                    EntityCollection optionalAttendees = new EntityCollection();
                    optionalAttendees = entity.GetAttributeValue<EntityCollection>("optionalattendees");
                  
                    for (int i = 0; i < optionalAttendees.Entities.Count; i++)
                    {
                        optionalAttendeesName = ((EntityReference)((EntityCollection)entity["optionalattendees"]).Entities[i].Attributes["partyid"]).Name;
                        optionalAttendeesName += optionalAttendeesName;

                    }


                    string ab = my.InsertAppointment(entity.GetAttributeValue<DateTime>("scheduledstart"), entity.GetAttributeValue<DateTime>("scheduledend")
                        , requiredAttendeesName, optionalAttendeesName
                         //,"dsgfdsgf"//  ((EntityReference)((EntityCollection)entity["regardingobjectid"]).Entities[0].Attributes["partyid"]).Name
                         //, entity.GetAttributeValue<string>("location")
                         //, entity.GetAttributeValue<string>("subject"));
                        , ((EntityReference)entity["regardingobjectid"]).Name
                         , string.IsNullOrEmpty(entity.GetAttributeValue<string>("location")) ? null : entity.GetAttributeValue<string>("location")
                         , string.IsNullOrEmpty(entity.GetAttributeValue<string>("subject")) ? null : entity.GetAttributeValue<string>("subject"));
                    if (ab != null)
                    {
                        throw new InvalidPluginExecutionException("Success");
                    }
                    my.Close();
                }
            }
            catch (CommunicationException ex)
            {
                throw new InvalidPluginExecutionException(ex.ToString());

            }




        }
    }
}


 WebService Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    [WebMethod]
    public string InsertLead(string subject,string fnm,string lnm,string email)
    {
        fnm = "demo";
        string isSuccess = null;
        using (SqlConnection connection = new SqlConnection(@"Data Source=RIGEL\SQL2008R2;Initial Catalog=AX2012R2_Contoso_SPICA;Integrated Security=SSPI"))
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = "Insert into Lead VALUES (@subject,@firstname,@lastname,@emailaddress)";

            command.Parameters.AddWithValue("@subject", subject);
            command.Parameters.AddWithValue("@firstname", fnm);
            command.Parameters.AddWithValue("@lastname", lnm);
            command.Parameters.AddWithValue("@emailaddress", email);
            connection.Open();
            command.ExecuteNonQuery();
            isSuccess = "Sucess";
        }
        return isSuccess;
    }
    [WebMethod]
    public string InsertAppointment(DateTime StartTime, DateTime EndTime, string Required, string Optional, string Regarding, string Location, string Subject)
    {
     
        string isSuccess = null;
        using (SqlConnection connection = new SqlConnection(@"Data Source=RIGEL\SQL2008R2;Initial Catalog=AX2012R2_Contoso_SPICA;Integrated Security=SSPI"))
        using (SqlCommand command = connection.CreateCommand())
        {
           // command.CommandText = "Insert into Appointment(Location,Subject,Optional) VALUES (@Location,@Subject,@Optional)";
            command.CommandText = "Insert into Appointment VALUES (@Required,@Optional,@Regarding,@Location,@StartTime,@EndTime,@Subject)";

            command.Parameters.AddWithValue("@Required", Required == null ? (object)DBNull.Value : Required);
            command.Parameters.AddWithValue("@Optional", Optional == null ? (object)DBNull.Value : Optional);
            command.Parameters.AddWithValue("@Regarding", Regarding== null ? (object)DBNull.Value :Regarding);
            command.Parameters.AddWithValue("@Location", Location== null ? (object)DBNull.Value :Location);
            command.Parameters.AddWithValue("@StartTime",StartTime);
            command.Parameters.AddWithValue("@EndTime",EndTime);
            command.Parameters.AddWithValue("@Subject",Subject);
            connection.Open();
            command.ExecuteNonQuery();
            isSuccess = "Sucess";
        }
        return isSuccess;
    }
}



This entry was posted in :

2 comments:

  1. in this blogs has some error please check it...
    and then upload blog like this

    ReplyDelete