예제 #1
0
        //public methods
        public Expression <TDelegate> Rewrite <TDelegate>(Expression <TDelegate> exp)
        {
            var        current  = _rewriter.Rewrite(exp.Body);
            Expression previous = null;

            while (!_comparer.Equals(current, previous))
            {
                previous = current;
                current  = _aligner.Align(current);
                current  = _rewriter.Rewrite(current);
            }

            return(Expression.Lambda <TDelegate>(current, exp.Parameters));
        }
        private CSharpCompilation CompileViews(ViewCompilationInfo[] results, string assemblyname)
        {
            var compiler    = MvcServiceProvider.Compiler;
            var compilation = compiler.CreateCompilation(assemblyname);
            var syntaxTrees = new SyntaxTree[results.Length];

            Parallel.For(0, results.Length, ParalellOptions, i =>
            {
                var result     = results[i];
                var sourceText = SourceText.From(result.CSharpDocument.GeneratedCode, Encoding.UTF8);
                var fileInfo   = result.ViewFileInfo;
                var syntaxTree = compiler.CreateSyntaxTree(sourceText)
                                 .WithFilePath(fileInfo.FullPath ?? fileInfo.ViewEnginePath);
                syntaxTrees[i] = syntaxTree;
            });

            compilation = compilation.AddSyntaxTrees(syntaxTrees);

            // Post process the compilation - run ExpressionRewritter and any user specified callbacks.
            compilation = ExpressionRewriter.Rewrite(compilation);
            var compilationContext = new RoslynCompilationContext(compilation);

#pragma warning disable CS0618 // Type or member is obsolete
            MvcServiceProvider.ViewEngineOptions.CompilationCallback(compilationContext);
#pragma warning restore CS0618 // Type or member is obsolete
            compilation = AssemblyMetadataGenerator.AddAssemblyMetadata(
                compiler,
                compilationContext.Compilation,
                Options);

            return(compilation);
        }
예제 #3
0
        /// <summary>
        /// Perform the actual update.
        /// </summary>
        /// <param name="context">Context.</param>
        /// <param name="data">Data.</param>
        public override TModel Update(ModelDataContext context, TModel data, IPrincipal principal)
        {
            // Check for key
            if (data.Key == Guid.Empty)
            {
                throw new SqlFormalConstraintException(SqlFormalConstraintType.NonIdentityUpdate);
            }

            // Get current object
            var domainObject  = this.FromModelInstance(data, context, principal) as TDomain;
            var currentObject = context.GetTable <TDomain>().FirstOrDefault(ExpressionRewriter.Rewrite <TDomain>(o => o.Id == data.Key));

            // Not found
            if (currentObject == null)
            {
                throw new KeyNotFoundException(data.Key.ToString());
            }

            // VObject
            var vobject = domainObject as IDbNonVersionedBaseData;

            if (vobject != null)
            {
                vobject.UpdatedBy   = principal.GetUser(context).UserId;
                vobject.UpdatedTime = DateTimeOffset.Now;
            }

            currentObject.CopyObjectData(domainObject);
            context.SubmitChanges();

            return(this.ToModelInstance(domainObject, context, principal));
        }
예제 #4
0
        private CSharpCompilation CompileViews(ViewCompilationInfo[] results, string assemblyname)
        {
            var compilation = compiler.CreateCompilation(assemblyname);
            var syntaxTrees = new SyntaxTree[results.Length];

            Parallel.For(0, results.Length, ParalellOptions, i =>
            {
                ViewCompilationInfo result = results[i];
                SourceText sourceText      = SourceText.From(result.CSharpDocument.GeneratedCode, Encoding.UTF8);

                TemplateFileInfo fileInfo = result.TemplateFileInfo;
                SyntaxTree syntaxTree     = compiler.CreateSyntaxTree(sourceText).WithFilePath(fileInfo.FullPath ?? fileInfo.ViewEnginePath);
                syntaxTrees[i]            = syntaxTree;
            });

            compilation = compilation.AddSyntaxTrees(syntaxTrees);
            compilation = ExpressionRewriter.Rewrite(compilation);

            compilation = AssemblyMetadataGenerator.AddAssemblyMetadata(
                compiler,
                compilation,
                Options);

            return(compilation);
        }
예제 #5
0
        /// <summary>
        /// Update the data with new version information
        /// </summary>
        public override TModel Update(ModelDataContext context, TModel data, IPrincipal principal)
        {
            if (data.Key == Guid.Empty)
            {
                throw new SqlFormalConstraintException(SqlFormalConstraintType.NonIdentityUpdate);
            }

            // This is technically an insert and not an update
            var existingObject = context.GetTable <TDomain>().FirstOrDefault(ExpressionRewriter.Rewrite <TDomain>(o => o.Id == data.Key && !o.ObsoletionTime.HasValue)); // Get the last version (current)

            if (existingObject == null)
            {
                throw new KeyNotFoundException(data.Key.ToString());
            }
            else if (existingObject.IsReadonly)
            {
                throw new SqlFormalConstraintException(SqlFormalConstraintType.UpdatedReadonlyObject);
            }

            // Map existing
            var storageInstance = this.FromModelInstance(data, context, principal);

            // Create a new version
            var user             = principal.GetUser(context);
            var newEntityVersion = new TDomain();

            newEntityVersion.CopyObjectData(storageInstance);

            // Client did not change on update, so we need to update!!!
            if (!data.VersionKey.HasValue ||
                data.VersionKey.Value == existingObject.VersionId)
            {
                data.VersionKey = newEntityVersion.VersionId = Guid.NewGuid();
            }

            data.VersionSequence    = newEntityVersion.VersionSequenceId = default(Decimal);
            newEntityVersion.Id     = data.Key.Value;
            data.PreviousVersionKey = newEntityVersion.ReplacesVersionId = existingObject.VersionId;
            data.CreatedByKey       = newEntityVersion.CreatedBy = user.UserId;
            // Obsolete the old version
            existingObject.ObsoletedBy    = user.UserId;
            existingObject.ObsoletionTime = DateTime.Now;
            context.GetTable <TDomain>().InsertOnSubmit(newEntityVersion);
            context.SubmitChanges();

            // Pull database generated fields
            data.VersionSequence = newEntityVersion.VersionSequenceId;
            data.CreationTime    = newEntityVersion.CreationTime;

            return(data);
            //return base.Update(context, data, principal);
        }
        private CSharpCompilation CompileViews(ViewCompilationInfo[] results, string assemblyname)
        {
            var compiler    = MvcServiceProvider.Compiler;
            var compilation = compiler.CreateCompilation(assemblyname);
            var syntaxTrees = new SyntaxTree[results.Length];

            string[] additionalReferences = new string[]
            {
                @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6\Microsoft.CSharp.dll",
                //@"C:\Users\jbato\.nuget\packages\Microsoft.DiaSymReader.Native\1.4.0\runtimes\win-x64\native\Microsoft.DiaSymReader.Native.amd64.dll",
            };

            compilation = compilation.AddReferences(additionalReferences.Select(r => MetadataReference.CreateFromFile(r)));

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            compilation = compilation.AddReferences(assemblies.Where(a => !a.IsDynamic).Select(a => MetadataReference.CreateFromFile(a.Location)));

            Parallel.For(0, results.Length, ParalellOptions, i =>
            {
                var result     = results[i];
                var sourceText = SourceText.From(result.GeneratorResults.GeneratedCode, Encoding.UTF8);
                var fileInfo   = result.RelativeFileInfo;
                var syntaxTree = compiler.CreateSyntaxTree(sourceText)
                                 .WithFilePath(fileInfo.FileInfo.PhysicalPath ?? fileInfo.RelativePath);
                syntaxTrees[i] = syntaxTree;
            });

            compilation = compilation.AddSyntaxTrees(syntaxTrees);
            Parallel.For(0, results.Length, ParalellOptions, i =>
            {
                results[i].TypeName = ReadTypeInfo(compilation, syntaxTrees[i]);
            });

            // Post process the compilation - run ExpressionRewritter and any user specified callbacks.
            compilation = ExpressionRewriter.Rewrite(compilation);
            var compilationContext = new RoslynCompilationContext(compilation);

            MvcServiceProvider.ViewEngineOptions.CompilationCallback(compilationContext);
            compilation = compilationContext.Compilation;

            var codeGenerator = new ViewInfoContainerCodeGenerator(compiler, compilation);

            codeGenerator.AddViewFactory(results);

            var assemblyName = new AssemblyName(ApplicationNameOption.Value());

            assemblyName = Assembly.Load(assemblyName).GetName();
            codeGenerator.AddAssemblyMetadata(assemblyName, StrongNameOptions);

            return(codeGenerator.Compilation);
        }
예제 #7
0
        private CSharpCompilation CreateCompilation(string compilationContent, string assemblyName)
        {
            SourceText sourceText = SourceText.From(compilationContent, Encoding.UTF8);
            SyntaxTree syntaxTree = CreateSyntaxTree(sourceText).WithFilePath(assemblyName);

            CSharpCompilation compilation = CreateCompilation(assemblyName).AddSyntaxTrees(syntaxTree);

            compilation = ExpressionRewriter.Rewrite(compilation);

            //var compilationContext = new RoslynCompilationContext(compilation);
            //_compilationCallback(compilationContext);
            //compilation = compilationContext.Compilation;
            return(compilation);
        }
예제 #8
0
        /// <summary>
        /// Update associated items
        /// </summary>
        protected virtual void UpdateAssociatedItems <TAssociation, TDomainAssociation>(IEnumerable <TAssociation> storage, TModel source, ModelDataContext context, IPrincipal principal)
            where TAssociation : IdentifiedData, ISimpleAssociation, new()
            where TDomainAssociation : class, IDbAssociation, new()
        {
            var persistenceService = ApplicationContext.Current.GetService <IDataPersistenceService <TAssociation> >() as SqlServerBasePersistenceService <TAssociation>;

            if (persistenceService == null)
            {
                this.m_tracer.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "Missing persister for type {0}", typeof(TAssociation).Name);
                return;
            }
            // Ensure the source key is set
            foreach (var itm in storage)
            {
                if (itm.SourceEntityKey == Guid.Empty ||
                    itm.SourceEntityKey == null)
                {
                    itm.SourceEntityKey = source.Key;
                }
            }

            // Get existing
            var existing = context.GetTable <TDomainAssociation>().Where(ExpressionRewriter.Rewrite <TDomainAssociation>(o => o.AssociatedItemKey == source.Key)).ToList().Select(o => m_mapper.MapDomainInstance <TDomainAssociation, TAssociation>(o) as TAssociation);
            // Remove old
            var obsoleteRecords = existing.Where(o => !storage.Any(ecn => ecn.Key == o.Key));

            foreach (var del in obsoleteRecords)
            {
                persistenceService.Obsolete(context, del, principal);
            }

            // Update those that need it
            var updateRecords = storage.Where(o => existing.Any(ecn => ecn.Key == o.Key && o.Key != Guid.Empty && o != ecn));

            foreach (var upd in updateRecords)
            {
                persistenceService.Update(context, upd, principal);
            }

            // Insert those that do not exist
            var insertRecords = storage.Where(o => !existing.Any(ecn => ecn.Key == o.Key));

            foreach (var ins in insertRecords)
            {
                persistenceService.Insert(context, ins, principal);
            }
        }
예제 #9
0
        /// <summary>
        /// Performs the actual obsoletion
        /// </summary>
        /// <param name="context">Context.</param>
        /// <param name="data">Data.</param>
        public override TModel Obsolete(ModelDataContext context, TModel data, IPrincipal principal)
        {
            if (data.Key == Guid.Empty)
            {
                throw new SqlFormalConstraintException(SqlFormalConstraintType.NonIdentityUpdate);
            }

            var domainObject = context.GetTable <TDomain>().FirstOrDefault(ExpressionRewriter.Rewrite <TDomain>(o => o.Id == data.Key));

            if (domainObject == null)
            {
                throw new KeyNotFoundException(data.Key.ToString());
            }

            context.GetTable <TDomain>().DeleteOnSubmit(domainObject);

            return(this.ToModelInstance(domainObject, context, principal));
        }
예제 #10
0
        public override Core.Model.Security.SecurityPolicy Update(ModelDataContext context, Core.Model.Security.SecurityPolicy data, IPrincipal principal)
        {
            var domainInstance = this.FromModelInstance(data, context, principal) as Data.Policy;

            var currentObject = context.GetTable <Data.Policy>().FirstOrDefault(ExpressionRewriter.Rewrite <Data.Policy>(o => o.Id == data.Key));

            if (currentObject == null)
            {
                throw new KeyNotFoundException(data.Key.ToString());
            }

            currentObject.CopyObjectData(domainInstance);

            currentObject.ObsoletedBy    = data.ObsoletedByKey == Guid.Empty ? null : data.ObsoletedByKey;
            currentObject.ObsoletionTime = data.ObsoletionTime;

            context.SubmitChanges();

            return(data);
        }
예제 #11
0
        /// <summary>
        /// Performs the actual obsoletion
        /// </summary>
        /// <param name="context">Context.</param>
        /// <param name="data">Data.</param>
        public override TModel Obsolete(ModelDataContext context, TModel data, IPrincipal principal)
        {
            if (data.Key == Guid.Empty)
            {
                throw new SqlFormalConstraintException(SqlFormalConstraintType.NonIdentityUpdate);
            }

            // Current object
            var currentObject = context.GetTable <TDomain>().FirstOrDefault(ExpressionRewriter.Rewrite <TDomain>(o => o.Id == data.Key));

            if (currentObject == null)
            {
                throw new KeyNotFoundException(data.Key.ToString());
            }

            data.ObsoletedBy?.EnsureExists(context, principal);
            data.ObsoletedByKey = currentObject.ObsoletedBy = data.ObsoletedBy?.Key ?? principal.GetUser(context).UserId;
            data.ObsoletionTime = currentObject.ObsoletionTime = currentObject.ObsoletionTime ?? DateTimeOffset.Now;
            context.SubmitChanges();
            return(data);
        }
        private CSharpCompilation CompileViews(ViewCompilationInfo[] results, string assemblyname)
        {
            var compiler    = MvcServiceProvider.Compiler;
            var compilation = compiler.CreateCompilation(assemblyname);
            var syntaxTrees = new SyntaxTree[results.Length];

            Parallel.For(0, results.Length, ParalellOptions, i =>
            {
                var result     = results[i];
                var sourceText = SourceText.From(result.GeneratorResults.GeneratedCode, Encoding.UTF8);
                var fileInfo   = result.RelativeFileInfo;
                var syntaxTree = compiler.CreateSyntaxTree(sourceText)
                                 .WithFilePath(fileInfo.FileInfo.PhysicalPath ?? fileInfo.RelativePath);
                syntaxTrees[i] = syntaxTree;
            });

            compilation = compilation.AddSyntaxTrees(syntaxTrees);
            Parallel.For(0, results.Length, ParalellOptions, i =>
            {
                results[i].TypeName = ReadTypeInfo(compilation, syntaxTrees[i]);
            });

            // Post process the compilation - run ExpressionRewritter and any user specified callbacks.
            compilation = ExpressionRewriter.Rewrite(compilation);
            var compilationContext = new RoslynCompilationContext(compilation);

            MvcServiceProvider.ViewEngineOptions.CompilationCallback(compilationContext);
            compilation = compilationContext.Compilation;

            var codeGenerator = new ViewInfoContainerCodeGenerator(compiler, compilation);

            codeGenerator.AddViewFactory(results);

            var assemblyName = new AssemblyName(ApplicationNameOption.Value());

            assemblyName = Assembly.Load(assemblyName).GetName();
            codeGenerator.AddAssemblyMetadata(assemblyName, StrongNameOptions);

            return(codeGenerator.Compilation);
        }
예제 #13
0
        /// <summary>
        /// Perform the actual update.
        /// </summary>
        /// <param name="context">Context.</param>
        /// <param name="data">Data.</param>
        public override TModel Update(ModelDataContext context, TModel data, IPrincipal principal)
        {
            // Sanity
            if (data.Key == Guid.Empty)
            {
                throw new SqlFormalConstraintException(SqlFormalConstraintType.NonIdentityUpdate);
            }

            // Map and copy
            var newDomainObject = this.FromModelInstance(data, context, principal) as TDomain;
            var domainQuery     = ExpressionRewriter.Rewrite <TDomain>(o => o.Id == newDomainObject.Id);
            var oldDomainObject = context.GetTable <TDomain>().SingleOrDefault(domainQuery);

            if (oldDomainObject == null)
            {
                throw new KeyNotFoundException(data.Key.ToString());
            }

            oldDomainObject.CopyObjectData(newDomainObject);
            context.SubmitChanges();
            return(data);
        }
예제 #14
0
        /// <summary>
        /// Update the roles to security user
        /// </summary>
        public override Core.Model.Security.SecurityApplication Update(ModelDataContext context, Core.Model.Security.SecurityApplication data, IPrincipal principal)
        {
            var domainInstance = this.FromModelInstance(data, context, principal) as Data.SecurityApplication;

            var currentObject = context.GetTable <Data.SecurityApplication>().FirstOrDefault(ExpressionRewriter.Rewrite <Data.SecurityApplication>(o => o.Id == data.Key));

            if (currentObject == null)
            {
                throw new KeyNotFoundException(data.Key.ToString());
            }

            currentObject.CopyObjectData(domainInstance);

            currentObject.ObsoletedBy    = data.ObsoletedByKey == Guid.Empty ? null : data.ObsoletedByKey;
            currentObject.ObsoletionTime = data.ObsoletionTime;

            context.SubmitChanges();

            context.SecurityApplicationPolicies.DeleteAllOnSubmit(context.SecurityApplicationPolicies.Where(o => o.ApplicationId == domainInstance.Id));

            context.SubmitChanges();

            context.SecurityApplicationPolicies.InsertAllOnSubmit(data.Policies.Select(o => new Data.SecurityApplicationPolicy
            {
                PolicyId                 = o.PolicyKey.Value,
                PolicyAction             = (int)o.GrantType,
                ApplicationId            = domainInstance.Id,
                SecurityPolicyInstanceId = Guid.NewGuid()
            }));

            context.SubmitChanges();

            return(data);
        }
예제 #15
0
        // Token: 0x06000183 RID: 387 RVA: 0x00007458 File Offset: 0x00005658
        private CSharpCompilation CreateCompilation(string compilationContent, string assemblyName)
        {
            SourceText sourceText = SourceText.From(compilationContent, Encoding.UTF8, SourceHashAlgorithm.Sha1);
            SyntaxTree syntaxTree = this._csharpCompiler.CreateSyntaxTree(sourceText).WithFilePath(assemblyName);
            RoslynCompilationContext roslynCompilationContext = new RoslynCompilationContext(ExpressionRewriter.Rewrite(this._csharpCompiler.CreateCompilation(assemblyName).AddSyntaxTrees(new SyntaxTree[]
            {
                syntaxTree
            })));

            this._compilationCallback(roslynCompilationContext);
            return(roslynCompilationContext.Compilation);
        }
예제 #16
0
        /// <summary>
        /// Update versioned association items
        /// </summary>
        internal virtual void UpdateVersionedAssociatedItems <TAssociation, TDomainAssociation>(IEnumerable <TAssociation> storage, TModel source, ModelDataContext context, IPrincipal principal)
            where TAssociation : VersionedAssociation <TModel>, new()
            where TDomainAssociation : class, IDbVersionedAssociation, new()
        {
            var persistenceService = ApplicationContext.Current.GetService <IDataPersistenceService <TAssociation> >() as SqlServerBasePersistenceService <TAssociation>;

            if (persistenceService == null)
            {
                this.m_tracer.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "Missing persister for type {0}", typeof(TAssociation).Name);
                return;
            }

            Dictionary <Guid, Decimal> sourceVersionMaps = new Dictionary <Guid, decimal>();

            // Ensure the source key is set
            foreach (var itm in storage)
            {
                if (itm.SourceEntityKey == Guid.Empty ||
                    itm.SourceEntityKey == null)
                {
                    itm.SourceEntityKey = source.Key;
                }
                else if (itm.SourceEntityKey != source.Key && !sourceVersionMaps.ContainsKey(itm.SourceEntityKey ?? Guid.Empty)) // The source comes from somewhere else
                {
                    // First we have our association type, we need to get the property that is
                    // linked on the association to get the map to the underlying SQL table
                    var domainType     = m_mapper.MapModelType(typeof(TDomainAssociation));
                    var mappedProperty = domainType.GetRuntimeProperty("AssociatedItemKey").GetCustomAttribute <LinqPropertyMapAttribute>().LinqMember;
                    // Next we want to get the association entity which is linked to this key identifier
                    var rpi = domainType.GetRuntimeProperties().FirstOrDefault(o => o.GetCustomAttribute <AssociationAttribute>()?.ThisKey == mappedProperty);
                    // Now we want to switch the type to the entity that is linked to the key so we can
                    // get ist primary key
                    domainType = rpi.PropertyType;
                    var pkey = domainType.GetRuntimeProperties().FirstOrDefault(o => o.GetCustomAttribute <ColumnAttribute>()?.IsPrimaryKey == true);
                    // Now we want to get the key that we should query by that is version independent
                    domainType = typeof(TDomain);
                    pkey       = domainType.GetRuntimeProperty(pkey.Name);
                    // Construct a LINQ expression to query the db
                    var parm         = Expression.Parameter(domainType);
                    var delegateType = typeof(Func <,>).MakeGenericType(domainType, typeof(bool));
                    var predicate    = Expression.Lambda(delegateType, Expression.MakeBinary(ExpressionType.Equal, Expression.MakeMemberAccess(parm, pkey), Expression.Constant(itm.SourceEntityKey.Value)), parm);
                    // Get the SQL table instance and filter
                    var table      = context.GetTable(domainType);
                    var tableEnum  = table.Provider.Execute(table.Expression);
                    var methodInfo = typeof(Queryable).GetGenericMethod("FirstOrDefault", new Type[] { domainType }, new Type[]
                    {
                        typeof(IQueryable <>).MakeGenericType(domainType),
                        typeof(Expression <>).MakeGenericType(delegateType)
                    });
                    var result = methodInfo.Invoke(null, new Object[] { tableEnum, predicate }) as IDbVersionedData;
                    sourceVersionMaps.Add(itm.SourceEntityKey.Value, result.VersionSequenceId);

                    //var whereMethod =
                    //var result = context.GetTable(domainType).Provider.Execute(predicate);
                }
            }

            // Get existing
            // TODO: What happens which this is reverse?
            var existing = context.GetTable <TDomainAssociation>().Where(ExpressionRewriter.Rewrite <TDomainAssociation>(o => o.AssociatedItemKey == source.Key && source.VersionSequence >= o.EffectiveVersionSequenceId && (source.VersionSequence < o.ObsoleteVersionSequenceId || !o.ObsoleteVersionSequenceId.HasValue))).ToList().Select(o => m_mapper.MapDomainInstance <TDomainAssociation, TAssociation>(o) as TAssociation);

            // Remove old
            var obsoleteRecords = existing.Where(o => !storage.Any(ecn => ecn.Key == o.Key));

            foreach (var del in obsoleteRecords)
            {
                decimal obsVersion = 0;
                if (!sourceVersionMaps.TryGetValue(del.SourceEntityKey.Value, out obsVersion))
                {
                    obsVersion = source.VersionSequence.GetValueOrDefault();
                }
                del.ObsoleteVersionSequenceId = obsVersion;
                persistenceService.Update(context, del, principal);
            }

            // Update those that need it
            var updateRecords = storage.Where(o => existing.Any(ecn => ecn.Key == o.Key && o.Key != Guid.Empty && o != ecn));

            foreach (var upd in updateRecords)
            {
                persistenceService.Update(context, upd, principal);
            }

            // Insert those that do not exist
            var insertRecords = storage.Where(o => !existing.Any(ecn => ecn.Key == o.Key));

            foreach (var ins in insertRecords)
            {
                decimal eftVersion = 0;
                if (!sourceVersionMaps.TryGetValue(ins.SourceEntityKey.Value, out eftVersion))
                {
                    eftVersion = source.VersionSequence.GetValueOrDefault();
                }
                ins.EffectiveVersionSequenceId = eftVersion;

                persistenceService.Insert(context, ins, principal);
            }
        }