Пример #1
1
        public override void Execute(IProcessExecutionContext executionContext, IWorkSession session, ITransaction transaction, ISerializedParameters parameters)
        {
            try
            {
                if (!parameters.ContainsKey("ActionName"))
                {
                    throw new Exception("ContextRecordAction requires a parameter for ActionName");
                }

                var contextRecord = transaction.TransactionContext;
                var dataRecord    = transaction.DataRecord;

                var req = new OrganizationRequest(parameters["ActionName"]);
                req["Target"]      = new EntityReference(contextRecord.RecordType, contextRecord.Id);
                req["Transaction"] = transaction.ToEntityReference();
                req["DataRecord"]  = new EntityReference(dataRecord.RecordType, dataRecord.Id);

                //process any additional parameter data passed in from the configuration.
                if (parameters.Count > 1)
                {
                    foreach (var key in parameters.Keys)
                    {
                        if (key != "ActionName" && !string.IsNullOrEmpty(parameters[key]))
                        {
                            req[key] = parameters[key];
                        }
                    }
                }

                executionContext.DataService.ToOrgService().Execute(req);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
Пример #2
0
        public void Serialize(ExecutionResult result, IFastJsonWriter writer, IWorkSession session)
        {
            writer.WriteStartObject();

            writer.WritePropertyStartArray("output");
            SerializeOutput(result.Output, writer);
            writer.WriteEndArray();

            writer.WritePropertyStartArray("flow");
            foreach (var step in result.Flow)
            {
                SerializeFlowStep(step, writer);
            }
            writer.WriteEndArray();

            if (session.GetContainerExperimentException() is {} exception&& !session.WasContainerExperimentExceptionReported())
            {
                writer.WriteProperty("containerExperimentException", exception.ToString());
                session.SetContainerExperimentExceptionReported(true);
            }

            writer.WriteEndObject();
        }
Пример #3
0
        public ImmutableArray <string?> GetCallArgumentIdentifiers(IWorkSession session, int callStartLine, int callStartColumn)
        {
            var call = RoslynAdapterHelper.FindSyntaxNodeInSession(session, callStartLine, callStartColumn) as InvocationExpressionSyntax;

            if (call == null)
            {
                return(ImmutableArray <string?> .Empty);
            }

            var arguments = call.ArgumentList.Arguments;

            if (arguments.Count == 0)
            {
                return(ImmutableArray <string?> .Empty);
            }

            var results = new string?[arguments.Count];

            for (var i = 0; i < arguments.Count; i++)
            {
                results[i] = (arguments[i].GetExpression() is IdentifierNameSyntax n) ? n.Identifier.ValueText : null;
            }
            return(ImmutableArray.Create(results));
        }
Пример #4
0
        public void WriteResult(IFastJsonWriter writer, object result, IWorkSession session)
        {
            if (result == null)
            {
                writer.WriteValue(null);
                return;
            }

            var targetName = session.GetTargetName();

            if (session.GetTargetName() == AstTargetName)
            {
                var astTarget = _astTargets.GetValueOrDefault(session.LanguageName);
                astTarget.SerializeAst(result, writer, session);
                return;
            }

            var decompiler = _decompilers[targetName];

            using (var stream = (Stream)result)
                using (var stringWriter = writer.OpenString()) {
                    decompiler.Decompile(stream, stringWriter);
                }
        }
Пример #5
0
        protected override ExecutionResultWithException ExecuteWithIsolation(MemoryStream assemblyStream, RuntimeGuardToken guardToken, IWorkSession session)
        {
            using (var context = new CustomAssemblyLoadContext(shouldShareAssembly: _ => false)) {
                var assembly       = context.LoadFromStream(assemblyStream);
                var serverAssembly = context.LoadFromAssemblyPath(Current.AssemblyPath);

                var coreType = serverAssembly.GetType(typeof(IsolatedExecutorCore).FullName);
                var execute  = coreType.GetMethod(nameof(IsolatedExecutorCore.Execute));

                var wrapperInContext = execute.Invoke(null, new object[] { assembly, guardToken.Guid, Current.ProcessId, ProfilerState.Active });
                // Since wrapperInContext belongs to a different AssemblyLoadContext, it is not possible to convert
                // it to same type in the default context without some trick (e.g. serialization).
                using (var wrapperStream = _memoryStreamManager.GetStream())
                {
                    var formatter = new BinaryFormatter();
                    formatter.Serialize(wrapperStream, wrapperInContext);
                    wrapperStream.Seek(0, SeekOrigin.Begin);
                    return((ExecutionResultWithException)formatter.Deserialize(wrapperStream));
                }
            }
        }
Пример #6
0
 public abstract bool Rollback(IProcessExecutionContext executionContext, IWorkSession session, ITransaction transaction, ISerializedParameters parameters);
Пример #7
0
        private async Task <bool> TryCompileFSharpToStreamAsync(MemoryStream assemblyStream, IWorkSession session, IList <Diagnostic> diagnostics, CancellationToken cancellationToken)
        {
            var fsharp = session.FSharp();

            // GetLastParseResults are guaranteed to be available here as MirrorSharp's SlowUpdate does the parse
            var parsed = fsharp.GetLastParseResults();

            using (var virtualAssemblyFile = FSharpFileSystem.RegisterVirtualFile(assemblyStream)) {
                var compiled = await FSharpAsync.StartAsTask(fsharp.Checker.Compile(
                                                                 // ReSharper disable once PossibleNullReferenceException
                                                                 FSharpList <Ast.ParsedInput> .Cons(parsed.ParseTree.Value, FSharpList <Ast.ParsedInput> .Empty),
                                                                 "_", virtualAssemblyFile.Name,
                                                                 fsharp.AssemblyReferencePathsAsFSharpList,
                                                                 pdbFile: null,
                                                                 executable: false,
                                                                 noframework: true
                                                                 ), null, cancellationToken).ConfigureAwait(false);

                foreach (var error in compiled.Item1)
                {
                    // no reason to add warnings as check would have added them anyways
                    if (error.Severity.Tag == FSharpErrorSeverity.Tags.Error)
                    {
                        diagnostics.Add(fsharp.ConvertToDiagnostic(error));
                    }
                }
                return(virtualAssemblyFile.Stream.Length > 0);
            }
        }
Пример #8
0
 public ImmutableArray <int> GetMethodParameterLines(IWorkSession session, int lineInMethod, int columnInMethod)
 {
     return(ImmutableArray <int> .Empty); // not supported yet
 }
Пример #9
0
 private void SerializeAst(RoslynAst ast, IFastJsonWriter writer, IWorkSession session)
 {
     writer.WriteStartArray();
     SerializeNode(ast.SyntaxRoot, ast.SemanticModel, writer);
     writer.WriteEndArray();
 }
Пример #10
0
        public async Task <(bool assembly, bool symbols)> TryCompileToStreamAsync(MemoryStream assemblyStream, MemoryStream?symbolStream, IWorkSession session, IList <Diagnostic> diagnostics, CancellationToken cancellationToken)
        {
            PerformanceLog.Checkpoint("Compiler.TryCompileToStreamAsync.Start");
            if (session.IsFSharp())
            {
                var compiled = await TryCompileFSharpToStreamAsync(assemblyStream, session, diagnostics, cancellationToken).ConfigureAwait(false);

                return(compiled, false);
            }

            #warning TODO: Revisit after https://github.com/dotnet/docs/issues/14784
            var compilation = (await session.Roslyn.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false)) !;
            var emitResult  = compilation.Emit(assemblyStream, pdbStream: symbolStream, options: RoslynEmitOptions);
            PerformanceLog.Checkpoint("Compiler.TryCompileToStreamAsync.Emit.End");
            if (!emitResult.Success)
            {
                foreach (var diagnostic in emitResult.Diagnostics)
                {
                    diagnostics.Add(diagnostic);
                }
                return(false, false);
            }
            return(true, true);
        }
Пример #11
0
        private ExecutionResult ExecuteInAppDomain(MemoryStream assemblyStream, RuntimeGuardToken guardToken, IWorkSession session)
        {
            var currentSetup = AppDomain.CurrentDomain.SetupInformation;

            using (var context = AppDomainContext.Create(new AppDomainSetup {
                ApplicationBase = currentSetup.ApplicationBase,
                PrivateBinPath = currentSetup.PrivateBinPath
            })) {
                context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                var(result, exception) = RemoteFunc.Invoke(context.Domain, assemblyStream, guardToken, CurrentProcess.Id, Remote.Execute);
                if (ShouldMonitorException(exception))
                {
                    _monitor.Exception(exception, session);
                }
                return(result);
            }
        }
Пример #12
0
 public static bool HasContainerExperimentFailed(this IWorkSession session)
 {
     return(session.GetContainerExperimentException() != null);
 }
Пример #13
0
 public static void SetContainerExperimentExceptionReported(this IWorkSession session, bool value)
 {
     session.ExtensionData["ContainerExperimentExceptionReported"] = true;
 }
Пример #14
0
 public static bool WasContainerExperimentExceptionReported(this IWorkSession session)
 {
     return((bool?)session.ExtensionData.GetValueOrDefault("ContainerExperimentExceptionReported") ?? false);
 }
Пример #15
0
 public static void SetContainerExperimentException(this IWorkSession session, Exception exception)
 {
     session.ExtensionData["ContainerExperimentException"] = exception;
 }
Пример #16
0
 public void Event(string name, IWorkSession session, IDictionary <string, string> extras = null)
 {
     Trace.TraceInformation("[{0}] Event '{0}'.", session?.GetSessionId(), name);
 }
Пример #17
0
 public void SerializeAst(object ast, IFastJsonWriter writer, IWorkSession session)
 {
     SerializeAst((RoslynAst)ast, writer, session);
 }
Пример #18
0
        public async Task <object?> ProcessAsync(IWorkSession session, IList <Diagnostic> diagnostics, CancellationToken cancellationToken)
        {
            PerformanceLog.Checkpoint("SlowUpdate.ProcessAsync.Start");
            var targetName = GetAndEnsureTargetName(session);

            if (targetName == TargetNames.Ast || targetName == TargetNames.Explain)
            {
                var astTarget = _astTargets[session.LanguageName];
                var ast       = await astTarget.GetAstAsync(session, cancellationToken).ConfigureAwait(false);

                if (targetName == TargetNames.Explain)
                {
                    return(await _explainer.ExplainAsync(ast, session, cancellationToken).ConfigureAwait(false));
                }
                return(ast);
            }

            if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                return(null);
            }

            if (targetName == LanguageNames.VisualBasic)
            {
                return(VisualBasicNotAvailable);
            }

            if (targetName != TargetNames.Run && targetName != TargetNames.Verify && !_decompilers.ContainsKey(targetName))
            {
                throw new NotSupportedException($"Target '{targetName}' is not (yet?) supported by this branch.");
            }

            MemoryStream?assemblyStream = null;
            MemoryStream?symbolStream   = null;

            try {
                assemblyStream = _memoryStreamManager.GetStream();
                if (targetName == TargetNames.Run || targetName == TargetNames.IL)
                {
                    symbolStream = _memoryStreamManager.GetStream();
                }

                var compiled = await _compiler.TryCompileToStreamAsync(assemblyStream, symbolStream, session, diagnostics, cancellationToken).ConfigureAwait(false);

                if (!compiled.assembly)
                {
                    assemblyStream.Dispose();
                    symbolStream?.Dispose();
                    return(null);
                }

                if (targetName == TargetNames.Verify)
                {
                    assemblyStream.Dispose();
                    symbolStream?.Dispose();
                    return("✔️ Compilation completed.");
                }

                assemblyStream.Seek(0, SeekOrigin.Begin);
                symbolStream?.Seek(0, SeekOrigin.Begin);
                var streams = new CompilationStreamPair(assemblyStream, compiled.symbols ? symbolStream : null);
                if (targetName == TargetNames.Run)
                {
                    return(_executor.Execute(streams, session));
                }

                // it's fine not to Dispose() here -- MirrorSharp will dispose it after calling WriteResult()
                return(streams);
            }
            catch {
                assemblyStream?.Dispose();
                symbolStream?.Dispose();
                throw;
            }
        }
Пример #19
0
 public void SetOptionsForTarget([NotNull] IWorkSession session, [NotNull] string target)
 {
     // I don't use `exe` for Run, see FSharpEntryPointRewriter
 }
Пример #20
0
        public async Task <object> GetAstAsync(IWorkSession session, CancellationToken cancellationToken)
        {
            var document = session.Roslyn.Project.Documents.Single();

            return(await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false));
        }
Пример #21
0
 /// <summary>Specifies whether the <see cref="IWorkSession" /> is using F#.</summary>
 /// <param name="session">The session</param>
 /// <returns><c>true</c> if the session is using F#; otherwise, <c>false</c></returns>
 public static bool IsFSharp(this IWorkSession session)
 {
     Argument.NotNull(nameof(session), session);
     return(((WorkSession)session).LanguageSession is IFSharpSession);
 }
Пример #22
0
 public void SerializeAst(object ast, IFastJsonWriter writer, IWorkSession session)
 {
     writer.WriteStartArray();
     SerializeNode((SyntaxNode)ast, writer);
     writer.WriteEndArray();
 }
Пример #23
0
        public async Task <bool> TryCompileToStreamAsync(MemoryStream assemblyStream, IWorkSession session, IList <Diagnostic> diagnostics, CancellationToken cancellationToken)
        {
            if (session.IsFSharp())
            {
                return(await TryCompileFSharpToStreamAsync(assemblyStream, session, diagnostics, cancellationToken));
            }

            var compilation = await session.Roslyn.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

            var emitResult = compilation.Emit(assemblyStream);

            if (!emitResult.Success)
            {
                foreach (var diagnostic in emitResult.Diagnostics)
                {
                    diagnostics.Add(diagnostic);
                }
                return(false);
            }
            return(true);
        }
Пример #24
0
        private void TryInsertReportMethodArguments(ILProcessor il, Instruction instruction, SequencePoint sequencePoint, MethodDefinition method, ReportMethods flow, IWorkSession session, ref int index)
        {
            if (!method.HasParameters)
            {
                return;
            }

            var parameterLines = _languages[session.LanguageName]
                                 .GetMethodParameterLines(session, sequencePoint.StartLine, sequencePoint.StartColumn);

            if (parameterLines.Length == 0)
            {
                return;
            }

            // Note: method parameter lines are unreliable and can potentially return
            // wrong lines if nested method syntax is unrecognized and code matches it
            // to the containing method. That is acceptable, as long as parameter count
            // mismatch does not crash things -> so check length here.
            if (parameterLines.Length != method.Parameters.Count)
            {
                return;
            }

            foreach (var parameter in method.Parameters)
            {
                if (parameter.IsOut)
                {
                    continue;
                }

                InsertReportValue(
                    il, instruction,
                    il.CreateLdargBest(parameter), parameter.ParameterType, parameter.Name,
                    parameterLines[parameter.Index], flow,
                    ref index
                    );
            }
        }
Пример #25
0
 public abstract void Execute(IProcessExecutionContext executionContext, IWorkSession session, ITransaction transaction, ISerializedParameters parameters);
Пример #26
0
        private (string name, TypeReference type)? GetValueToReport(Instruction instruction, ILProcessor il, IWorkSession session)
        {
            var localIndex = GetIndexIfStloc(instruction);

            if (localIndex != null)
            {
                var variable = il.Body.Variables[localIndex.Value];
                var symbols  = il.Body.Method.DebugInformation;
                if (symbols == null || !symbols.TryGetName(variable, out var variableName))
                {
                    return(null);
                }

                return(variableName, variable.VariableType);
            }

            if (instruction.OpCode.Code == Code.Ret)
            {
                if (instruction.Previous?.Previous?.OpCode.Code == Code.Tail)
                {
                    return(null);
                }
                var returnType = il.Body.Method.ReturnType;
                if (returnType.IsVoid())
                {
                    return(null);
                }
                return("return", returnType);
            }

            return(null);
        }
 public bool TryGetById(string id, out IWorkSession item)
 {
     item = _Repo.FirstOrDefault(i => i.Id == id);
     return(item != null);
 }
        public IStepExecutionResult Execute(IProcessExecutionContext executionContext, IWorkSession session, ITransaction transaction, IRequirementEvaluator requirementEvaluator)
        {
            try
            {
                bool blockProgress = false;
                bool isValid       = true;

                Type.ValidateStepParameters(executionContext, Parameters);

                //complete any specific implementation for the step type
                Type.Execute(executionContext, session, transaction, Parameters);

                if (ValidationRequirements.Count > 0)
                {
                    var requirementPointers = ValidationRequirements.Select(r => r.RequirementId).ToList();
                    var deficiencies        = requirementEvaluator.Evaluate(executionContext, transaction, requirementPointers);

                    if (deficiencies.Count > 0)
                    {
                        isValid = false;

                        //if any validation requirement is configured to block progress and there is a deficiency for that requirement
                        //then the step is blocked.
                        foreach (var r in ValidationRequirements)
                        {
                            if (r.BlockProcessProgress && deficiencies.Where(d => d.Requirement.Id == r.RequirementId.Id).FirstOrDefault() != null)
                            {
                                blockProgress = true;
                            }
                        }
                    }
                }

                var nextStep = getNextStep(executionContext, transaction);

                return(new StepExecutionResult
                {
                    StepIsBlocked = blockProgress,
                    StepIsValid = isValid,
                    NextStep = nextStep
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
Пример #29
0
        protected override ExecutionResultWithException ExecuteWithIsolation(MemoryStream assemblyStream, RuntimeGuardToken guardToken, IWorkSession session)
        {
            var currentSetup = AppDomain.CurrentDomain.SetupInformation;

            using (var context = AppDomainContext.Create(new AppDomainSetup {
                ApplicationBase = currentSetup.ApplicationBase,
                PrivateBinPath = currentSetup.PrivateBinPath
            })) {
                context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                return(RemoteFunc.Invoke(context.Domain, assemblyStream.ToArray(), guardToken, Current.ProcessId, ProfilerState.Active, Remote.Execute));
            }
        }
Пример #30
0
 public void Exception(Exception exception, IWorkSession session, IDictionary <string, string> extras = null)
 {
     Trace.TraceError("[{0}] Exception: {0}.", session?.GetSessionId(), exception);
 }