Hi all ,

My requirement was, When a case is created and there were no activity(activity includes update any field of case or any activity created or closed for the case) done  on this case for 5 mint , then we should send email to case owner. 

I have used workflow to trigger email after 5 mint of case creation. To check any case filed is modified or not or any custom activity created or not , I have used plugin. But sometime i got "An unexpected error occurred""

error details: 

{ [-]
       ClassName: System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]
       Data: null
       ExceptionMethod: 8 RetrieveMultiple Microsoft.Crm.Extensibility, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal Microsoft.Xrm.Sdk.EntityCollection RetrieveMultiple(Microsoft.Xrm.Sdk.Query.QueryBase, Microsoft.Crm.Extensibility.CorrelationToken, Microsoft.Crm.Sdk.CallerOriginToken, Microsoft.Crm.Performance.WebServiceType, Boolean)
       HResult: -2146233087
       HelpURL: null
       InnerException: null
       Message: An unexpected error occurred.
       RemoteStackIndex: 0
       RemoteStackTraceString: null
       Source: Microsoft.Crm.Extensibility
       StackTraceString: at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.RetrieveMultiple(QueryBase query, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode) at Microsoft.Crm.Extensibility.InprocessServiceProxy.RetrieveMultipleCore(QueryBase query) at CCAS.CRM.Plugins.CaseCheckActivity.GetActivityDetails(String linkEntity, String sActivityId, CCContext ccContext)
       WatsonBuckets: null
       action: null
       code: [ [+]
       ]

       detail: { [-]
         ErrorCode: -2147220970
         ErrorDetails: [ [+]
         ]

         InnerFault: { [-]
           ErrorCode: -2147220970
           ErrorDetails: [ [-]
           ]

           InnerFault: null
           Message: System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #F4BB49E4
           Timestamp: 2019-07-26T13:11:09.7003572Z
           TraceText: null
         }

         Message: An unexpected error occurred.
         Timestamp: 2019-07-26T13:11:09.7003572Z
         TraceText: null
       }

       messageFault: null
       reason: [ [+]
       ]

     }

what could be  issue ? 

workflow images :

and plugin code : 

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using SL = CCAS.CRM.SplunkLogger;

namespace CCAS.CRM.Plugins
{
public class CaseCheckActivity : IPlugin
{

/// </summary>
public IOrganizationService OrgService
{
get;
private set;
}

/// <summary>
/// Tracing Service
/// </summary>
public ITracingService TracingService { get; private set; }

private const string _className = "CaseCheckActivity";

SL.SplunkLogger splunkLog = new SL.SplunkLogger();

public void Execute(IServiceProvider serviceProvider)
{
CCContext ccContext = null;
try
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
ccContext = new CCContext(context, serviceProvider);
TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
var service = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
OrgService = service.CreateOrganizationService(context.UserId);
ccContext.WriteContextToLog(_className, CCContext.LogPoint.Entering);
Entity CallingEntity = (Entity)context.InputParameters["Target"];

bool flag = GetAssociatedActivities(CallingEntity, ccContext);

if (flag == true)
{
CallingEntity["new_lastactivity"] = System.DateTime.Now;
}
}
catch (Exception ex)
{
if (ccContext != null)
{
ccContext.WriteException(ex.Message, ex);
}
}
finally
{
if (ccContext != null)
{
ccContext.WriteContextToLog(_className, CCContext.LogPoint.Exiting);
ccContext.SaveLog();
var data = new SL.LogData
{
LogName = "**************",
Severity = SL.LogLevel.Info,
Message = ccContext.LogBuilder.ToString()
};
ccContext.WriteSplunkLog(data);
ccContext = null;
}
}
}

/*
4201 Appointment
4202 Email
4204 Fax
4206 IncidentResolution
4210 PhoneCall
4212 Task
*/
private bool GetAssociatedActivities(Entity regarding, CCContext ccContext)
{
bool flag = false;
try
{
QueryExpression query = new QueryExpression { EntityName = "activitypointer", ColumnSet = new ColumnSet(new string[] { "activitytypecode", "createdby", "modifiedby", "isworkflowcreated" }) };
query.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, regarding.Id);
EntityCollection collection = OrgService.RetrieveMultiple(query);

if (collection.Entities.Count > 0)
{
foreach (Entity activity in collection.Entities)
{
string _activityTypeCode = (string)activity.Attributes["activitytypecode"];
string _sactivityId = activity.Attributes["activityid"].ToString();
bool isWorkflowCreated = (bool)(activity.Attributes["isworkflowcreated"]);

if (!isWorkflowCreated)
{
string activityDetails = GetActivityDetails(_activityTypeCode, _sactivityId, ccContext);
string sActivitySource = activityDetails.Split(',')[0];
string activityModified = activityDetails.Split(',')[1];

if (activityModified == "True") // check system activity modified by users for origin VIMS and gateway
{
flag = false;
break;
}
else if (sActivitySource == "0") // when new activity is created
{
flag = false;
break;
}
else
{
flag = true;
}
}
}
}

}
catch(Exception ex)
{
if (ccContext != null)
{
ccContext.WriteException(ex.Message, ex);
}
}
return flag;
}

private string GetActivityDetails(string linkEntity, string sActivityId, CCContext ccContext)
{
string activitySource = "";
OptionSetValue ActivitySourceCode = new OptionSetValue();
bool activityModified = false;
QueryExpression query = new QueryExpression("activitypointer");
query.ColumnSet = new ColumnSet("activitytypecode", "createdby", "modifiedby");
LinkEntity lnkEntity = new LinkEntity("activitypointer", linkEntity, "activityid", "activityid", JoinOperator.Inner); // TASK Has to be dynamic value
lnkEntity.Columns = new ColumnSet("new_activitysource", "createdon", "modifiedon");
lnkEntity.EntityAlias = linkEntity; // TASK Has to be dynamic value
query.LinkEntities.Add(lnkEntity);
query.Criteria.Conditions.Add(new ConditionExpression("activityid", ConditionOperator.Equal, sActivityId));

try
{
var result = OrgService.RetrieveMultiple(query);
foreach (Entity entity in result.Entities)
{
switch (lnkEntity.EntityAlias)
{
case "task":
ActivitySourceCode = entity.Contains("task.new_activitysource") ? (OptionSetValue)(entity["task.new_activitysource"] as AliasedValue).Value : new OptionSetValue();

DateTime dtTaskCreatedOn = (DateTime)(entity["task.createdon"] as AliasedValue).Value;
dtTaskCreatedOn = dtTaskCreatedOn.AddSeconds(-dtTaskCreatedOn.Second);

DateTime dtTaskModifiedOn = (DateTime)(entity["task.modifiedon"] as AliasedValue).Value;
dtTaskModifiedOn = dtTaskModifiedOn.AddSeconds(-dtTaskModifiedOn.Second);

activityModified = dtTaskCreatedOn == dtTaskModifiedOn ? false : true;
break;
case "phonecall":
ActivitySourceCode = entity.Contains("phonecall.new_activitysource") ? (OptionSetValue)(entity["phonecall.new_activitysource"] as AliasedValue).Value : new OptionSetValue();

DateTime dtPhonecallCreatedOn = (DateTime)(entity["phonecall.createdon"] as AliasedValue).Value;
dtPhonecallCreatedOn = dtPhonecallCreatedOn.AddSeconds(-dtPhonecallCreatedOn.Second);

DateTime dtPhonecallModifiedOn = (DateTime)(entity["phonecall.modifiedon"] as AliasedValue).Value;
dtPhonecallModifiedOn = dtPhonecallModifiedOn.AddSeconds(-dtPhonecallModifiedOn.Second);

activityModified = dtPhonecallCreatedOn == dtPhonecallModifiedOn ? false : true;
break;
case "email":
ActivitySourceCode = entity.Contains("email.new_activitysource") ? (OptionSetValue)(entity["email.new_activitysource"] as AliasedValue).Value : new OptionSetValue();

DateTime dtEmailCreatedOn = (DateTime)(entity["email.createdon"] as AliasedValue).Value;
dtEmailCreatedOn = dtEmailCreatedOn.AddSeconds(-dtEmailCreatedOn.Second);

DateTime dtEmailModifiedOn = (DateTime)(entity["email.modifiedon"] as AliasedValue).Value;
dtEmailModifiedOn = dtEmailModifiedOn.AddSeconds(-dtEmailModifiedOn.Second);

activityModified = dtEmailCreatedOn == dtEmailModifiedOn ? false : true;
break;
case "fax":
ActivitySourceCode = entity.Contains("fax.new_activitysource") ? (OptionSetValue)(entity["fax.new_activitysource"] as AliasedValue).Value : new OptionSetValue();

DateTime dtFaxCreatedOn = (DateTime)(entity["fax.createdon"] as AliasedValue).Value;
dtFaxCreatedOn = dtFaxCreatedOn.AddSeconds(-dtFaxCreatedOn.Second);

DateTime dtFaxModifiedOn = (DateTime)(entity["fax.modifiedon"] as AliasedValue).Value;
dtFaxModifiedOn = dtFaxModifiedOn.AddSeconds(-dtFaxModifiedOn.Second);

activityModified = dtFaxCreatedOn == dtFaxModifiedOn ? false : true;
break;
case "letter":
ActivitySourceCode = entity.Contains("letter.new_activitysource") ? (OptionSetValue)(entity["letter.new_activitysource"] as AliasedValue).Value : new OptionSetValue();

DateTime dtLetterCreatedOn = (DateTime)(entity["letter.createdon"] as AliasedValue).Value;
dtLetterCreatedOn = dtLetterCreatedOn.AddSeconds(-dtLetterCreatedOn.Second);

DateTime dtLetterModifiedOn = (DateTime)(entity["letter.modifiedon"] as AliasedValue).Value;
dtLetterModifiedOn = dtLetterModifiedOn.AddSeconds(-dtLetterModifiedOn.Second);

activityModified = dtLetterCreatedOn == dtLetterModifiedOn ? false : true;
break;
case "appointment":
ActivitySourceCode = entity.Contains("appointment.new_activitysource") ? (OptionSetValue)(entity["appointment.new_activitysource"] as AliasedValue).Value : new OptionSetValue();

DateTime dtAppointmentCreatedOn = (DateTime)(entity["appointment.createdon"] as AliasedValue).Value;
dtAppointmentCreatedOn = dtAppointmentCreatedOn.AddSeconds(-dtAppointmentCreatedOn.Second);

DateTime dtAppointmentModifiedOn = (DateTime)(entity["appointment.modifiedon"] as AliasedValue).Value;
dtAppointmentModifiedOn = dtAppointmentModifiedOn.AddSeconds(-dtAppointmentModifiedOn.Second);

activityModified = dtAppointmentCreatedOn == dtAppointmentModifiedOn ? false : true;
break;
}
}
}
catch(Exception ex)
{
if (ccContext != null)
{
ccContext.WriteException(ex.Message, ex);

var data = new SL.LogData
{
ErrorObject = ex,
LogName = "****************",
Severity = SL.LogLevel.Error,
Message = ex.Message
};
ccContext.WriteSplunkLog(data);
}
}
return activitySource = ActivitySourceCode.Value.ToString() + "," + activityModified;
}
}

}