Exemple #1
0
        /// <summary>
        /// Create Model from ServiceMetadata object
        /// </summary>
        /// <param name="serviceMetadata">ServiceMetadata object</param>
        /// <returns>The model code in C#</returns>
        public string CreateModelFromMetadata(ServiceMetadata serviceMetadata)
        {
            _serviceMetadata = serviceMetadata;

            Dictionary <string, string> classes = new Dictionary <string, string>();

            CreateModelFromMetadataRecursive(classes, serviceMetadata.Elements.Values.First(el => el.ParentElement == null));

            foreach (KeyValuePair <string, ElementMetadata> group in serviceMetadata.Elements.Where(e => e.Value.Type == ElementType.Group))
            {
                StringBuilder classBuilder = new StringBuilder();
                classBuilder.AppendLine("public class " + group.Value.Name + "{");

                foreach (KeyValuePair <string, ElementMetadata> childElement in serviceMetadata.Elements.Where(e => e.Value.ParentElement == group.Value.ID))
                {
                }

                classBuilder.AppendLine("}");
            }

            var writer = new StringBuilder()
                         .AppendLine("using System;")
                         .AppendLine("using System.Collections.Generic;")
                         .AppendLine("using System.Linq;")
                         .AppendLine("using System.Threading.Tasks;")
                         .AppendLine("using System.Xml.Serialization;")
                         .AppendLine("using System.ComponentModel.DataAnnotations;")
                         .AppendLine("using Microsoft.AspNetCore.Mvc.ModelBinding;")
                         .AppendLine("namespace " + string.Format(CodeGeneration.ServiceNamespaceTemplate, serviceMetadata.Org, CompileHelper.GetCSharpValidAppId(serviceMetadata.RepositoryName)))
                         .AppendLine("{")
                         ////Append all classes
                         .Append(string.Concat(classes.Values))
                         .AppendLine("}");

            return(writer.ToString());
        }
        /// <inheritdoc/>
        public IServiceImplementation GetServiceImplementation(string applicationOwnerId, string applicationId, bool startServiceFlag)
        {
            string assemblykey            = $"{applicationOwnerId}_{applicationId}";
            string implementationTypeName = null;
            Type   type = null;

            if (_assemblyNames.ContainsKey(assemblykey))
            {
                implementationTypeName = string.Format(CodeGeneration.ServiceNamespaceTemplate, applicationOwnerId, CompileHelper.GetCSharpValidAppId(applicationId)) + ".ServiceImplementation," + _assemblyNames[assemblykey];

                type = Type.GetType(implementationTypeName);

                if (type != null)
                {
                    return((IServiceImplementation)Activator.CreateInstance(Type.GetType(implementationTypeName)));
                }
            }

            implementationTypeName = string.Format(CodeGeneration.ServiceNamespaceTemplate, applicationOwnerId, CompileHelper.GetCSharpValidAppId(applicationId)) + ".ServiceImplementation";

            Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(_settings.BaseResourceFolderContainer + _settings.GetBinaryFolder() + "AltinnService.dll");

            type = asm.GetType(implementationTypeName);

            if (type != null)
            {
                _assemblyNames.Add(assemblykey, asm.FullName);
            }

            dynamic serviceImplementation = Activator.CreateInstance(type);

            return((IServiceImplementation)serviceImplementation);
        }
        /// <summary>
        /// Creates the assembly for an app.
        /// </summary>
        /// <param name="org">Unique identifier of the organisation responsible for the app.</param>
        /// <param name="app">Application identifier which is unique within an organisation.</param>
        /// <param name="startAppFlag">Flag to determine if the app should run/re-run.</param>
        /// <param name="outputLocation">The directory where the resulting assembly should be saved.</param>
        /// <param name="loadAssemblyContext">Defines if assembly should be loaded in context.</param>
        /// <returns>The assembly name.</returns>
        public CodeCompilationResult CreateServiceAssembly(string org, string app, bool startAppFlag, string outputLocation = null, bool loadAssemblyContext = true)
        {
            CodeCompilationResult compilationResult = new CodeCompilationResult()
            {
                CompileStarted = DateTime.Now
            };
            string assemblykey = org + "_" + CompileHelper.GetCSharpValidAppId(app);
            List <AltinnCoreFile> implementationFiles = _repository.GetImplementationFiles(org, app);

            DateTime lastChanged = new DateTime(2000, 01, 01);

            foreach (AltinnCoreFile file in implementationFiles)
            {
                if (file.LastChanged > lastChanged)
                {
                    lastChanged = file.LastChanged;
                }
            }

            SyntaxTree[]             syntaxTrees = GetSyntaxTrees(org, app);
            List <MetadataReference> references  = new List <MetadataReference>();
            Assembly root = Assembly.GetEntryAssembly();

            string assemblyName = Path.GetRandomFileName();

            MetadataReferenceFeature referenceFeature = new MetadataReferenceFeature();

            _partManager.PopulateFeature(referenceFeature);

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: syntaxTrees,
                references: referenceFeature.MetadataReferences,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var pdbMs = new MemoryStream())
                using (var ms = new MemoryStream())
                {
                    EmitResult result;
                    Stopwatch  stopWatch = new Stopwatch();
                    stopWatch.Start();
                    if (!string.IsNullOrEmpty(outputLocation))
                    {
                        result = compilation.Emit(outputLocation + assemblyName + ".dll", outputLocation + assemblyName + ".pdb");
                    }
                    else
                    {
                        result = compilation.Emit(ms, pdbMs);
                    }

                    stopWatch.Stop();
                    compilationResult.TimeUsed = stopWatch.Elapsed;

                    compilationResult.CompilationInfo = new List <CompilationInfo>();
                    foreach (Diagnostic diag in result.Diagnostics)
                    {
                        // TODO: Decide how to handle this special CS1701 we get
                        if (!diag.Id.Equals("CS1701"))
                        {
                            var compInfo = new CompilationInfo
                            {
                                Info         = diag.GetMessage(),
                                FilePath     = diag.Location.SourceTree.FilePath,
                                FileName     = System.IO.Path.GetFileName(diag.Location.SourceTree.FilePath),
                                Severity     = diag.Severity.ToString(),
                                Code         = diag.Id,
                                WarningLevel = diag.WarningLevel,
                                LineNumber   = diag.Location.GetLineSpan().StartLinePosition.Line + 1,
                            };

                            if (diag.Severity.Equals(DiagnosticSeverity.Warning))
                            {
                                compilationResult.Warnings++;
                            }
                            else if (diag.Severity.Equals(DiagnosticSeverity.Error))
                            {
                                compilationResult.Errors++;
                            }

                            compilationResult.CompilationInfo.Add(compInfo);
                        }
                    }

                    if (!result.Success)
                    {
                        LogEmitResult(result);
                    }
                    else
                    {
                        compilationResult.AssemblyName = compilation.AssemblyName;
                        compilationResult.Succeeded    = true;

                        if (string.IsNullOrEmpty(outputLocation) && loadAssemblyContext)
                        {
                            ms.Seek(0, SeekOrigin.Begin);
                            pdbMs.Seek(0, SeekOrigin.Begin);
                            AssemblyLoadContext.Default.LoadFromStream(ms, pdbMs);
                            ms.Seek(0, SeekOrigin.Begin);
                            MetadataReference newReference = MetadataReference.CreateFromStream(ms);
                            if (_roslynCompilation.ServiceReferences.ContainsKey(assemblykey))
                            {
                                _roslynCompilation.ServiceReferences.Remove(assemblykey);
                            }

                            _roslynCompilation.ServiceReferences.Add(assemblykey, newReference);

                            if (_assemblyNames.ContainsKey(assemblykey))
                            {
                                _assemblyNames.Remove(assemblykey);
                            }

                            _assemblyNames.Add(assemblykey, compilationResult);
                        }

                        return(compilationResult);
                    }
                }

            return(compilationResult);
        }
Exemple #4
0
        /// <inheritdoc/>
        public IServiceImplementation GetServiceImplementation(string org, string app, bool startAppFlag)
        {
            string assemblyName           = LoadServiceAssembly(org, app, startAppFlag);
            string implementationTypeName = string.Format(CodeGeneration.ServiceNamespaceTemplate, org, CompileHelper.GetCSharpValidAppId(app)) + ".ServiceImplementation," + assemblyName;

            return((IServiceImplementation)Activator.CreateInstance(Type.GetType(implementationTypeName)));
        }