Beispiel #1
0
        private static void AddOptionSetValueNames <T>(LocalCrmDatabaseInfo info, T entity, EntityProperties properties) where T : Entity
        {
            foreach (var osvAttribute in entity.Attributes.Where(a => a.Value is OptionSetValue || (a.Value as AliasedValue)?.Value is OptionSetValue))
            {
                PropertyInfo property;
                if (osvAttribute.Key == Email.Fields.StateCode)
                {
                    property = properties.GetProperty(osvAttribute.Key);
                }
                else if (!properties.PropertiesByLowerCaseName.TryGetValue(osvAttribute.Key + "enum", out var lowerCaseProperties))
                {
                    if (!(osvAttribute.Value is AliasedValue aliased))
                    {
                        continue;
                    }

                    // Handle Aliased Value
                    var aliasedDictionary = PropertiesCache.For(info, aliased.EntityLogicalName).PropertiesByLowerCaseName;
                    if (!aliasedDictionary.TryGetValue(aliased.AttributeLogicalName + "enum", out lowerCaseProperties))
                    {
                        continue;
                    }

                    property = lowerCaseProperties.First(p => p.PropertyType.GenericTypeArguments.Length >= 1);
                    entity.FormattedValues.Add(osvAttribute.Key, Enum.ToObject(property.PropertyType.GenericTypeArguments[0], ((OptionSetValue)aliased.Value).Value).ToString());
                    continue;
                }
                else
                {
                    property = lowerCaseProperties.First(p => p.PropertyType.GenericTypeArguments.Length >= 1);
                }

                entity.FormattedValues.Add(osvAttribute.Key, property.GetValue(entity).ToString());
            }
        }
Beispiel #2
0
        // ReSharper disable once UnusedMember.Local
        private static IQueryable <TRoot> ChildJoin <TRoot, TFrom, TTo>(LocalCrmDatabaseInfo info, IQueryable <LinkEntityTypes <TRoot, TFrom> > query, LinkEntity link)
            where TRoot : Entity
            where TFrom : Entity
            where TTo : Entity
        {
            IQueryable <LinkEntityTypes <TRoot, TTo> > result;

            if (link.JoinOperator == JoinOperator.Inner)
            {
                result = from f in query
                         join t in SchemaGetOrCreate <TTo>(info).AsQueryable() on ConvertCrmTypeToBasicComparable(f.Current, link.LinkFromAttributeName) equals
                         ConvertCrmTypeToBasicComparable(t, link.LinkToAttributeName)
                         select new LinkEntityTypes <TRoot, TTo>(f.Root, t, link.EntityAlias);
            }
            else
            {
                result = from f in query
                         join t in SchemaGetOrCreate <TTo>(info).AsQueryable() on ConvertCrmTypeToBasicComparable(f.Current, link.LinkFromAttributeName) equals
                         ConvertCrmTypeToBasicComparable(t, link.LinkToAttributeName) into joinResult
                         from t in joinResult.DefaultIfEmpty()
                         select new LinkEntityTypes <TRoot, TTo>(f.Root, t, link.EntityAlias);
            }

            // Apply any Conditions on the Link Entity
            result = ApplyLinkFilter(result, link.LinkCriteria);

            return(link.LinkEntities.Aggregate(result.Select(e => AddAliasedColumns(e.Root, e.Current, e.Alias, link.Columns)),
                                               (current, childLink) => current.Intersect(CallChildJoin(info, result, childLink))));
        }
Beispiel #3
0
        private static LocalCrmDatabase GetDatabaseForService(LocalCrmDatabaseInfo info)
        {
            LocalCrmDatabase db;

            if (info.DatabaseName == null)
            {
                db = Default;
            }
            else
            {
                // ReSharper disable once InconsistentlySynchronizedField
                if (Databases.TryGetValue(info.DatabaseName, out db))
                {
                    return(db);
                }
                lock (DatabaseCreationLock)
                {
                    if (Databases.TryGetValue(info.DatabaseName, out db))
                    {
                        return(db);
                    }
                    db = new LocalCrmDatabase();
                    Databases.AddOrUpdate(info.DatabaseName, db, (s, d) => { throw new Exception("Lock Failed Creating Database!"); });
                }
            }
            return(db);
        }
Beispiel #4
0
 public LocalCrmDatabaseOrganizationService(LocalCrmDatabaseInfo info)
 {
     if (info == null)
     {
         throw new ArgumentNullException("info");
     }
     Info = info;
 }
Beispiel #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocalCrmDatabaseOrganizationService"/> class.
 /// </summary>
 /// <param name="info">The info object.</param>
 /// <exception cref="System.ArgumentNullException"></exception>
 public LocalCrmDatabaseOrganizationService(LocalCrmDatabaseInfo info)
 {
     if (info == null)
     {
         throw new ArgumentNullException(nameof(info));
     }
     Info = info;
     CreateRequiredEntitiesIfNeeded();
 }
Beispiel #6
0
 internal static Type GetType(LocalCrmDatabaseInfo info, string logicalName)
 {
     try
     {
         return(EntityHelper.GetType(info.EarlyBoundEntityAssembly, info.EarlyBoundNamespace, logicalName));
     }
     catch (Exception ex)
     {
         throw new Exception($"Entity with logical name '{logicalName}' was not found in '{info.EarlyBoundNamespace}' namespace of assembly '{info.EarlyBoundEntityAssembly}'.", ex);
     }
 }
Beispiel #7
0
        private static void PopulateFormattedValues <T>(LocalCrmDatabaseInfo info, T entity) where T : Entity
        {
            // TODO: Handle Names?
            if (!entity.Attributes.Values.Any(HasFormattedAttribute))
            {
                return;
            }
            var properties = PropertiesCache.For <T>();

            AddOptionSetValueNames(info, entity, properties);
            AddMoneyAndDateFormattedValues(entity);
        }
Beispiel #8
0
 private static IQueryable <T> CallJoin <T>(LocalCrmDatabaseInfo service, IQueryable <T> query, LinkEntity link) where T : Entity
 {
     try
     {
         var tFrom = typeof(T);
         var tTo   = EntityHelper.GetType(tFrom.Assembly, tFrom.Namespace, link.LinkToEntityName);
         return((IQueryable <T>) typeof(LocalCrmDatabase).GetMethod("Join", BindingFlags.NonPublic | BindingFlags.Static).
                MakeGenericMethod(tFrom, tTo).Invoke(null, new object[] { service, query, link }));
     }
     catch (TargetInvocationException ex)
     {
         throw ex.InnerException;
     }
 }
        private static void PopulateFormattedValues <T>(LocalCrmDatabaseInfo info, Entity entity) where T : Entity
        {
            // TODO: Handle Names?
            if (!entity.Attributes.Values.Any(HasFormattedAttribute))
            {
                return;
            }
            var type       = typeof(T);
            var properties = PropertiesCache.For <T>();

            foreach (var osvAttribute in entity.Attributes.Where(a => a.Value is OptionSetValue || (a.Value as AliasedValue)?.Value is OptionSetValue))
            {
                PropertyInfo property;
                if (osvAttribute.Key == Email.Fields.StateCode)
                {
                    property = properties.GetProperty(osvAttribute.Key);
                }
                else if (!properties.PropertiesByLowerCaseName.TryGetValue(osvAttribute.Key + "enum", out property))
                {
                    if (!(osvAttribute.Value is AliasedValue aliased))
                    {
                        continue;
                    }
                    // Handle Aliased Value
                    var aliasedDictionary = PropertiesCache.For(info, type, aliased.EntityLogicalName).PropertiesByLowerCaseName;
                    if (!aliasedDictionary.TryGetValue(aliased.AttributeLogicalName + "enum", out property))
                    {
                        continue;
                    }
                    entity.FormattedValues.Add(osvAttribute.Key, Enum.ToObject(property.PropertyType.GenericTypeArguments[0], ((OptionSetValue)aliased.Value).Value).ToString());
                    continue;
                }
                entity.FormattedValues.Add(osvAttribute.Key, property.GetValue(entity).ToString());
            }
            foreach (var stringyAttribute in entity.Attributes.Where(a => !(a.Value is OptionSetValue) &&
                                                                     !((a.Value as AliasedValue)?.Value is OptionSetValue) &&
                                                                     HasFormattedAttribute(a.Value)))
            {
                var att = (stringyAttribute.Value as AliasedValue)?.Value ?? stringyAttribute.Value;
                if (att is Money)
                {
                    att = (att as Money).Value.ToString("C", CultureInfo.CurrentCulture);
                }
                if (att is DateTime)
                {
                    att = ((DateTime)att).ToString("g");
                }
                entity.FormattedValues.Add(stringyAttribute.Key, att.ToString());
            }
        }
        private static IQueryable <TRoot> CallChildJoin <TRoot, TFrom>(LocalCrmDatabaseInfo info, IQueryable <TRoot> query, LinkEntity fromEntity, LinkEntity link)
            where TRoot : Entity
            where TFrom : Entity
        {
            var tRoot = typeof(TRoot);
            var tTo   = GetType(info, link.LinkToEntityName);

            return((IQueryable <TRoot>)GenericMethodCaller.InvokeLocalCrmDatabaseStaticMultiGenericMethod(
                       info,
                       nameof(ChildJoin),
                       BindingFlags.NonPublic,
                       new object[] { tRoot, typeof(TFrom), tTo },
                       info, query, fromEntity, link));
        }
        private static string GetFullName(LocalCrmDatabaseInfo info, string firstName, string middleName, string lastName)
        {
            var fullNameFormat = RemoveEmptyPartsFromFormat(firstName, middleName, lastName, info.FullNameFormat);

            fullNameFormat = fullNameFormat.Replace("F", "{0}");
            fullNameFormat = fullNameFormat.Replace("L", "{1}");
            fullNameFormat = fullNameFormat.Replace("M", "{2}");
            fullNameFormat = fullNameFormat.Replace("I", "{3}");

            return(string.Format(fullNameFormat,
                                 (firstName ?? "").Trim(),
                                 (lastName ?? "").Trim(),
                                 (middleName ?? "").Trim(),
                                 ((middleName ?? " ").Trim() + " ")[0]));
        }
Beispiel #12
0
 private static IQueryable <TRoot> CallChildJoin <TRoot, TFrom>(LocalCrmDatabaseInfo info, IQueryable <LinkEntityTypes <TRoot, TFrom> > query, LinkEntity link)
     where TRoot : Entity
     where TFrom : Entity
 {
     try
     {
         var tRoot = typeof(TRoot);
         var tTo   = EntityHelper.GetType(tRoot.Assembly, tRoot.Namespace, link.LinkToEntityName);
         return((IQueryable <TRoot>) typeof(LocalCrmDatabase).GetMethod("ChildJoin", BindingFlags.NonPublic | BindingFlags.Static)
                .MakeGenericMethod(tRoot, typeof(TFrom), tTo)
                .Invoke(null, new object[] { info, query, link }));
     }
     catch (TargetInvocationException ex)
     {
         throw ex.InnerException;
     }
 }
 private static IQueryable <T> CallJoin <T>(LocalCrmDatabaseInfo info, IQueryable <T> query, LinkEntity link) where T : Entity
 {
     try
     {
         var tFrom = typeof(T);
         var tTo   = GetType(info, link.LinkToEntityName);
         return((IQueryable <T>) typeof(LocalCrmDatabase).GetMethod("Join", BindingFlags.NonPublic | BindingFlags.Static)?.
                MakeGenericMethod(tFrom, tTo).Invoke(null, new object[] { info, query, link }));
     }
     catch (TargetInvocationException ex)
     {
         if (ex.InnerException == null)
         {
             throw;
         }
         throw ex.InnerException;
     }
 }
        // ReSharper disable once UnusedMember.Local
        private static IQueryable <TFrom> Join <TFrom, TTo>(LocalCrmDatabaseInfo info, IQueryable <TFrom> query, LinkEntity link)
            where TFrom : Entity
            where TTo : Entity
        {
            IQueryable <LinkEntityTypes <TFrom, TTo> > result;

            if (link.JoinOperator == JoinOperator.Inner)
            {
                result = from f in query
                         join t in SchemaGetOrCreate <TTo>(info).AsQueryable() on ConvertCrmTypeToBasicComparable(f, link.LinkFromAttributeName) equals ConvertCrmTypeToBasicComparable(t, link.LinkToAttributeName)
                         select new LinkEntityTypes <TFrom, TTo>(AddAliasedColumns(f, t, link), t);

                // Apply any Conditions on the Link Entity
                result = ApplyLinkFilter(result, link.LinkCriteria);
            }
            else
            {
                result = from f in query
                         join t in SchemaGetOrCreate <TTo>(info).AsQueryable() on
                         new
                {
                    Id = ConvertCrmTypeToBasicComparable(f, link.LinkFromAttributeName),
                    FilterConditions = true
                }
                equals
                new
                {
                    Id = ConvertCrmTypeToBasicComparable(t, link.LinkToAttributeName),
                    FilterConditions = EvaluateFilter(t, link.LinkCriteria)
                }
                into joinResult
                from t in joinResult.DefaultIfEmpty()
                select new LinkEntityTypes <TFrom, TTo>(AddAliasedColumns(f, t, link), t);
            }

            var root = result.Select(r => r.Root);

            foreach (var entity in link.LinkEntities)
            {
                root = CallChildJoin <TFrom, TTo>(info, root, link, entity);
            }

            return(root);
        }
        private static ITable <T> SchemaGetOrCreate <T>(LocalCrmDatabaseInfo info) where T : Entity
        {
            var db          = GetDatabaseForService(info);
            var logicalName = EntityHelper.GetEntityLogicalName <T>();

            if (db._tables.TryGetValue(logicalName, out ITable table))
            {
                return((ITable <T>)table);
            }
            table = db.Tables.Create <T, Guid>(e => e.Id, null);
            if (db._tables.TryAdd(logicalName, table))
            {
                return((ITable <T>)table);
            }

            if (!db._tables.TryGetValue(logicalName, out table))
            {
                throw new Exception("Could Not Create Table " + EntityHelper.GetEntityLogicalName <T>());
            }
            return((ITable <T>)table);
        }
        // ReSharper disable once UnusedMember.Local
        private static IQueryable <TRoot> ChildJoin <TRoot, TFrom, TTo>(LocalCrmDatabaseInfo info, IQueryable <TRoot> query, LinkEntity fromEntity, LinkEntity link)
            where TRoot : Entity
            where TFrom : Entity
            where TTo : Entity
        {
            IQueryable <LinkEntityTypes <TRoot, TTo> > result;
            var fromName = JoinAliasEntityPreFix + fromEntity.EntityAlias;

            if (link.JoinOperator == JoinOperator.Inner)
            {
                result = from f in query
                         join t in SchemaGetOrCreate <TTo>(info).AsQueryable()
                         on ConvertCrmTypeToBasicComparable((TFrom)f[fromName], link.LinkFromAttributeName) equals
                         ConvertCrmTypeToBasicComparable(t, link.LinkToAttributeName)
                         select new LinkEntityTypes <TRoot, TTo>(AddAliasedColumns(f, t, link), t);
            }
            else
            {
                result = from f in query
                         join t in SchemaGetOrCreate <TTo>(info).AsQueryable() on ConvertCrmTypeToBasicComparable((TFrom)f[fromName], link.LinkFromAttributeName) equals
                         ConvertCrmTypeToBasicComparable(t, link.LinkToAttributeName) into joinResult
                         from t in joinResult.DefaultIfEmpty()
                         select new LinkEntityTypes <TRoot, TTo>(AddAliasedColumns(f, t, link), t);
            }

            // Apply any Conditions on the Link Entity
            result = ApplyLinkFilter(result, link.LinkCriteria);

            var root = result.Select(r => r.Root);

            foreach (var entity in link.LinkEntities)
            {
                root = CallChildJoin <TRoot, TTo>(info, root, link, entity);
            }

            return(root);

            //return link.LinkEntities.Aggregate(result.Select(e => AddAliasedColumns(e.Root, e.Current, e.Alias, link.Columns)),
            //                                   (current, childLink) => current.Intersect(CallChildJoin(info, result, childLink)));
        }
        private static IQueryable <T> CallJoin <T>(LocalCrmDatabaseInfo info, IQueryable <T> query, LinkEntity link) where T : Entity
        {
            try
            {
                var tFrom = typeof(T);
                var tTo   = GetType(info, link.LinkToEntityName);
                return((IQueryable <T>)GenericMethodCaller.InvokeLocalCrmDatabaseStaticMultiGenericMethod(
                           info,
                           nameof(Join),
                           BindingFlags.NonPublic,
                           new object[] { tFrom, tTo },
                           info, query, link));
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException == null)
                {
                    throw;
                }

                throw ex.InnerException;
            }
        }
        internal static object InvokeLocalCrmDatabaseStaticMultiGenericMethod(LocalCrmDatabaseInfo info, string methodName, BindingFlags bindingFlags, object[] typesOrLogicalNames, params object[] parameters)
        {
            var types = new Type[typesOrLogicalNames.Length];

            for (var i = 0; i < typesOrLogicalNames.Length; i++)
            {
                types[i] = typesOrLogicalNames[i] is string
                           ?LocalCrmDatabase.GetType(info, (string)typesOrLogicalNames[i])
                               : (Type)typesOrLogicalNames[i];
            }

            try
            {
                return(typeof(LocalCrmDatabase).GetMethods(bindingFlags | BindingFlags.Static)
                       .FirstOrDefault(m => m.Name == methodName && m.IsGenericMethod)
                       ?.MakeGenericMethod(types)
                       .Invoke(null, parameters));
            }
            catch (TargetInvocationException ex)
            {
                ThrowInnerException(ex);
                throw new Exception("Throw InnerException didn't throw exception");
            }
        }
 /// <summary>
 /// Creates the organization service.
 /// </summary>
 /// <param name="info">The information.</param>
 /// <returns></returns>
 public static LocalCrmDatabaseOrganizationService CreateOrganizationService(LocalCrmDatabaseInfo info)
 {
     return(new LocalCrmDatabaseOrganizationService(info));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="LocalCrmDatabaseOrganizationService"/> class.
 /// </summary>
 /// <param name="info">The info object.</param>
 /// <exception cref="System.ArgumentNullException"></exception>
 public LocalCrmDatabaseOrganizationService(LocalCrmDatabaseInfo info)
 {
     Info = info ?? throw new ArgumentNullException(nameof(info));
     EnforceValidForOperationCheck = true;
     CreateRequiredEntitiesIfNeeded();
 }
 /// <summary>
 /// Creates the organization service.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 public static LocalCrmDatabaseOrganizationService CreateOrganizationService <T>()
     where T : OrganizationServiceContext
 {
     return(new LocalCrmDatabaseOrganizationService(LocalCrmDatabaseInfo.Create <T>()));
 }
 internal static object InvokeLocalCrmDatabaseStaticGenericMethod(LocalCrmDatabaseInfo info, string logicalName, string methodName, BindingFlags bindingFlags, params object[] parameters)
 {
     return(InvokeLocalCrmDatabaseStaticMultiGenericMethod(info, methodName, bindingFlags, new object[] { logicalName }, parameters));
 }
Beispiel #23
0
 private static T GetDatabaseEntity <T>(LocalCrmDatabaseInfo info, Guid id) where T : Entity
 {
     return(SchemaGetOrCreate <T>(info).Where("Id == @0", id).FirstOrDefault());
 }
Beispiel #24
0
 private static Entity GetDatabaseEntity(LocalCrmDatabaseInfo info, string logicalName, Guid id)
 {
     return((Entity)GenericMethodCaller.InvokeLocalCrmDatabaseStaticGenericMethod(info, logicalName, nameof(GetDatabaseEntity), BindingFlags.NonPublic | BindingFlags.Static, info, id));
 }
 internal static Entity InvokeToEntity(Entity entity, LocalCrmDatabaseInfo info)
 {
     return(InvokeToEntity(entity, LocalCrmDatabase.GetType(info, entity.LogicalName)));
 }
 private static void PopulateModifiedAttributes <T>(LocalCrmDatabaseInfo info, T entity, EntityProperties properties) where T : Entity
 {
     ConditionallyAddValue(entity, properties, Email.Fields.ModifiedBy, info.User, info.User.GetIdOrDefault() != Guid.Empty);
     ConditionallyAddValue(entity, properties, Email.Fields.ModifiedOnBehalfBy, info.UserOnBehalfOf, info.UserOnBehalfOf.GetIdOrDefault() != Guid.Empty);
     ConditionallyAddValue(entity, properties, Email.Fields.ModifiedOn, DateTime.UtcNow);
 }
 public EntityProperties For(LocalCrmDatabaseInfo info, Type type, string logicalName)
 {
     return(For(LocalCrmDatabase.GetType(info, logicalName)));
 }
Beispiel #28
0
 public static LocalCrmDatabaseOrganizationService CreateOrganizationService <T>(LocalCrmDatabaseInfo info = null)
     where T : OrganizationServiceContext
 {
     info = info ?? LocalCrmDatabaseInfo.Create <T>();
     return(new LocalCrmDatabaseOrganizationService(info));
 }
 internal static Type GetType(LocalCrmDatabaseInfo info, string logicalName)
 {
     return(EntityHelper.GetType(info.EarlyBoundEntityAssembly, info.EarlyBoundNamespace, logicalName));
 }
 internal static Type GetType(LocalCrmDatabaseInfo info, string logicalName)
 {
     return(_n2NAssociations.TryGetValue(logicalName, out var value)
         ? value.AssociationType
         : EntityHelper.GetType(info.EarlyBoundEntityAssembly, info.EarlyBoundNamespace, logicalName));
 }