public EntityCollection RetrieveMultiple(QueryBase queryBase) { ThrowExceptionIfDisposed(); try { if (queryBase is QueryExpression query) { Dictionary <string, string> aliases = GetAliases(query); query.ColumnSet = FilterColumns(query.EntityName, query.ColumnSet); FilterFilterExpression(query.EntityName, query.Criteria, aliases); FilterLinkEntities(query.LinkEntities, aliases); FilterOrders(query.EntityName, query.Orders); } return(_serviceProxy.RetrieveMultiple(queryBase)); } catch (Exception ex) { var serializer = new DataContractSerializer(queryBase.GetType()); string serializeString = GetSerializedString(serializer, queryBase); Helpers.DTEHelper.WriteExceptionToLog(ex, $"OrganizationServiceExtentedProxy.RetrieveMultiple{Environment.NewLine}{serializeString}"); throw; } }
private string GetDetailedMessage(QueryBase query) { string message; switch (query) { case QueryExpression qe: message = $"Query Expression: {qe.GetSqlStatement()}"; break; case FetchExpression fe: message = $"Fetch Expression: {fe.Query}"; break; case QueryByAttribute ba: message = $"Query By Attribute for {ba.EntityName} with attributes {string.Join(", ", ba.Attributes)} and values {string.Join(", ", ba.Values)} and Columns {string.Join(", ", ba.ColumnSet.Columns)}"; break; default: message = $"Unknown Query Base {query.GetType().FullName}"; break; } return(message); }
public async Task <TResponse> ExecuteQueryAsync <TResponse>(QueryBase <TResponse> query) where TResponse : ResponseBase { Type queryType = query.GetType(); object result = await queryHandlers[queryType].HandleAsync((dynamic)query); return((TResponse)result); }
// TODO: Rename private static QueryBase SetProperty(QueryBase query, object value, string propertyName) { var property = query.GetType().GetProperty(propertyName); property.SetValue(query, value); return(query); }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecuteGetSiteMap(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } Entity output = new Entity("webresource"); IOrganizationService service = localContext.OrganizationService; ITracingService trace = localContext.TracingService; // Exract the search criteria QueryBase query = (QueryBase)localContext.PluginExecutionContext.InputParameters["Query"]; Type queryType = query.GetType(); if (queryType == typeof(QueryExpression)) { trace.Trace("Found QueryExpression"); // Get condition QueryExpression queryExpression = (QueryExpression)query; if (queryExpression.EntityName != "webresource") { return; } if (queryExpression.Criteria == null || queryExpression.Criteria.Conditions.Count != 1 || queryExpression.Criteria.Conditions[0].AttributeName != "name") { return; } string webresourceName = (string)queryExpression.Criteria.Conditions[0].Values[0]; if ((webresourceName.Length > SiteMapResourceName.Length + 3) && webresourceName.StartsWith(SiteMapResourceName) && webresourceName.EndsWith(".js")) { string lcid = webresourceName.Substring(16); lcid = lcid.Substring(0, lcid.Length - 3); trace.Trace("LCID={0}", lcid); var outputCollection = (EntityCollection)localContext.PluginExecutionContext.OutputParameters["BusinessEntityCollection"]; SiteMapLoader siteMap = new SiteMapLoader(int.Parse(lcid)); StringWriter json = new StringWriter(); siteMap.ParseSiteMapToJson(service, trace, json); var scriptBytes = System.Text.Encoding.UTF8.GetBytes(json.ToString()); trace.Trace("Parsed Sit Map OK"); output["name"] = webresourceName; output["content"] = System.Convert.ToBase64String(scriptBytes); output["webresourcetype"] = new OptionSetValue(3); outputCollection.Entities.Clear(); outputCollection.Entities.Add(output); } } }
private bool IsEnumInRange(QueryBase obj) { var propertyInfo = GetPropertyInfo("Operand", obj.GetType()); if (propertyInfo == null) { return(true); } var maxValue = Enum.GetValues(propertyInfo.PropertyType).Length; var value = (int)(propertyInfo.GetValue(obj)); return(0 <= value && value < maxValue); }
/// <summary> /// Retrieves all pages for a given query /// </summary> public static EntityCollection RetrieveMultipleAllPages(this IOrganizationService service, QueryBase query) { if (null == service) { throw new ArgumentNullException("service"); } else if (null == query) { throw new ArgumentNullException("query"); } var fullResults = service.RetrieveMultiple(query); if (!fullResults.MoreRecords) { return(fullResults); } var property = query.GetType().GetProperty("PageInfo"); if (null == property) { throw new NotSupportedException("The specified query object does not have a PageInfo property defined."); } var paging = new PagingInfo() { PageNumber = 1, ReturnTotalRecordCount = false }; property.SetValue(query, paging, null); var results = fullResults; while (results.MoreRecords) { //Update the paging information paging.PagingCookie = results.PagingCookie; paging.PageNumber++; //Retrieve the next page results = service.RetrieveMultiple(query); //Add the results to the full list fullResults.Entities.AddRange(results.Entities); } return(fullResults); }
public TResult Execute <TResult>(QueryBase <TResult> queryBase) { var handlerType = typeof(IQueryHandler <,>).MakeGenericType(queryBase.GetType(), typeof(TResult)); dynamic handler = _container.GetInstance(handlerType); try { return(handler.Handle((dynamic)queryBase)); } catch (Exception) { throw; } }
public static EntityCollection RetrieveMultiple(this LocalPluginContext local, QueryBase query) { local.Trace($"Internal RM {query.GetType()}"); if (query is QueryExpression qx) { local.Trace($"Querying entity {qx.EntityName}"); local.Trace($"Attributes: {string.Join(", ", qx.ColumnSet.Columns)}"); } var sw = Stopwatch.StartNew(); var result = local.OrganizationService.RetrieveMultiple(query); sw.Stop(); local.Trace($"Returning {result.Entities.Count} records after {sw.ElapsedMilliseconds} ms"); return(result); }
/// <summary> /// 转化QueryString /// </summary> /// <param name="query"></param> /// <returns></returns> public static string QueryStringFormat(this QueryBase query) { var queryStringBuilder = new StringBuilder(); if (query == null) { return(null); } foreach (var propInfo in query.GetType().GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance)) { var propertyValue = propInfo.GetValue(query, null); if (propertyValue == null || string.IsNullOrEmpty(propertyValue.ToString())) { continue; } queryStringBuilder.Append($"{propInfo.Name}={propertyValue}&"); } return(queryStringBuilder.ToString().TrimEnd('&')); }
internal static string Trace(QueryBase queryBase) { if (queryBase == null) { return(Environment.NewLine); } if (queryBase is QueryExpression) { return(Trace((QueryExpression)queryBase)); } else if (queryBase is FetchExpression) { return(Trace((FetchExpression)queryBase)); } else if (queryBase is QueryByAttribute) { return(Trace((QueryByAttribute)queryBase)); } else { return(queryBase.GetType().Name); } }
private EntityCollection RetrieveMultipleInternal(QueryBase query) { throw new NotImplementedException("Retrieve Multiple for Query Base Type " + query.GetType().FullName + " not Impemented"); }
public List <Entity> QueryWithPaging(QueryBase query) { var results = new List <Entity>(); var initialFetchXml = string.Empty; var pageNumber = 1; if (query is QueryByAttribute) { ((QueryByAttribute)query).PageInfo = new PagingInfo() { Count = 500, PageNumber = 1 } } ; else if (query is QueryExpression) { ((QueryExpression)query).PageInfo = new PagingInfo() { Count = 500, PageNumber = 1 } } ; else if (query is FetchExpression) { initialFetchXml = ((FetchExpression)query).Query; var fetchXml = CreateFetchXml(initialFetchXml, null, 1, 500); ((FetchExpression)query).Query = fetchXml; } else { throw new Exception($"Paging for {query.GetType().FullName} is not supported yet!"); } EntityCollection records; do { records = Context.UserService.RetrieveMultiple(query); results.AddRange(records.Entities); if (query is QueryByAttribute) { ((QueryByAttribute)query).PageInfo.PageNumber++; ((QueryByAttribute)query).PageInfo.PagingCookie = records.PagingCookie; } else if (query is QueryExpression) { ((QueryExpression)query).PageInfo.PageNumber++; ((QueryExpression)query).PageInfo.PagingCookie = records.PagingCookie; } else { pageNumber++; var fetchXml = CreateFetchXml(initialFetchXml, records.PagingCookie, pageNumber, 500); ((FetchExpression)query).Query = fetchXml; } } while (records.MoreRecords); return(results); }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecuteRetrieveMultiplePlugin(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } try { var service = localContext.OrganizationService; var trace = localContext.TracingService; // Check the depth - we don't want to run on child queries if (localContext.PluginExecutionContext.Depth > 1) { return; } // Exract the search criteria QueryBase query = (QueryBase)localContext.PluginExecutionContext.InputParameters["Query"]; Type queryType = query.GetType(); if (queryType == typeof(QueryExpression)) { var queryExpression = (QueryExpression)query; var webresourceName = GetMetadataRequestWebresourceName(queryExpression); if (webresourceName == null) { return; } // Get the requested LCID var lcidString = webresourceName.Substring(webresourceName.Length - 7, 4); int lcid = 0; if (!int.TryParse(lcidString, out lcid)) { return; } // Is there a webresource with this LCID in the system? var outputCollection = (EntityCollection)localContext.PluginExecutionContext.OutputParameters["BusinessEntityCollection"]; var templateEntity = outputCollection; if (outputCollection.Entities.Count == 0) { // No webresource found, so get the template resource file for the base language queryExpression.Criteria.Conditions[0].Values[0] = webresourceName.Replace("_" + lcid.ToString(), "_" + GetDefaultLCID(service).ToString()); templateEntity = service.RetrieveMultiple(query); if (templateEntity.Entities.Count != 1) { return; } } var templateData = System.Convert.FromBase64String(templateEntity.Entities[0].GetAttributeValue <string>("content")); var templateText = System.Text.Encoding.UTF8.GetString(templateData); var outputText = ParseTemplate(templateText, lcid, service); var scriptBytes = System.Text.Encoding.UTF8.GetBytes(outputText); Entity output = new Entity("webresource"); output["name"] = webresourceName; output["content"] = System.Convert.ToBase64String(scriptBytes); output["webresourcetype"] = new OptionSetValue(3); outputCollection.Entities.Clear(); outputCollection.Entities.Add(output); } } catch (Exception ex) { if (_unsecureconfig == "Debug") { throw new InvalidPluginExecutionException("Could not create metadata webresouces : " + ex.Message, ex); } } }
public static List <Entity> RetrieveAll(this IOrganizationService service, QueryBase query) { var results = new List <Entity>(); var initialFetchXml = string.Empty; var pageNumber = 1; switch (query) { case QueryByAttribute _: ((QueryByAttribute)query).PageInfo = new PagingInfo() { Count = 500, PageNumber = 1 }; break; case QueryExpression _: ((QueryExpression)query).PageInfo = new PagingInfo() { Count = 500, PageNumber = 1 }; break; case FetchExpression _: initialFetchXml = ((FetchExpression)query).Query; var fetchXml = CreateFetchXml(initialFetchXml, null, 1, 500); ((FetchExpression)query).Query = fetchXml; break; default: throw new Exception($"Paging for {query.GetType().FullName} is not supported yet!"); } EntityCollection records; do { records = service.RetrieveMultiple(query); results.AddRange(records.Entities); switch (query) { case QueryByAttribute _: ((QueryByAttribute)query).PageInfo.PageNumber++; ((QueryByAttribute)query).PageInfo.PagingCookie = records.PagingCookie; break; case QueryExpression _: ((QueryExpression)query).PageInfo.PageNumber++; ((QueryExpression)query).PageInfo.PagingCookie = records.PagingCookie; break; default: pageNumber++; var fetchXml = CreateFetchXml(initialFetchXml, records.PagingCookie, pageNumber, 500); ((FetchExpression)query).Query = fetchXml; break; } } while (records.MoreRecords); return(results); }