Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

C# Dynamic CRM error

Posted on 2013-01-29
7
Medium Priority
?
2,601 Views
Last Modified: 2013-03-04
I created a plug-in Dynamic CRM 2011 that gets some values from a stored proc then inserts those values in an attribute/field on a CRM Entity. When I run the workflow that calls or runs the plug-in I get the error below. I have serarched the web and have come up short. Please help. Thanks.
Error:

EXCEPTION=EXCEPTION=System.FormatException: Unrecognized Guid format.
   at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException)
   at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult& result)
   at System.Guid..ctor(String g)
   at AddAEToCommits.AddAEToCommits.Execute(CodeActivityContext executionContext)

Please let me know if you need the code as well.
0
Comment
Question by:newjeep19
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2
7 Comments
 
LVL 19

Expert Comment

by:Rikin Shah
ID: 38833809
Hi,

I created a plug-in Dynamic CRM 2011 that gets some values from a stored proc then inserts those values in an attribute/field on a CRM Entity.

You probably are assigning an ID (Guid type) attribute a wrong data type value or without converting it to System.Guid. Convert the value to Guid and you are good to go.
0
 

Author Comment

by:newjeep19
ID: 38835665
Thank you for the reply. However I am now getting this error
EXCEPTION=EXCEPTION=System.NullReferenceException: Object reference not set to an instance of an object.
   at AddAEToCommits.AddAEToCommits.Execute(CodeActivityContext executionContext)

Code :
Guid opportunityId = Guid.Empty;

//Then update the Opportunity < -- syntax that is causing the above error
 _opportunity.Id = opportunityId;
0
 
LVL 19

Expert Comment

by:Rikin Shah
ID: 38838141
Why assigning an empty Guid? Any reason behind it? Also check your org context for null.
0
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 

Author Comment

by:newjeep19
ID: 38859758
When I run my workflow/ practice in CRM I get the error below:
Workflow paused due to error: Unhandled Exception: System.Activities.InvalidWorkflowException: The following errors were encountered while processing the workflow tree:
'DynamicActivity': The private implementation of activity '1: DynamicActivity' has the following validation error:   Compiler error(s) encountered processing expression "DirectCast(CustomActivityStep4_5_converted, Microsoft.Xrm.Sdk.EntityReference)".Invalid L-value expression.:Reference expressions cannot end with Conversion. The provided expression's type must exactly match the type T of VisualBasicReference<T> or LambdaReference<T>.
   at System.Activities.Hosting.WorkflowInstance.ValidateWorkflow(WorkflowInstanceExtensionManager extensionManager)
   at System.Activities.WorkflowApplication.EnsureInitialized()
   at System.Activities.WorkflowApplication.Enqueue(InstanceOperation operation, Boolean push)
   at System.Activities.WorkflowApplication.WaitForTurn(InstanceOperation operation, TimeSpan timeout)
   at System.Activities.WorkflowApplication.InternalRun(TimeSpan timeout, Boolean isUserRun)
   at Microsoft.Crm.Workflow.ActivityHost.StartWorkflowExecution(Activity workflow, ICommonWorkflowContext context)
   at Microsoft.Crm.Workflow.ActivityHostBase.StartWorkflow(ICommonWorkflowContext context, Activity preLoadedActivity)

Here is my full C# code for the plug-in
using System;
using System.Activities;
using System.Collections.ObjectModel;
using System.Collections.Generic;

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;

using Microsoft.Crm.Sdk.Messages;

using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Collections;
using System.Reflection;
using System.Text;

using System.Linq;

using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Web;
using System.Web.Services.Protocols;
using System.Xml;

using GTRI;
using GTRI.DataAccess;

using System.Configuration;
using System.Web.Services;
using System.Net.Mail;

namespace AddAEToCommits
{
    public sealed class AddAEToCommits : CodeActivity
    {
        #region Connections
        private static string connectionString = connection info here
        #endregion

        #region Globals
        Entity opportunity = null;
        Entity _opportunity = null;
        string AECustomerReader = string.Empty;
        Guid accountExecutiveId;
        DateTime date;
        Guid CustomEntityName;
        Guid AECommitId;
        #endregion

        #region SQL
        string sqlQuery = String.Empty;
        private Guid monthlyCommitId;
        string monthlyCommitName = String.Empty;
        private Guid AECustomerGuid;
        #endregion

        public void Write(string arg1)
        {
            _Write(arg1, String.Empty);
        }

        public void Write(Exception ex)
        {
            _Write(ex.ToString(), "");
        }

        public void Write(Exception ex, string arg1)
        {
            _Write(ex.ToString(), arg1);
        }

        private void _Write(string s, string ss)
        {
            try
            {
                string fileDate = DateTime.Now.ToShortDateString().Replace(":", "").Replace("/", "") + DateTime.Now.ToShortTimeString().Replace(":", "").Replace(" ", "");
                using (System.IO.TextWriter T = new System.IO.StreamWriter(@"C:\Logs\AEWorkflow\ErrorLog_" + fileDate + ".txt", true))
                {
                    T.WriteLine("Adds To Commit Workflow Exception");
                    T.WriteLine("");
                    T.WriteLine("EXCEPTION=" + s.ToString());
                    T.WriteLine("");
                    T.WriteLine("EXCEPTION=" + ss.ToString()); ;
                    T.WriteLine(""); 
                    T.WriteLine("Created By: " + accountExecutiveId);
                    T.WriteLine("Estimated Closedate: " + date);
                    T.WriteLine("Input field: " + AECustomerReader);
                    T.WriteLine("Opportunity: " + CustomEntityName);
                }
            }
            catch (Exception e)
            {
                e.InnerException.Message.ToString();
            }
        }

        // Initialize the input parameter
        [Input("Account Executive")]
        [ReferenceTarget("systemuser")]
        public InArgument<EntityReference> accountExecutiveReference { get; set; }

        [Input("Date to Close")]
        public InArgument<DateTime> dateToCloseReference { get; set; }

        [Input("Opportunity")]
        [ReferenceTarget("opportunity")]
        public InOutArgument<EntityReference> opportunityReference { get; set; }

        [Output("Monthly Commit Id")]
        [ReferenceTarget("opportunity")]
        public OutArgument<EntityReference> commitOutReference { get; set; }

        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {

                //Create the IWorkflowContext and the
                //IOrganizationService for communication with CRM
                IWorkflowContext workflowContext = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

                EntityReference systemuser = accountExecutiveReference.Get<EntityReference>(executionContext);

                // Access the input parameter declared above 
                Guid accountExecutiveId = new Guid();
                accountExecutiveId = accountExecutiveReference.Get(executionContext).Id;

                DateTime date = new DateTime();
                date = dateToCloseReference.Get(executionContext);

                //Then update the Opportunity
                Guid CustomEntityName = new Guid();
                CustomEntityName = opportunityReference.Get(executionContext).Id;

                _opportunity.Id = CustomEntityName;

               //Execute Stored Proc
                using (SqlConnection oConn = new SqlConnection(connectionString))
                {
                    oConn.Open();

                    //Delete Commit link SQL statement
                    using (SqlCommand cmdAECommit = new SqlCommand())
                    {
                        cmdAECommit.Connection = oConn;
                        cmdAECommit.CommandType = CommandType.StoredProcedure;
                        cmdAECommit.CommandText = "dbo.AddOppInfoToCommits";
                        cmdAECommit.Parameters.AddWithValue("@estimatedclosedate", date);
                        cmdAECommit.Parameters.AddWithValue("@createdby", accountExecutiveId);
                        using (SqlDataReader reader = cmdAECommit.ExecuteReader())
                        {
                            int intCounter = 0;
                            while (reader.Read()) //opens the SQL 
                            {
                                if (intCounter == 0)
                                {
                                    AECustomerReader = reader["GTRI_name"].ToString();
                                }
                                intCounter++; //end of reader
                            }
                            reader.Close();
                        }
                    }
                    oConn.Close();
                }

                Entity updateOpportunity = new Entity(_opportunity.LogicalName);
                updateOpportunity.Attributes["gtri_monthlycommitid"] = AECustomerReader;
                service.Update(updateOpportunity);

                Write("Created By: " + accountExecutiveId);
                Write("Estimated Closedate: " + date);
                Write("Input field: " + AECustomerReader);
                Write("Opportunity: " + CustomEntityName);
            }
            catch (Exception ex)
            {
            }
        }
    }
}

Open in new window

0
 

Author Comment

by:newjeep19
ID: 38859768
Please help I need an answer soon thank you
0
 

Accepted Solution

by:
newjeep19 earned 0 total points
ID: 38935289
I was able to find a solution on my own. The code is below:

    protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                //Create the IWorkflowContext and the
                //IOrganizationService for communication with CRM
                IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);


                EntityReference systemuser = accountExecutiveReference.Get<EntityReference>(executionContext);
                EntityReference opportunity = myOpportunity.Get<EntityReference>(executionContext);

                // Access the input parameter declared above 
                Guid accountExecutiveId = new Guid();
                accountExecutiveId = accountExecutiveReference.Get(executionContext).Id;

                DateTime date = new DateTime();
                date = dateToCloseReference.Get(executionContext);

                Guid opportunityId = new Guid();
                opportunityId = myOpportunity.Get(executionContext).Id;

                Guid monthlyCommitId = Guid.Empty;

                //Execute Stored Proc
                using (SqlConnection oConn = new SqlConnection(connectionString))
                {
                    oConn.Open();

                    //Delete Commit link SQL statement
                    using (SqlCommand cmdAECommit = new SqlCommand())
                    {
                        cmdAECommit.Connection = oConn;
                        cmdAECommit.CommandType = CommandType.StoredProcedure;
                        cmdAECommit.CommandText = "dbo.AddOppInfoToCommits";
                        cmdAECommit.Parameters.AddWithValue("@estimatedclosedate", date);
                        cmdAECommit.Parameters.AddWithValue("@createdby", accountExecutiveId);
                        using (SqlDataReader reader = cmdAECommit.ExecuteReader())
                        {
                            if (reader != null)
                            {
                                if (reader.HasRows)
                                {
                                    int intCounter = 0;
                                    while (reader.Read()) //opens the SQL 
                                    {
                                        if (intCounter == 0)
                                        {
                                            monthlyCommitId = (Guid)reader["GTRI_MonthlyCommitId"];
                                            MonthlyCommitName = reader["Gtri_name"].ToString();
                                        }
                                        intCounter++; //end of reader
                                    }
                                    reader.Close();
                                }
                            }
                        }
                    }
                    oConn.Close();
                }

                if (monthlyCommitId != Guid.Empty)
                {
                    Entity updateOpportunity = new Entity("opportunity");
                    updateOpportunity.Id = opportunityId;

                    EntityReference monthlyCommitReference = new EntityReference("gtri_monthlycommit", monthlyCommitId);
                    updateOpportunity["gtri_monthlycommitid"] = monthlyCommitReference;

                    service.Update(updateOpportunity);
                }
            }
            catch (SoapException ex)
            {
                Write("SoapException", ex);
            }
            catch (Exception ex)
            {
                Write("Exception", ex);
            }
        }

        #region CRMInput
        // Initialize the input parameter
        [Input("Account Executive")]
        [ReferenceTarget("systemuser")]
        public InArgument<EntityReference> accountExecutiveReference { get; set; }

        [Input("Date to Close")]
        public InArgument<DateTime> dateToCloseReference { get; set; }

        [Input("Opportunity")]
        [ReferenceTarget("opportunity")]
        public InArgument<EntityReference> myOpportunity { get; set; }

        #endregion
    }

Open in new window

0
 

Author Closing Comment

by:newjeep19
ID: 38949187
I wa able to workout the issue by writing the errors out to a log and searching for examples on the internet
0

Featured Post

Tech or Treat! - Giveaway

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
For cloud, the “train has left the station” and in the Microsoft ERP & CRM world, that means the next generation of enterprise software from Microsoft is here: Dynamics 365 is Microsoft’s new integrated business solution that unifies CRM and ERP fun…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question