Example #1
0
        private void Interprete(FunctionMap map, bool reverse, Run run)
        {
            int currentWalk = 0;

            foreach (List <FunctionID> original in stackWalks)
            {
                currentWalk++;
                List <FunctionID> stackWalk;
                if (reverse)
                {
                    stackWalk = new List <FunctionID>(original);
                    stackWalk.Reverse();
                }
                else
                {
                    stackWalk = original;
                }
                for (int i = 0; i < stackWalk.Count; i++)
                {
                    Function function = Run.GetFunctionInfo(map, stackWalk[stackWalk.Count - i - 1], run, reverse);
                    if (function.lastWalk != currentWalk)
                    {
                        function.Samples++;
                        function.stackWalks.Add(new StackWalk(currentWalk, stackWalk.Count - i - 1, stackWalk));
                    }
                    function.lastWalk = currentWalk;
                }
            }
            //foreach (List<FunctionID> stackWalk in stackWalks)
            //{
            //    Function f = Run.GetFunctionInfo(map, stackWalk[0], run);
            //    f.ExclusiveSamples++;
            //}
        }
        private AggregateFunctionContext CreateMemberContext(ClassMappingDescriptor descriptor, MemberMappingDescriptor member, FunctionMap functionMap)
        {
            Type implementationType = functionMap.GetTypeForFunction(member.AggregateMappingDescription.FunctionName);
            string functionObjectName = string.Format("_{0}_to_{1}_Fn_",
                member.AggregateMappingDescription.FunctionObject,
                member.Member);
            if (implementationType.IsGenericType)
            {
                if (member.IsArray || member.IsList)
                {
                    Type instanceType = member.IsArray ?
                        member.AggregateMappingDescription.TargetType.GetElementType() :
                        member.AggregateMappingDescription.TargetType.GetGenericArguments()[0];
                    implementationType = implementationType.MakeGenericType(instanceType);
                }
                else
                {
                    implementationType = implementationType.MakeGenericType(member.AggregateMappingDescription.TargetType);
                }
            }

            IAggregateFunctionCodeGenerator generator = GetGeneratorImpl(implementationType, member);

            return new AggregateFunctionContext(member,
                                descriptor,
                                implementationType,
                                functionObjectName,
                                generator);
        }
Example #3
0
 public void Registration_Suceeds_For_Well_Implemented_Aggregate_Function()
 {
     FunctionMap map = new FunctionMap();
     map.Register("test", typeof(TestFn<int>));
     Type t1 = typeof(TestFn<int>);
     Type t2 = map.GetTypeForFunction("test");
     Assert.AreEqual(typeof(TestFn<int>), map.GetTypeForFunction("test"));
 }
        public AggregateExpressionBuilder(ClassMappingDescriptor descriptor, ICollection<MemberMappingDescriptor> members, FunctionMap functionMap)
        {
            m_contexts = new List<AggregateFunctionContext>(members.Count);

            foreach (MemberMappingDescriptor member in members)
            {
                m_contexts.Add(CreateMemberContext(descriptor, member, functionMap));
            }
        }
Example #5
0
        public static Function GetFunctionInfo(FunctionMap functions, FunctionID id, Run run, bool reverse)
        {
            Function result;

            if (!functions.TryGetValue(id, out result))
            {
                result        = new Function(id, run, reverse);
                functions[id] = result;
            }
            return(result);
        }
Example #6
0
        public IWasmicSyntaxTree ParseText(string text)
        {
            var lexer       = new WasmicLexer(text);
            var functionMap = new FunctionMap();
            var functions   = new List <IWasmicSyntaxTree>();
            var functionDefinitionGenerator = new FunctionDefinitionParser();
            var heap = new LinearHeap();

            while (lexer.Next.TokenType != TokenType.EndOfText)
            {
                switch (lexer.Next.TokenType)
                {
                case TokenType.Extern:
                    lexer.Advance();     // eat extern
                    var functionDefinition = functionDefinitionGenerator.Generate(lexer);
                    functionMap.Add(functionDefinition);
                    functions.Add(new Import(functionDefinition.Name.Split('.'), functionDefinition));
                    break;

                default:
                    var functionGenerator = new FunctionParser(
                        lexer,
                        functionMap,
                        functionDefinitionGenerator,
                        heap
                        );
                    var function = functionGenerator.GetFunction();
                    functions.Add(function);
                    break;
                }

                if (lexer.Next.TokenType == TokenType.SemiColon)
                {
                    lexer.Advance();
                }
            }

            if (heap.IsAllocated)
            {
                functions = new[] { new Memory() }
                .Concat(heap.GetAllocatedStrings().Select(v => new Data(v.offset, v.value) as IWasmicSyntaxTree))
                .Concat(functions).ToList();
            }

            return(new Module(functions));
        }
Example #7
0
 public void Update(Run run, FunctionMap functions)
 {
     this.functions = functions;
     currentRun     = run;
     SuspendLayout();
     Invalidate();
     BeginUpdate();
     foreach (Function method in SortFunctions(functions.Values))
     {
         AddItem(Nodes, method);
     }
     foreach (TreeNode item in Nodes)
     {
         EnsureComputed(item);
     }
     EndUpdate();
     ResumeLayout();
 }
Example #8
0
        public void Update(Run run, FunctionMap functions)
        {
            this.Nodes.Clear();
            updating       = true;
            this.run       = run;
            this.functions = functions;
            BeginUpdate();
            List <Function> functionList = new List <Function>(functions.Values);

            functionList.Sort(new Comparison <Function>(delegate(Function a, Function b)
            {
                return(a.Signature.Namespace.CompareTo(b.Signature.Namespace));
            }));
            foreach (Function function in functionList)
            {
                if (function.Signature.Namespace == "")
                {
                    continue;
                }
                TreeNodeCollection items = this.Nodes;
                foreach (string name in function.Signature.Namespace.Split('.'))
                {
                    bool found = false;
                    foreach (TreeNode item in items)
                    {
                        if (item.Text == name)
                        {
                            items = item.Nodes;
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        TreeNode item = items.Add(name, name);
                        item.Checked = true;
                        items        = item.Nodes;
                    }
                }
            }
            EndUpdate();
            updating = false;
        }
Example #9
0
        private async Task OnActivityStateChanged(ActivityEventArgs eventArgs)
        {
            _retryCancellationTokenSource.Cancel();
            _retryCancellationTokenSource = new CancellationTokenSource();

            var logTimeModel = new LogTimeModel()
            {
                IsActive  = eventArgs.IsActive,
                Timestamp = eventArgs.TimeStamp,
            };

            var httpContent = new StringContent(
                JsonSerializer.Serialize(logTimeModel),
                Encoding.UTF8,
                "application/json");

            await _retryPolicy.ExecuteAsync(
                (ctx, ct) => _httpClient.PostAsync(FunctionMap.Get(Function.LogTime), httpContent, ct),
                _retryContext,
                _retryCancellationTokenSource.Token);
        }
        public async Task TryRefreshToken(CancellationToken?cancellationToken = null)
        {
            using var request = new HttpRequestMessage(HttpMethod.Get, FunctionMap.Get(Function.RefreshJwtToken));
            request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include);
            var response = await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None);

            string jwtToken = null !;

            if (response.IsSuccessStatusCode)
            {
                var responseString = await response.Content.ReadAsStringAsync();

                if (!responseString.IsNullOrEmpty())
                {
                    var refreshTokenResult = JsonSerializer.Deserialize <RefreshTokenResult>(responseString);

                    jwtToken = refreshTokenResult.Token;
                }
            }

            _authService.JwtToken = jwtToken;
        }
Example #11
0
 public void Retrieving_Unregistered_Function_Fails()
 {
     FunctionMap map = new FunctionMap();
     map.GetTypeForFunction("test");
 }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cs"></param>
        public NameSection(CustomSection cs)
        {
            var stream           = new MemoryStream((byte[])cs.Content);
            var reader           = new Reader(stream);
            var previousSection  = NameSubsection.Module;
            var preSectionOffset = reader.Offset;

            while (reader.TryReadVarUInt7(out var id)) //At points where TryRead is used, the stream can safely end.
            {
                if (id != 0 && (NameSubsection)id < previousSection)
                {
                    throw new ModuleLoadException($"Sections out of order; section {(NameSubsection)id} encounterd after {previousSection}.", preSectionOffset);
                }
                var payloadLength = reader.ReadVarUInt32();

                switch ((NameSubsection)id)
                {
                case NameSubsection.Module:
                {
                    var nameLength = reader.ReadVarUInt32();
                    Name = reader.ReadString(nameLength);
                }
                break;

                case NameSubsection.Function:
                {
                    var count = reader.ReadVarUInt32();
                    Functions = new FunctionMap((int)count);
                    for (int i = 0; i < count; i++)
                    {
                        var index      = reader.ReadVarUInt32();
                        var nameLength = reader.ReadVarUInt32();
                        var name       = reader.ReadString(nameLength);
                        Functions.Add(index, name);
                    }
                }
                break;

                case NameSubsection.Local:
                {
                    var fun_count = reader.ReadVarUInt32();
                    Locals = new LocalMap((int)fun_count);
                    for (int f = 0; f < fun_count; f++)
                    {
                        var fun_index = reader.ReadVarUInt32();

                        var count   = reader.ReadVarUInt32();
                        var nameMap = new NameMap((int)count);
                        Locals.Add(fun_index, nameMap);
                        for (int i = 0; i < count; i++)
                        {
                            var index      = reader.ReadVarUInt32();
                            var nameLength = reader.ReadVarUInt32();
                            var name       = reader.ReadString(nameLength);
                            nameMap.Add(index, name);
                        }
                    }
                }
                break;
                }

                previousSection = (NameSubsection)id;
            }
        }
Example #13
0
 public void Registration_Fails_If_Type_Doesnt_Implement_IAggregateFunction()
 {
     FunctionMap map = new FunctionMap();
     map.Register("test", typeof(string));
 }
 public CodeGeneratorContext(IList<IMappingDescriptorProvider> providers, FunctionMap functionMap, AssemblerGenerationOptions options)
 {
     m_providers = providers;
     m_functionMap = functionMap;
     m_options = options;
 }
        public async Task ReturnsUnauthorizedResultIfNotAuthenticated()
        {
            // Arrange
            var request = new DefaultHttpContext().Request;

            string xsrfToken = $"xsrf-token-{DateTime.Now.Ticks}";

            request.Headers.Add("Cookie", new CookieHeaderValue(Globals.XsrfTokenCookieAndHeaderName, xsrfToken).ToString());
            request.Headers.Add(Globals.XsrfTokenCookieAndHeaderName, xsrfToken);

            var durableClientMoq = new Mock <IDurableClient>();
            var logMoq           = new Mock <ILogger>();

            // Getting the list of all functions to be validated
            var functionsToBeCalled = typeof(DfmEndpoint).Assembly.DefinedTypes
                                      .Where(t => t.IsClass)
                                      .SelectMany(t => t.GetMethods(BindingFlags.Static | BindingFlags.Public))
                                      .Where(m => m.CustomAttributes.Any(a => a.AttributeType == typeof(FunctionNameAttribute)))
                                      .Select(m => m.Name)
                                      .ToHashSet();

            // Only these two methods should be publicly accessible as of today
            functionsToBeCalled.Remove(nameof(ServeStatics.DfmServeStaticsFunction));
            functionsToBeCalled.Remove(nameof(EasyAuthConfig.DfmGetEasyAuthConfigFunction));

            // Collecting the list of functions that were actually called by this test
            var functionsThatWereCalled = new HashSet <string>();

            logMoq.Setup(log => log.Log(It.IsAny <LogLevel>(), It.IsAny <EventId>(), It.IsAny <It.IsAnyType>(), It.IsAny <Exception>(), It.IsAny <Func <It.IsAnyType, Exception, string> >()))
            .Callback((LogLevel l, EventId i, object s, Exception ex, object o) =>
            {
                // Ensuring the correct type of exception was raised internally
                Assert.IsInstanceOfType(ex, typeof(UnauthorizedAccessException));
                Assert.AreEqual("No access token provided. Call is rejected.", ex.Message);

                // Also extracting the function name, that was called, from current stack trace
                foreach (var stackFrame in new StackTrace().GetFrames())
                {
                    var method = stackFrame.GetMethod();
                    if (method.CustomAttributes.Any(a => a.AttributeType == typeof(FunctionNameAttribute)))
                    {
                        functionsThatWereCalled.Add(method.Name);
                    }
                }
            });

            Environment.SetEnvironmentVariable(EnvVariableNames.DFM_HUB_NAME, string.Empty);

            // Act
            var results = new List <IActionResult>()
            {
                await About.DfmAboutFunction(request, "-", "TestHub", logMoq.Object),

                await new CleanEntityStorage(null).DfmCleanEntityStorageFunction(request, durableClientMoq.Object, "-", "TestHub", logMoq.Object),

                await new DeleteTaskHub(null).DfmDeleteTaskHubFunction(request, durableClientMoq.Object, "-", "TestHub", logMoq.Object),

                await new IdSuggestions(null).DfmGetIdSuggestionsFunction(request, durableClientMoq.Object, "-", "TestHub", "abc", logMoq.Object),

                await ManageConnection.DfmManageConnectionFunction(request, "-", "TestHub", new Microsoft.Azure.WebJobs.ExecutionContext(), logMoq.Object),

                await new IdSuggestions(null).DfmGetIdSuggestionsFunction(request, durableClientMoq.Object, "-", "TestHub", "abc", logMoq.Object),

                await new Orchestration(null).DfmGetOrchestrationFunction(request, durableClientMoq.Object, "-", "TestHub", "abc", logMoq.Object),

                await new Orchestration(null).DfmGetOrchestrationHistoryFunction(request, durableClientMoq.Object, "-", "TestHub", "abc", logMoq.Object),

                await new Orchestration(null).DfmStartNewOrchestrationFunction(request, durableClientMoq.Object, "-", "TestHub", logMoq.Object),

                await new Orchestration(null).DfmPostOrchestrationFunction(request, durableClientMoq.Object, "-", "TestHub", "abc", "todo", logMoq.Object),

                await new Orchestration(null).DfmGetOrchestrationTabMarkupFunction(request, durableClientMoq.Object, "-", "TestHub", "abc", "todo", logMoq.Object),

                await new Orchestrations(null).DfmGetOrchestrationsFunction(request, durableClientMoq.Object, "-", "TestHub", logMoq.Object),

                await new PurgeHistory(null).DfmPurgeHistoryFunction(request, durableClientMoq.Object, "-", "TestHub", logMoq.Object),

                await TaskHubNames.DfmGetTaskHubNamesFunction(request, logMoq.Object),

                await FunctionMap.DfmGetFunctionMap(request, "-", "TestHub", logMoq.Object),
            };

            // Assert
            results.ForEach(r => Assert.IsInstanceOfType(r, typeof(UnauthorizedResult)));

            functionsToBeCalled.ExceptWith(functionsThatWereCalled);
            Assert.IsTrue(functionsToBeCalled.Count == 0, "You forgot to test " + string.Join(", ", functionsToBeCalled));
        }
        public AggregateExpressionBuilder(ClassMappingDescriptor descriptor, ICollection <MemberMappingDescriptor> members, FunctionMap functionMap)
        {
            m_contexts = new List <AggregateFunctionContext>(members.Count);

            foreach (MemberMappingDescriptor member in members)
            {
                m_contexts.Add(CreateMemberContext(descriptor, member, functionMap));
            }
        }
        private AggregateFunctionContext CreateMemberContext(ClassMappingDescriptor descriptor, MemberMappingDescriptor member, FunctionMap functionMap)
        {
            Type   implementationType = functionMap.GetTypeForFunction(member.AggregateMappingDescription.FunctionName);
            string functionObjectName = string.Format("_{0}_to_{1}_Fn_",
                                                      member.AggregateMappingDescription.FunctionObject,
                                                      member.Member);

            if (implementationType.IsGenericType)
            {
                if (member.IsArray || member.IsList)
                {
                    Type instanceType = member.IsArray ?
                                        member.AggregateMappingDescription.TargetType.GetElementType() :
                                        member.AggregateMappingDescription.TargetType.GetGenericArguments()[0];
                    implementationType = implementationType.MakeGenericType(instanceType);
                }
                else
                {
                    implementationType = implementationType.MakeGenericType(member.AggregateMappingDescription.TargetType);
                }
            }

            IAggregateFunctionCodeGenerator generator = GetGeneratorImpl(implementationType, member);

            return(new AggregateFunctionContext(member,
                                                descriptor,
                                                implementationType,
                                                functionObjectName,
                                                generator));
        }