Ejemplo n.º 1
0
        private static void GetDependsOnWriteableDataStructure(DataStructureInfo dataStructure, List <DataStructureInfo> dependencies, IDslModel allConcepts, IConceptInfo errorContext, HashSet <string> done)
        {
            var conceptKey = dataStructure.GetKey();

            if (done.Contains(conceptKey))
            {
                return;
            }
            done.Add(conceptKey);

            if (dataStructure is EntityInfo)
            {
                dependencies.Add(dataStructure);
            }
            else if (dataStructure is SqlQueryableInfo)
            {
                var deps = allConcepts.FindByType <SqlDependsOnDataStructureInfo>().Where(dep => dep.Dependent == dataStructure).ToArray();
                foreach (var dep in deps)
                {
                    GetDependsOnWriteableDataStructure(dep.DependsOn, dependencies, allConcepts, errorContext, done);
                }
            }
            else
            {
                throw new DslSyntaxException(errorContext.GetKeywordOrTypeName()
                                             + " is not supported on dependency type '" + dataStructure.GetKeywordOrTypeName() + "'. "
                                             + errorContext.GetUserDescription() + " depends on " + dataStructure.GetUserDescription() + ".");
            }
        }
Ejemplo n.º 2
0
        private static string ServiceDefinitionCodeSnippet(DataStructureInfo info)
        {
            return string.Format(@"
            [System.ServiceModel.ServiceContract]
            [System.ServiceModel.Activation.AspNetCompatibilityRequirements(RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)]
            public class RestService{0}{1}
            {{
            private ServiceUtility _serviceUtility;

            public RestService{0}{1}(ServiceUtility serviceUtility)
            {{
            _serviceUtility = serviceUtility;
            }}

            [OperationContract]
            [WebGet(UriTemplate = ""/?parameter={{parameter}}&convertFormat={{convertFormat}}"", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
            public DownloadReportResult DownloadReport(string parameter, string convertFormat)
            {{
            return _serviceUtility.DownloadReport<{0}.{1}>(parameter, convertFormat);
            }}

            " + AdditionalOperationsTag.Evaluate(info) + @"
            }}

            ",
            info.Module.Name,
            info.Name);
        }
Ejemplo n.º 3
0
 public static void GenerateQueryableRepositoryFunctions(DataStructureInfo info, ICodeBuilder codeBuilder, string queryFunctionBody)
 {
     GenerateReadableRepositoryFunctions(info, codeBuilder, "return Query().ToArray();\r\n            ");
     codeBuilder.InsertCode(RepositoryQueryFunctionsSnippet(info, queryFunctionBody), RepositoryMembers, info);
     codeBuilder.InsertCode("IQueryableRepository<" + info.Module.Name + "." + info.Name + ">", RepositoryInterfaces, info);
     codeBuilder.InsertCode("IFilterRepository<IEnumerable<Guid>, " + info.Module.Name + "." + info.Name + ">", RepositoryInterfaces, info);
 }
        private static string ImplementationCodeSnippet(DataStructureInfo info)
        {
            string dataStructureBezBrowsea = info.Name;
            if (dataStructureBezBrowsea.ToLower().EndsWith("browse")) dataStructureBezBrowsea = dataStructureBezBrowsea.Substring(0, dataStructureBezBrowsea.Length - 6);

            return string.Format(@"
            namespace Omega.MvcModel.{0}
            {{
            [Rhetos.Mvc.LocalizedDisplayName(""{3}"", {4})]
            public partial class {1} : Rhetos.Mvc.BaseMvcModel
            {{
            public const string Entity{1} = ""{1}"";

            {2}
            }}
            }}

            ",
                info.Module.Name,
                info.Name,
                ClonePropertiesTag.Evaluate(info),
                CaptionHelper.GetCaptionConstant(info),
                "typeof(Captions)"
                );
        }
Ejemplo n.º 5
0
        private static string GetFilterExpression(FilterByBaseInfo info, DataStructureInfo baseDataStructure)
        {
            return string.Format(@"(repository, parameter) =>
            {{
                var baseDataSourceRepositiory = repository.{3}.{4} as IFilterRepository<{2}, {3}.{4}>;
                if (baseDataSourceRepositiory == null)
                {{
                    const string userDescription = {5};
                    throw new Rhetos.UserException(""Invalid use of "" + userDescription + "". Filter's base data source '{3}.{4}' does not implement a filter for '{2}'."");
                }}

                Guid[] references = baseDataSourceRepositiory.Filter(parameter).Select(item => item.ID).ToArray();
                {0}.{1}[] result = repository.{0}.{1}.Filter(references);

                Rhetos.Utilities.DirectedGraph.SortByGivenOrder(result, references, item => item.ID);
                return result;
            }}
            ",
            info.Source.Module.Name,
            info.Source.Name,
            info.Parameter,
            baseDataStructure.Module.Name,
            baseDataStructure.Name,
            CsUtility.QuotedString(info.GetUserDescription()));
        }
 public static bool IsSupported(DataStructureInfo conceptInfo)
 {
     return conceptInfo is IOrmDataStructure
         || conceptInfo is BrowseDataStructureInfo
         || conceptInfo is QueryableExtensionInfo
         || conceptInfo is ComputedInfo;
 }
Ejemplo n.º 7
0
        public static IEnumerable<IConceptInfo> GetAdditionalForeignKeyDependencies(DataStructureInfo dataStructure)
        {
            if (dataStructure is PolymorphicInfo)
                return new IConceptInfo[] { new PersistedDataStructureInfo { Module = dataStructure.Module, Name = dataStructure.Name + "_Materialized" } };

            return new IConceptInfo[] { };
        }
Ejemplo n.º 8
0
        public IEnumerable <IConceptInfo> CreateNewConcepts(FilterByBaseInfo conceptInfo, IDslModel existingConcepts)
        {
            DataStructureInfo baseDataStructure = GetBaseDataStructure(conceptInfo, existingConcepts);

            if (baseDataStructure == null)
            {
                return(null);
            }

            return(new IConceptInfo[]
            {
                new FilterByInfo
                {
                    Source = conceptInfo.Source,
                    Parameter = conceptInfo.Parameter,
                    Expression = GetFilterExpression(conceptInfo, baseDataStructure)
                },
                new ModuleExternalReferenceInfo
                {
                    Module = new ModuleInfo {
                        Name = conceptInfo.Source.Module.Name
                    },
                    TypeOrAssembly = typeof(DslUtility).AssemblyQualifiedName
                }
            });
        }
Ejemplo n.º 9
0
        /// <param name="allowSystemProperties">Allows path to end with a C# property that does not have a representation in the DSL model (ID property or the Guid property used for a Reference).</param>
        public static ValueOrError <PropertyInfo> GetPropertyByPath(DataStructureInfo source, string path, IDslModel existingConcepts, bool allowSystemProperties = true)
        {
            if (path.Contains(" "))
            {
                return(ValueOrError.CreateError("The path contains a space character."));
            }

            if (string.IsNullOrEmpty(path))
            {
                return(ValueOrError.CreateError("The path is empty."));
            }

            var propertyNames    = path.Split('.');
            var referenceNames   = propertyNames.Take(propertyNames.Count() - 1).ToArray();
            var lastPropertyName = propertyNames[propertyNames.Count() - 1];

            ValueOrError <DataStructureInfo> selectedDataStructure = source;

            foreach (var referenceName in referenceNames)
            {
                selectedDataStructure = NavigateToNextDataStructure(selectedDataStructure.Value, referenceName, existingConcepts);
                if (selectedDataStructure.IsError)
                {
                    return(ValueOrError.CreateError(selectedDataStructure.Error));
                }
            }

            PropertyInfo selectedProperty = FindProperty(existingConcepts, selectedDataStructure.Value, lastPropertyName);

            if (allowSystemProperties && selectedProperty == null && lastPropertyName == "ID")
            {
                return new GuidPropertyInfo {
                           DataStructure = selectedDataStructure.Value, Name = "ID"
                }
            }
            ;

            if (allowSystemProperties && selectedProperty == null && lastPropertyName.EndsWith("ID"))
            {
                string referenceName = lastPropertyName.Substring(0, lastPropertyName.Length - 2);

                var referencePrototype = new PropertyInfo {
                    DataStructure = selectedDataStructure.Value, Name = referenceName
                };
                if (existingConcepts.FindByKey(referencePrototype.GetKey()) != null)
                {
                    return new GuidPropertyInfo {
                               DataStructure = selectedDataStructure.Value, Name = lastPropertyName
                    }
                }
                ;
            }

            if (selectedProperty == null)
            {
                return(ValueOrError.CreateError("There is no property '" + lastPropertyName + "' on " + selectedDataStructure.Value.GetUserDescription() + "."));
            }

            return(selectedProperty);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Note: When using this function to create a database object, always add the dependencies from GetAdditionalForeignKeyDependencies().
        /// </summary>
        public static string GetSchemaTableForForeignKey(DataStructureInfo dataStructure)
        {
            if (dataStructure is EntityInfo)
            {
                return(SqlUtility.Identifier(dataStructure.Module.Name)
                       + "." + SqlUtility.Identifier(dataStructure.Name));
            }

            if (dataStructure is LegacyEntityInfo)
            {
                var legacy = (LegacyEntityInfo)dataStructure;
                return(SqlUtility.GetFullName(legacy.Table));
            }

            if (dataStructure is LegacyEntityWithAutoCreatedViewInfo)
            {
                var legacy = (LegacyEntityWithAutoCreatedViewInfo)dataStructure;
                return(SqlUtility.GetFullName(legacy.Table));
            }

            if (dataStructure is PolymorphicInfo)
            {
                return(dataStructure.GetKeyProperties() + "_Materialized");
            }

            return(null);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Returns a writable data structure that can be used to monitor data changes (intercepting its Save function), in order to update a persisted data.
        /// Returns empty array if a required data structure is not found.
        /// </summary>
        public static IEnumerable <DataStructureInfo> GetBaseChangesOnDependency(DataStructureInfo dependsOn, IDslModel existingConcepts)
        {
            if (dependsOn.Name.EndsWith("_History"))
            {
                var history = existingConcepts.FindByReference <EntityHistoryInfo>(h => h.Dependency_HistorySqlQueryable, dependsOn).SingleOrDefault();
                if (history != null)
                {
                    return new DataStructureInfo[] { history.Entity, history.Dependency_ChangesEntity }
                }
                ;
            }

            if (dependsOn is IWritableOrmDataStructure)
            {
                return new[] { dependsOn }
            }
            ;

            if (existingConcepts.FindByReference <WriteInfo>(write => write.DataStructure, dependsOn).Any())
            {
                return new[] { dependsOn }
            }
            ;

            var baseDataStructure = existingConcepts.FindByReference <DataStructureExtendsInfo>(ex => ex.Extension, dependsOn)
                                    .Select(ex => ex.Base).SingleOrDefault();

            if (baseDataStructure != null)
            {
                return(GetBaseChangesOnDependency(baseDataStructure, existingConcepts));
            }

            return(Enumerable.Empty <DataStructureInfo>());
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Returns all entities that a given data structure is constructed from.
        /// If the given data structure depends is an entity, it will be the only item in the result.
        /// </summary>
        public static List <DataStructureInfo> GetDependsOnWriteableDataStructure(DataStructureInfo dataStructure, IDslModel allConcepts, IConceptInfo errorContext)
        {
            var dependencies = new List <DataStructureInfo>();

            GetDependsOnWriteableDataStructure(dataStructure, dependencies, allConcepts, errorContext, new HashSet <string>());
            return(dependencies);
        }
Ejemplo n.º 13
0
 // TODO: Remove this hack after implementing repository concept and cleaner queryable data structure configuration.
 public static bool IsQueryable(DataStructureInfo dataStructure)
 {
     return(dataStructure is QueryableExtensionInfo ||
            dataStructure is BrowseDataStructureInfo ||
            dataStructure is ComputedInfo ||
            dataStructure is IOrmDataStructure);
 }
 public void InitializeNonparsableProperties(out IEnumerable <IConceptInfo> createdConcepts)
 {
     Referenced = new DataStructureInfo {
         Module = DataStructure.Module, Name = Name
     };
     createdConcepts = null;
 }
Ejemplo n.º 15
0
 private static string RegisterRepository(DataStructureInfo info)
 {
     return string.Format(
     @"builder.RegisterType<{0}._Helper.{1}_Repository>().Keyed<IRepository>(""{0}.{1}"").InstancePerLifetimeScope();
     ",
         info.Module.Name,
         info.Name);
 }
 public static bool IsEntityType(DataStructureInfo conceptInfo)
 {
     return conceptInfo is IOrmDataStructure
         || conceptInfo is BrowseDataStructureInfo
         || conceptInfo is QueryableExtensionInfo
         || conceptInfo is ComputedInfo
         || conceptInfo is ActionInfo; // TODO: Remove ActionInfo. It is here only for backward compatibility.
 }
Ejemplo n.º 17
0
 public static void CloneExtension(DataStructureInfo source, DataStructureInfo destination, IDslModel existingConcepts, List <IConceptInfo> newConcepts)
 {
     newConcepts.AddRange(
         existingConcepts.FindByType <DataStructureExtendsInfo>().Where(ci => ci.Extension == source)
         .Select(ci => new DataStructureExtendsInfo {
         Extension = destination, Base = ci.Base
     }));
 }
Ejemplo n.º 18
0
        private static string CallFromModuleRepostiorySnippet(DataStructureInfo info)
        {
            return string.Format(
            @"        private {0}_Repository _{0}_Repository;
            public {0}_Repository {0} {{ get {{ return _{0}_Repository ?? (_{0}_Repository = new {0}_Repository(_domRepository, _executionContext)); }} }}

            ", info.Name);
        }
Ejemplo n.º 19
0
        public void CheckSemantics(IDslModel existingConcepts)
        {
            DataStructureInfo baseDataStructure = GetBaseDataStructure(existingConcepts);

            if (baseDataStructure == null)
            {
                throw new DslSyntaxException("Invalid use of " + this.GetUserDescription() + ". Filter's data structure '" + Source.GetKeyProperties() + "' is not an extension of another base class.");
            }
        }
Ejemplo n.º 20
0
 public static string CreateComposableFilterSnippet(string permissionExpressionName, DataStructureInfo dataStructure)
 {
     return string.Format(
     @"(source, repository, parameter, context) =>
         {{
             var filterExpression = {0}(source, repository, context);
             return FilterExpression<Common.Queryable.{1}_{2}>.OptimizedWhere(source, filterExpression);
         }}", permissionExpressionName, dataStructure.Module.Name, dataStructure.Name);
 }
Ejemplo n.º 21
0
 public static void CheckIfSupported(DataStructureInfo dataStructure, IConceptInfo errorContext)
 {
     if (!IsSupported(dataStructure))
     {
         throw new DslSyntaxException(errorContext,
                                      $"SQL index can only be used in a writable data structure." +
                                      $" '{dataStructure}' is a '{dataStructure.GetType().Name}'.");
     }
 }
Ejemplo n.º 22
0
        public static void ValidatePath(DataStructureInfo source, string path, IDslModel existingConcepts, IConceptInfo errorContext)
        {
            var property = GetPropertyByPath(source, path, existingConcepts);

            if (property.IsError)
            {
                throw new DslSyntaxException(errorContext, "Invalid path: " + property.Error);
            }
        }
Ejemplo n.º 23
0
        private static ValueOrError <DataStructureInfo> NavigateToNextDataStructure(DataStructureInfo source, string referenceName, IDslModel existingConcepts)
        {
            var selectedProperty = FindProperty(existingConcepts, source, referenceName);

            IEnumerable <DataStructureExtendsInfo> allExtensions;

            allExtensions = existingConcepts.FindByType <DataStructureExtendsInfo>();

            if (selectedProperty == null && referenceName == "Base")
            {
                var baseDataStructure = allExtensions
                                        .Where(ex => ex.Extension == source)
                                        .Select(ex => ex.Base).SingleOrDefault();
                if (baseDataStructure != null)
                {
                    return(baseDataStructure);
                }

                if (selectedProperty == null)
                {
                    return(ValueOrError.CreateError("There is no property '" + referenceName + "' nor a base data structure on " + source.GetUserDescription() + "."));
                }
            }

            if (selectedProperty == null && referenceName.StartsWith("Extension_"))
            {
                string extensionName           = referenceName.Substring("Extension_".Length);
                var    extendsionDataStructure = allExtensions
                                                 .Where(ex => ex.Base == source)
                                                 .Where(ex => ex.Extension.Module == source.Module && ex.Extension.Name == extensionName ||
                                                        ex.Extension.Module.Name + "_" + ex.Extension.Name == extensionName)
                                                 .Select(ex => ex.Extension).SingleOrDefault();
                if (extendsionDataStructure != null)
                {
                    return(extendsionDataStructure);
                }

                if (selectedProperty == null)
                {
                    return(ValueOrError.CreateError("There is no property '" + referenceName + "' nor an extension '" + extensionName + "' on " + source.GetUserDescription() + "."));
                }
            }

            if (selectedProperty == null)
            {
                return(ValueOrError.CreateError("There is no property '" + referenceName + "' on " + source.GetUserDescription() + "."));
            }

            if (!(selectedProperty is ReferencePropertyInfo))
            {
                return(ValueOrError.CreateError(string.Format("Property {0} cannot be used in the path because it is '{1}'. Only Reference properties can be used in a path.",
                                                              selectedProperty.Name, selectedProperty.GetKeywordOrTypeName())));
            }

            return(((ReferencePropertyInfo)selectedProperty).Referenced);
        }
Ejemplo n.º 24
0
        private static string CallFromModuleRepostiorySnippet(DataStructureInfo info)
        {
            return string.Format(
        @"private {0}_Repository _{0}_Repository;
        public {0}_Repository {0} {{ get {{ return _{0}_Repository ?? (_{0}_Repository = ({0}_Repository)Rhetos.Extensibility.NamedPluginsExtensions.GetPlugin(_repositories, {1})); }} }}

        ",
                info.Name,
                CsUtility.QuotedString(info.Module.Name + "." + info.Name));
        }
Ejemplo n.º 25
0
        protected static string CodeSnippet(DataStructureInfo info)
        {
            return AttributesTag.Evaluate(info) + @"
            public partial class " + info.Name + InterfaceTag.Evaluate(info) + @"
            {
            " + BodyTag.Evaluate(info) + @"
            }

            ";
        }
Ejemplo n.º 26
0
 private string GenerateMapping(DataStructureInfo info)
 {
     return
     @"
     <class name=""{0}.{1}, " + NHibernateMappingGenerator.AssemblyTag + @""" schema=""{2}"" table=""{3}"">
     <id name=""ID"" />
     " + MembersTag.Evaluate(info) + @"
     </class>
     ";
 }
 public static bool IsTypeSupported(DataStructureInfo conceptInfo)
 {
     return conceptInfo is EntityInfo
         || conceptInfo is BrowseDataStructureInfo
         || conceptInfo is LegacyEntityInfo
         || conceptInfo is LegacyEntityWithAutoCreatedViewInfo
         || conceptInfo is SqlQueryableInfo
         || conceptInfo is QueryableExtensionInfo
         || conceptInfo is ComputedInfo;
 }
Ejemplo n.º 28
0
 public static void CheckIfPropertyBelongsToDataStructure(PropertyInfo property, DataStructureInfo dataStructure, IConceptInfo errorContext)
 {
     if (property.DataStructure != dataStructure)
         throw new Exception(String.Format(
             "Invalid use of " + errorContext.GetKeywordOrTypeName() + ": Property {0}.{1}.{2} is not in data structure {3}.{4}.",
             property.DataStructure.Module.Name,
             property.DataStructure.Name,
             property.Name,
             dataStructure.Module.Name,
             dataStructure.Name));
 }
Ejemplo n.º 29
0
        public static IEnumerable <IConceptInfo> GetAdditionalForeignKeyDependencies(DataStructureInfo dataStructure)
        {
            if (dataStructure is PolymorphicInfo)
            {
                return new IConceptInfo[] { new PersistedDataStructureInfo {
                                                Module = dataStructure.Module, Name = dataStructure.Name + "_Materialized"
                                            } }
            }
            ;

            return(new IConceptInfo[] { });
        }
    }
Ejemplo n.º 30
0
        private static string GetFilterExpression(FilterByBaseInfo info, DataStructureInfo baseDataStructure)
        {
            return($@"(repository, parameter) =>
            {{
                var baseRepositiory = repository.{baseDataStructure.FullName};
                Guid[] references = baseRepositiory.Filter(parameter).Select(item => item.ID).ToArray();
                {info.Source.FullName}[] result = repository.{info.Source.FullName}.Filter(references);

                Rhetos.Utilities.Graph.SortByGivenOrder(result, references, item => item.ID);
                return result;
            }}
");
        }
        private static string FilterOldItemsBeforeSaveSnippet(DataStructureInfo hookOnSaveEntity, string filterType, string filterFormula, string uniqueName)
        {
            return string.Format(
            @"Func<IEnumerable<Common.Queryable.{0}_{1}>, {2}> filterLoadKeepSynchronizedOnChangedItems{3} =
                {4};
            {2} filterKeepSynchronizedOnChangedItems{3}Old = filterLoadKeepSynchronizedOnChangedItems{3}(updated.Concat(deleted));

            ",
                hookOnSaveEntity.Module.Name,
                hookOnSaveEntity.Name,
                filterType,
                uniqueName,
                filterFormula);
        }
 private static string DataSourceExpositionCodeSnippet(DataStructureInfo info)
 {
     return string.Format(@"
     public IQueryable<Rhetos.OData.{0}.{1}> {0}{1}
     {{
     get
     {{
         return Rhetos.OData.{0}.{1}.Get{1}Queryable(_processingEngine);
     }}
     }}",
     info.Module.Name,
     info.Name,
     "_" + info.Module.Name.ToLower() + info.Name);
 }
        string RepositoryMemberSnippet(DataStructureInfo info)
        {
            return string.Format(
@"        // Claims in use should be deactivated instead of deleted.
        public IEnumerable<Claim> Filter(IEnumerable<Claim> deleted, Rhetos.Dom.DefaultConcepts.DeactivateInsteadOfDelete parameter)
        {{
            var deactivateClaimsId = new List<Guid>();
            var deletedClaimsId = new Lazy<List<Guid>>(() => deleted.Select(c => c.ID).ToList());

            {0}

            var deactivateClaimsIdIndex = new HashSet<Guid>(deactivateClaimsId);
            return deleted.Where(item => deactivateClaimsIdIndex.Contains(item.ID)).ToList();
        }}

", DeactivateInsteadOfDeleteTag.Evaluate(info));
        }
        protected static string SnippetQueryableClass(DataStructureInfo info)
        {
            return string.Format(
    AttributesTag.Evaluate(info) + @"
    public class {0}_{1} : global::{0}.{1}, System.IEquatable<{0}_{1}>" + InterfaceTag.Evaluate(info) + @"
    {{
        " + MembersTag.Evaluate(info) + @"

        public bool Equals({0}_{1} other)
        {{
            return other != null && other.ID == ID;
        }}
    }}

    ",
            info.Module.Name,
            info.Name);
        }
Ejemplo n.º 35
0
        private static string GetFilterExpression(FilterByBaseInfo info, DataStructureInfo baseDataStructure)
        {
            return(string.Format(@"(repository, parameter) =>
            {{
                var baseRepositiory = repository.{3}.{4};
                Guid[] references = baseRepositiory.Filter(parameter).Select(item => item.ID).ToArray();
                {0}.{1}[] result = repository.{0}.{1}.Filter(references);

                Rhetos.Utilities.Graph.SortByGivenOrder(result, references, item => item.ID);
                return result;
            }}
",
                                 info.Source.Module.Name,
                                 info.Source.Name,
                                 info.Parameter,
                                 baseDataStructure.Module.Name,
                                 baseDataStructure.Name,
                                 CsUtility.QuotedString(info.GetUserDescription())));
        }
Ejemplo n.º 36
0
        public IEnumerable <IConceptInfo> CreateNewConcepts(FilterByBaseInfo conceptInfo, IDslModel existingConcepts)
        {
            DataStructureInfo baseDataStructure = GetBaseDataStructure(conceptInfo, existingConcepts);

            if (baseDataStructure == null)
            {
                return(null);
            }

            return(new IConceptInfo[]
            {
                new FilterByInfo
                {
                    Source = conceptInfo.Source,
                    Parameter = conceptInfo.Parameter,
                    Expression = GetFilterExpression(conceptInfo, baseDataStructure)
                },
            });
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Creates a clone of the given source property and puts it in the given destination data structure.
 /// The clone should not have active behavior (HierarchyInfo and SimpleReferencePropertyInfo becomes a simple ReferencePropertyInfo, for example).
 /// </summary>
 public static PropertyInfo CreatePassiveClone(PropertyInfo source, DataStructureInfo destination)
 {
     if (source is ReferencePropertyInfo)
     {
         return(new ReferencePropertyInfo
         {
             DataStructure = destination,
             Name = source.Name,
             Referenced = ((ReferencePropertyInfo)source).Referenced
         });
     }
     else
     {
         var cloneMethod = typeof(object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);
         var property    = (PropertyInfo)cloneMethod.Invoke(source, null);
         property.DataStructure = destination;
         return(property);
     }
 }
Ejemplo n.º 38
0
 /// <summary>
 /// Creates a clone of the given source property and puts it in the given destination data structure.
 /// The clone should not have active behavior (HierarchyInfo and SimpleReferencePropertyInfo becomes a simple ReferencePropertyInfo, for example).
 /// </summary>
 public static PropertyInfo CreatePassiveClone(PropertyInfo source, DataStructureInfo destination)
 {
     if (source is ReferencePropertyInfo)
     {
         return new ReferencePropertyInfo
         {
             DataStructure = destination,
             Name = source.Name,
             Referenced = ((ReferencePropertyInfo)source).Referenced
         };
     }
     else
     {
         var cloneMethod = typeof(object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);
         var property = (PropertyInfo)cloneMethod.Invoke(source, null);
         property.DataStructure = destination;
         return property;
     }
 }
        private static string ImplementationCodeSnippet(DataStructureInfo info)
        {
            return string.Format(@"
            namespace Rhetos.Mvc.{0}
            {{
            {3}
            public partial class {1}{4}
            {{
            public const string Entity{1} = ""{1}"";

            {2}
            }}
            }}
            ",
                info.Module.Name,
                info.Name,
                PropertiesTag.Evaluate(info),
                AttributesTag.Evaluate(info),
                IsEntityType(info) ? " : Rhetos.Mvc.BaseMvcModel" : "");
        }
Ejemplo n.º 40
0
        public static string SnippetQueryableFilterById(DataStructureInfo info)
        {
            return string.Format(
            @"        public IQueryable<{0}.{1}> Filter(IQueryable<{0}.{1}> items, IEnumerable<Guid> ids)
            {{
            if (!(ids is System.Collections.IList))
                ids = ids.ToList();

            if (ids.Count() < 2000) // NHibernate limit for Contains function.
                return items.Where(item => ids.Contains(item.ID));
            else
            {{
                var idsQuery = _domRepository.Common.FilterId.CreateQueryableFilterIds(ids);
                return items.Where(item => idsQuery.Contains(item.ID));
            }}
            }}

            ",
                info.Module.Name, info.Name);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Returns a writable data structure that can be used to monitor data changes (intercepting its Save function), in order to update a persisted data.
        /// Returns empty array if a required data structure is not found.
        /// </summary>
        public static IEnumerable<DataStructureInfo> GetBaseChangesOnDependency(DataStructureInfo dependsOn, IDslModel existingConcepts)
        {
            if (dependsOn.Name.EndsWith("_History"))
            {
                var history = existingConcepts.FindByReference<EntityHistoryInfo>(h => h.Dependency_HistorySqlQueryable, dependsOn).SingleOrDefault();
                if (history != null)
                    return new DataStructureInfo[] { history.Entity, history.Dependency_ChangesEntity };
            }

            if (dependsOn is IWritableOrmDataStructure)
                return new[] { dependsOn };

            if (existingConcepts.FindByReference<WriteInfo>(write => write.DataStructure, dependsOn).Any())
                return new[] { dependsOn };

            var baseDataStructure = existingConcepts.FindByReference<DataStructureExtendsInfo>(ex => ex.Extension, dependsOn)
                .Select(ex => ex.Base).SingleOrDefault();
            if (baseDataStructure != null)
                return GetBaseChangesOnDependency(baseDataStructure, existingConcepts);

            return Enumerable.Empty<DataStructureInfo>();
        }
Ejemplo n.º 42
0
        private static string RepositorySnippet(DataStructureInfo info)
        {
            return string.Format(
    RepositoryAttributes.Evaluate(info) + @"
    public class {0}_Repository : IRepository" + RepositoryInterfaces.Evaluate(info) + @"
    {{
        private readonly Common.DomRepository _domRepository;
        private readonly Common.ExecutionContext _executionContext;
        " + RepositoryPrivateMembers.Evaluate(info) + @"

        public {0}_Repository(Common.DomRepository domRepository, Common.ExecutionContext executionContext" + ConstructorArguments.Evaluate(info) + @")
        {{
            _domRepository = domRepository;
            _executionContext = executionContext;
            " + ConstructorCode.Evaluate(info) + @"
        }}

        " + RepositoryMembers.Evaluate(info) + @"
    }}

    ",
                info.Name);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Note: When using this function to create a database object, always add the dependencies from GetAdditionalForeignKeyDependencies().
        /// </summary>
        public static string GetSchemaTableForForeignKey(DataStructureInfo dataStructure)
        {
            if (dataStructure is EntityInfo)
                return SqlUtility.Identifier(dataStructure.Module.Name)
                    + "." + SqlUtility.Identifier(dataStructure.Name);

            if (dataStructure is LegacyEntityInfo)
            {
                var legacy = (LegacyEntityInfo)dataStructure;
                return SqlUtility.GetFullName(legacy.Table);
            }

            if (dataStructure is LegacyEntityWithAutoCreatedViewInfo)
            {
                var legacy = (LegacyEntityWithAutoCreatedViewInfo)dataStructure;
                return SqlUtility.GetFullName(legacy.Table);
            }

            if (dataStructure is PolymorphicInfo)
                return dataStructure.GetKeyProperties() + "_Materialized";

            return null;
        }
Ejemplo n.º 44
0
        protected static string CodeSnippet(DataStructureInfo info)
        {
            return
            @"
            public override int GetHashCode()
            {
            " + GetHashCodeTag.Evaluate(info) + @"
            return ID.GetHashCode();
            }

            public override bool Equals(object o)
            {
            " + EqualsBaseTag.Evaluate(info) + @"
            var other = o as " + info.Name + @";
            return other != null && other.ID == ID;
            }

            bool System.IEquatable<" + info.Name + @">.Equals(" + info.Name + @" other)
            {
            " + EqualsInterfaceTag.Evaluate(info) + @"
            return other != null && other.ID == ID;
            }
            ";
        }
Ejemplo n.º 45
0
        public static string SnippetQueryableFilterById(DataStructureInfo info)
        {
            return string.Format(
            @"public IQueryable<Common.Queryable.{0}_{1}> Filter(IQueryable<Common.Queryable.{0}_{1}> items, IEnumerable<Guid> ids)
            {{
            if (!(ids is System.Collections.IList))
                ids = ids.ToList();

            if (ids.Count() == 1) // EF 6.1.3. does not use parametrized SQL query for Contains() function. The equality comparer is used instead, to reuse cached execution plans.
            {{
                Guid id = ids.Single();
                return items.Where(item => item.ID == id);
            }}
            else
            {{
                // Depending on the ids count, this method will return the list of IDs, or insert the ids to the database and return an SQL query that selects the ids.
                var idsQuery = _domRepository.Common.FilterId.CreateQueryableFilterIds(ids);
                return items.Where(item => idsQuery.Contains(item.ID));
            }}
            }}

            ",
                info.Module.Name, info.Name);
        }
        protected static string SnippetEntityClassMembers(DataStructureInfo info)
        {
            return
        @"public override int GetHashCode()
        {
            " + GetHashCodeTag.Evaluate(info) + @"
            return ID.GetHashCode();
        }

        public override bool Equals(object o)
        {
            " + EqualsBaseTag.Evaluate(info) + @"
            var other = o as " + info.Name + @";
            return other != null && other.ID == ID;
        }

        public bool Equals(" + info.Name + @" other)
        {
            " + EqualsInterfaceTag.Evaluate(info) + @"
            return other != null && other.ID == ID;
        }

        ";
        }
Ejemplo n.º 47
0
 public static string CreateComposableFilterSnippet(string permissionExpressionName, DataStructureInfo dataStructure)
 {
     return($@"(source, parameter) => 
 {{
     var filterExpression = {permissionExpressionName}(source, _domRepository, _executionContext);
     return FilterExpression<Common.Queryable.{dataStructure.Module.Name}_{dataStructure.Name}>.OptimizedWhere(source, filterExpression);
 }}");
 }
Ejemplo n.º 48
0
 protected static string QuerySnippet(DataStructureInfo info)
 {
     return string.Format(
         @"return _executionContext.NHibernateSession.Query<global::{0}.{1}>();",
         info.Module.Name, info.Name);
 }
Ejemplo n.º 49
0
        private static string RepositoryReadFunctionsSnippet(DataStructureInfo info, string readFunctionBody)
        {
            return string.Format(
        @"public IEnumerable<{0}> Load(object parameter, Type parameterType)
        {{
            var items = _executionContext.GenericRepository(""{0}"").Load(parameter, parameterType);
            return (IEnumerable<{0}>)items;
        }}

        public IEnumerable<{0}> Read(object parameter, Type parameterType, bool preferQuery)
        {{
            var items = _executionContext.GenericRepository(""{0}"").Read(parameter, parameterType, preferQuery);
            return (IEnumerable<{0}>)items;
        }}

        [Obsolete(""Use Load() or Query() method."")]
        public global::{0}[] All()
        {{
            {1}
        }}

        [Obsolete(""Use Load() or Query() method."")]
        public global::{0}[] Filter(FilterAll filterAll)
        {{
            return All();
        }}

        ",
                info.GetKeyProperties(),
                readFunctionBody);
        }
        private RowPermissionsWriteInfo GetRowPermissionsWrite(DataStructureInfo dataStructure, IEnumerable <IConceptInfo> concepts)
        {
            var allRp = concepts.OfType <RowPermissionsWriteInfo>();

            return(allRp.SingleOrDefault(a => a.Source == dataStructure));
        }
Ejemplo n.º 51
0
 public static void CheckIfPropertyBelongsToDataStructure(PropertyInfo property, DataStructureInfo dataStructure, IConceptInfo errorContext)
 {
     if (property.DataStructure != dataStructure)
     {
         throw new DslSyntaxException(errorContext,
                                      $"Property {property.FullName} is not in data structure {dataStructure.FullName}.");
     }
 }
Ejemplo n.º 52
0
 public static bool IsSupported(DataStructureInfo dataStructure)
 {
     return(dataStructure is IWritableOrmDataStructure);
 }
Ejemplo n.º 53
0
 public static string CreateComposableFilterSnippet(string permissionExpressionName, DataStructureInfo dataStructure)
 {
     return(string.Format(
                @"(source, repository, parameter, context) => 
         {{
             var filterExpression = {0}(source, repository, context);
             return FilterExpression<Common.Queryable.{1}_{2}>.OptimizedWhere(source, filterExpression);
         }}", permissionExpressionName, dataStructure.Module.Name, dataStructure.Name));
 }
Ejemplo n.º 54
0
        public static PropertyInfo FindProperty(IDslModel dslModel, DataStructureInfo dataStructure, string propertyName)
        {
            var propertyKey = string.Format("PropertyInfo {0}.{1}.{2}", dataStructure.Module.Name, dataStructure.Name, propertyName);

            return((PropertyInfo)dslModel.FindByKey(propertyKey));
        }
Ejemplo n.º 55
0
 public static void CheckIfPropertyBelongsToDataStructure(PropertyInfo property, DataStructureInfo dataStructure, IConceptInfo errorContext)
 {
     if (property.DataStructure != dataStructure)
     {
         throw new Exception(String.Format(
                                 "Invalid use of " + errorContext.GetKeywordOrTypeName() + ": Property {0}.{1}.{2} is not in data structure {3}.{4}.",
                                 property.DataStructure.Module.Name,
                                 property.DataStructure.Name,
                                 property.Name,
                                 dataStructure.Module.Name,
                                 dataStructure.Name));
     }
 }
Ejemplo n.º 56
0
 /// <summary>
 /// Concatenates module name and data stucture name. Omits module name if it is same as the context module.
 /// </summary>
 public static string NameOptionalModule(DataStructureInfo dataStructure, ModuleInfo contextModule)
 {
     return(dataStructure.Module.Name != contextModule.Name ? (dataStructure.Module.Name + dataStructure.Name) : dataStructure.Name);
 }