Exemplo n.º 1
0
        public Graph Convert(BuildGraph buildGraph, GraphDepth depth)
        {
            var aglGraph = new Graph();

            foreach (var buildNode in buildGraph.Nodes)
            {
                string id = this.GetNodeId(buildNode);

                var aglNode = aglGraph.AddNode(id);
                this.DecorateNode(aglNode, buildNode, depth);
            }

            // Add the edges once all the nodes are in the graph
            foreach (var buildNode in buildGraph.Nodes)
            {
                string idFrom = this.GetNodeId(buildNode);

                foreach (var buildEdge in buildNode.OutgoingEdges)
                {
                    string idTo = this.GetNodeId(buildEdge.To);

                    var aglEdge = aglGraph.AddEdge(idFrom, idTo);
                    this.DecorateEdge(aglEdge, buildEdge);
                }
            }

            return(aglGraph);
        }
Exemplo n.º 2
0
//Returns a list with the graph and other info for testing
        public static List <object> ValidRandom()
        {
            var random = new Random();
            var graph  = BuildGraph.SetGraphType(random.Next(1, 2));

            var numberOfVertices = random.Next(2, 50);

            for (var i = 0; i < numberOfVertices; i++)
            {
                graph.AddVertex(new Vertex(RNGHelpers.GetUniqueKey(random.Next(4, 16))));
            }

            var numberOfAdjacenciesToAdd = random.Next(6, 32);

            for (var i = 0; i < numberOfAdjacenciesToAdd; i++)
            {
                graph.AddEdge(graph.MyGraph[random.Next(2, numberOfVertices - 1)], graph.MyGraph[random.Next(2, numberOfVertices - 1)], random.Next(0, 500));
            }

            var list = new List <object>();

            list.Add(graph);
            list.Add(numberOfVertices);
            list.Add(numberOfAdjacenciesToAdd);
            return(list);
        }
            /// <summary>
            /// Populates the given graph based on the given compilation. Only the compilation's entry points and
            /// those callables that the entry points depend on will be included in the graph. All Generated
            /// Implementations for specializations should be resolved before calling this, except Self-Inverse,
            /// which is handled by creating a dependency to the appropriate specialization of the same callable.
            /// This will throw an error if a Generated Implementation other than a Self-Inverse is encountered.
            /// </summary>
            public static void PopulateConcreteGraph(ConcreteGraphBuilder graph, QsCompilation compilation)
            {
                var walker          = new BuildGraph(graph);
                var entryPointNodes = compilation.EntryPoints.Select(name => new ConcreteCallGraphNode(name, QsSpecializationKind.QsBody, TypeParameterResolutions.Empty));

                foreach (var entryPoint in entryPointNodes)
                {
                    // Make sure all the entry points are added to the graph
                    walker.SharedState.Graph.AddNode(entryPoint);
                    walker.SharedState.RequestStack.Push(entryPoint);
                }

                var globals = compilation.Namespaces.GlobalCallableResolutions();

                while (walker.SharedState.RequestStack.TryPop(out var currentRequest))
                {
                    // If there is a call to an unknown callable, throw exception
                    if (!globals.TryGetValue(currentRequest.CallableName, out QsCallable currentCallable))
                    {
                        throw new ArgumentException($"Couldn't find definition for callable: {currentRequest.CallableName}");
                    }

                    var spec = GetSpecializationFromRequest(currentRequest, currentCallable);

                    // The current request must be added before it is processed to prevent
                    // self-references from duplicating on the stack.
                    walker.SharedState.ResolvedNodeSet.Add(currentRequest);
                    walker.SharedState.CurrentNode            = currentRequest;
                    walker.SharedState.GetSpecializationKinds = (callableName) => GetSpecializationKinds(globals, callableName);
                    walker.Namespaces.OnSpecializationImplementation(spec.Implementation);
                }
            }
Exemplo n.º 4
0
        private void Button_ShortestPath_Click(object sender, RoutedEventArgs e)
        {
            // Generate the graph using Quickgraph first if it is not yet created
            if (graph == null)
            {
                if (fedID < 0)
                {
                    if (!int.TryParse(TextBox_FedModelID.Text, out fedID))
                    {
                        return;
                    }
                }
                graph = new BuildGraph(GraphData.refBimrlCommon);
                //graph.generateUndirectedGraph(fedID, "CIRCULATION_" + fedID.ToString("X4"));
                graph.generateBiDirectionalGraph(fedID, "CIRCULATION");
            }

            List <string> result = graph.getShortestPath(TextBox_StartNode.Text, TextBox_EndNode.Text);

            if (result.Count > 0)
            {
                TextBox_Output.Text = "";
                foreach (string res in result)
                {
                    TextBox_Output.Text += res + "\n";
                }
            }
            else
            {
                TextBox_Output.Text = "No result!";
            }
        }
Exemplo n.º 5
0
    //Post process the grid
    public void ProcessGrid(BuildGraph builder)
    {
        //Make a list of nodes to flag as unwalkable
        //we can't immediately update them or the
        //whole thing would go horribly wrong as it
        //scanned its own output!
        var unwalkable = new List <BuildGraph.GridPosition>();

        //Run through the grid
        for (var x = 0; x < builder.width; x++)
        {
            for (var y = 0; y < builder.height; y++)
            {
                //Get a current position
                var currentPosition = new BuildGraph.GridPosition {
                    x = x, y = y
                };
                //Get all of the neighbours within 2 grid units and see if any
                //of them are not walkable
                if (builder.GetNeighbours(currentPosition, 2).Select(cell => builder.GetCell(cell)).Any(gc => !gc.walkable))
                {
                    //If so add this cell to the unwalkable
                    //list
                    unwalkable.Add(currentPosition);
                }
            }
        }
        //Update the map
        foreach (var unwalk in unwalkable)
        {
            builder.GetCell(unwalk).walkable = false;
        }
    }
Exemplo n.º 6
0
    public void ProcessGrid(BuildGraph builder)
    {
        var cover = builder.cells.Get<Cover>();
        cover.lowCover = new byte[builder.width,builder.height];
        cover.highCover = new byte[builder.width, builder.height];
        foreach (var cell in builder.allWalkableCells)
        {
            //Cast rays for each direction
            for (var i = 0; i < 8; i++)
            {

                var startPosition = builder.GetWorldPosition(cell) + Vector3.up * 0.4f;

                if (Physics.Raycast(startPosition, Cover.CoverVectors[i], 4, builder.culling))
                {
                    cover.lowCover[cell.x, cell.y] = (byte)(cover.lowCover[cell.x, cell.y] | (byte)(1 << i));
                }
                startPosition += Vector3.up;
                if (Physics.Raycast(startPosition, Cover.CoverVectors[i], 4, builder.culling))
                {
                    cover.highCover[cell.x, cell.y] = (byte)(cover.highCover[cell.x, cell.y] | (byte)(1 << i));
                }
            }
        }
    }
Exemplo n.º 7
0
        private void Button_genCirculation_Click(object sender, RoutedEventArgs e)
        {
            if (!int.TryParse(TextBox_FedModelID.Text, out fedID))
            {
                return;
            }

            GraphData graphData = new GraphData();

            //graphData.createCirculationGraph(fedID);
            graphData.createCirculationGraph(fedID);
            if (GraphData.refBimrlCommon.BIMRLErrorStackCount > 0)
            {
                TextBox_Output.Clear();
                string wholeStack = string.Empty;
                while (true)
                {
                    wholeStack += GraphData.refBimrlCommon.StackPopError() + "\n";
                    if (GraphData.refBimrlCommon.BIMRLErrorStackCount == 0)
                    {
                        break;
                    }
                }
                TextBox_Output.Text = wholeStack;
            }

            if (graph != null)
            {
                graph = null;
            }
        }
            /// <summary>
            /// Populates the given graph based on the given compilation. Only the compilation's entry points and
            /// those callables that the entry points depend on will be included in the graph.
            /// </summary>
            public static void PopulateTrimmedGraph(GraphBuilder graph, QsCompilation compilation)
            {
                var walker          = new BuildGraph(graph);
                var entryPointNodes = compilation.EntryPoints.Select(name => new CallGraphNode(name));

                walker.SharedState.WithTrimming = true;
                foreach (var entryPoint in entryPointNodes)
                {
                    // Make sure all the entry points are added to the graph
                    walker.SharedState.Graph.AddNode(entryPoint);
                    walker.SharedState.RequestStack.Push(entryPoint);
                }

                var globals = compilation.Namespaces.GlobalCallableResolutions();

                while (walker.SharedState.RequestStack.TryPop(out var currentRequest))
                {
                    // If there is a call to an unknown callable, throw exception
                    if (!globals.TryGetValue(currentRequest.CallableName, out QsCallable currentCallable))
                    {
                        throw new ArgumentException($"Couldn't find definition for callable: {currentRequest.CallableName}");
                    }

                    // The current request must be added before it is processed to prevent
                    // self-references from duplicating on the stack.
                    walker.SharedState.ResolvedNodeSet.Add(currentRequest);
                    walker.SharedState.CurrentNode = currentRequest;
                    walker.Namespaces.OnCallableDeclaration(currentCallable);
                }
            }
Exemplo n.º 9
0
    public void ProcessGrid(BuildGraph builder)
    {
        var cover = builder.cells.Get <Cover>();

        cover.lowCover  = new byte[builder.width, builder.height];
        cover.highCover = new byte[builder.width, builder.height];
        foreach (var cell in builder.allWalkableCells)
        {
            //Cast rays for each direction
            for (var i = 0; i < 8; i++)
            {
                var startPosition = builder.GetWorldPosition(cell) + Vector3.up * 0.4f;

                if (Physics.Raycast(startPosition, Cover.CoverVectors[i], 4, builder.culling))
                {
                    cover.lowCover[cell.x, cell.y] = (byte)(cover.lowCover[cell.x, cell.y] | (byte)(1 << i));
                }
                startPosition += Vector3.up;
                if (Physics.Raycast(startPosition, Cover.CoverVectors[i], 4, builder.culling))
                {
                    cover.highCover[cell.x, cell.y] = (byte)(cover.highCover[cell.x, cell.y] | (byte)(1 << i));
                }
            }
        }
    }
Exemplo n.º 10
0
 //Post process the grid
 public void ProcessGrid(BuildGraph builder)
 {
     //Make a list of nodes to flag as unwalkable
     //we can't immediately update them or the
     //whole thing would go horribly wrong as it
     //scanned its own output!
     var unwalkable = new List<BuildGraph.GridPosition>();
     //Run through the grid
     for(var x = 0; x < builder.width; x ++)
     {
         for(var y = 0; y < builder.height; y++)
         {
             //Get a current position
             var currentPosition = new BuildGraph.GridPosition { x = x, y = y };
             //Get all of the neighbours within 2 grid units and see if any
             //of them are not walkable
             if(builder.GetNeighbours(currentPosition, 2).Select(cell=>builder.GetCell(cell)).Any(gc=>!gc.walkable))
             {
                 //If so add this cell to the unwalkable
                 //list
                 unwalkable.Add(currentPosition);
             }
         }
     }
     //Update the map
     foreach(var unwalk in unwalkable)
     {
         builder.GetCell(unwalk).walkable = false;
     }
 }
Exemplo n.º 11
0
        public void Should_add_a_vertex()
        {
            BuildGraph.graph = new UndirectedGraph();
            Console.SetIn(new StringReader("DummyName"));
            BuildGraph.Build(2);

            BuildGraph.graph.MyGraph[0].VertexID.Should().Be("DummyName");
        }
            /// <summary>
            /// Populates the given graph based on the given callables.
            /// </summary>
            public static void PopulateGraph(GraphBuilder graph, IEnumerable <QsCallable> callables)
            {
                var walker = new BuildGraph(graph);

                foreach (var callable in callables)
                {
                    walker.Namespaces.OnCallableDeclaration(callable);
                }
            }
Exemplo n.º 13
0
 public void Visualize(BuildGraph builder, BuildGraph.GridPosition position)
 {
     if(grid == null)
         grid = builder.cells.Get<PinchPointGrid>();
     if (grid.pinchPoints.Contains(position))
     {
         Gizmos.color = Color.blue;
         Gizmos.DrawCube(builder.GetWorldPosition(position) + Vector3.up*2.5f, Vector3.one*Mathf.Lerp(0.5f, 1f, grid.cells[position.x, position.y]/grid.cells[grid.pinchPoints[0].x, grid.pinchPoints[0].y]));
     }
 }
Exemplo n.º 14
0
 public void Visualize(BuildGraph builder, BuildGraph.GridPosition position)
 {
     if (grid == null)
     {
         grid = builder.cells.Get <PinchPointGrid>();
     }
     if (grid.pinchPoints.Contains(position))
     {
         Gizmos.color = Color.blue;
         Gizmos.DrawCube(builder.GetWorldPosition(position) + Vector3.up * 2.5f, Vector3.one * Mathf.Lerp(0.5f, 1f, grid.cells[position.x, position.y] / grid.cells[grid.pinchPoints[0].x, grid.pinchPoints[0].y]));
     }
 }
        public override async Task <IActionResult> GetBuildGraph(int id)
        {
            Data.Models.Build build = await _context.Builds.Include(b => b.Incoherencies).FirstOrDefaultAsync(b => b.Id == id);

            if (build == null)
            {
                return(NotFound());
            }

            var builds = await _context.GetBuildGraphAsync(build.Id);

            return(Ok(BuildGraph.Create(builds.Select(b => new Build(b)))));
        }
Exemplo n.º 16
0
 public void ProcessGrid(BuildGraph builder)
 {
     var grid = builder.cells.Get<PinchPointGrid>();
     var points = new List<PinchInfo>();
     grid.cells = new int[builder.width, builder.height];
     foreach(var cell in builder.allWalkableCells)
     {
         grid.cells[cell.x, cell.y] = builder.GetNeighbours(cell, 10).Count(c=>!builder.GetCell(c).walkable);
         points.Add(new PinchInfo {
                                      pinch = grid.cells[cell.x, cell.y],
                                      position = cell
                                  });
     }
     grid.pinchPoints = points.OrderByDescending(p => p.pinch).GroupBy(p=>Mathf.FloorToInt(p.position.x/20) + Mathf.FloorToInt(p.position.y/20)*2000).Select(grp=>grp.First()).Select(p => p.position).Take(20).ToList();
 }
Exemplo n.º 17
0
    public void ProcessGrid(BuildGraph builder)
    {
        var grid   = builder.cells.Get <PinchPointGrid>();
        var points = new List <PinchInfo>();

        grid.cells = new int[builder.width, builder.height];
        foreach (var cell in builder.allWalkableCells)
        {
            grid.cells[cell.x, cell.y] = builder.GetNeighbours(cell, 10).Count(c => !builder.GetCell(c).walkable);
            points.Add(new PinchInfo {
                pinch    = grid.cells[cell.x, cell.y],
                position = cell
            });
        }
        grid.pinchPoints = points.OrderByDescending(p => p.pinch).GroupBy(p => Mathf.FloorToInt(p.position.x / 20) + Mathf.FloorToInt(p.position.y / 20) * 2000).Select(grp => grp.First()).Select(p => p.position).Take(20).ToList();
    }
Exemplo n.º 18
0
        public void Should_add_an_adjacency()
        {
            BuildGraph.graph = GraphBuilder.ValidUndirected();
            var vertexIndex    = new Random();
            var randomDistance = new Random();

            var index1   = vertexIndex.Next(1, 14);
            var index2   = vertexIndex.Next(1, 14);
            var distance = vertexIndex.Next(1, 100);

            //2 random vertexes to add and a random distance
            BuildGraph.AddAdjacency(BuildGraph.graph.MyGraph[index1], BuildGraph.graph.MyGraph[index2], distance);
            var result = BuildGraph.graph;

            result.MyGraph[index1].AdjacentVertices[result.MyGraph[index1].AdjacentVertices.Count - 1].AdjacentVertex
            .VertexID.Should()
            .Be(result.MyGraph[index2].VertexID);

            result.MyGraph[index1].AdjacentVertices[result.MyGraph[index1].AdjacentVertices.Count - 1].Distance.Should()
            .Be(distance);
        }
Exemplo n.º 19
0
        public FileCopy(
            BuildGraph buildGraph, 
            string source, 
            string destination,
            string buildFileDir)
            : base(buildGraph)
        {
            if (String.IsNullOrEmpty(source)) {
                throw new InvalidOperationException("Invalid source argument.");
            }
            if (String.IsNullOrEmpty(destination)) {
                throw new InvalidOperationException("Invalid destination argument.");
            }
            if (String.IsNullOrEmpty(destination)) {
                throw new InvalidOperationException("Invalid destination argument.");
            }

            m_source = QRPath.GetCanonical(source);
            m_destination = QRPath.GetCanonical(destination); ;
            m_buildFileDir = QRPath.GetCanonical(buildFileDir);
        }
Exemplo n.º 20
0
        private void Button_kShortestPath_Click(object sender, RoutedEventArgs e)
        {
            // Generate the graph using Quickgraph first if it is not yet created
            if (graph == null)
            {
                if (fedID < 0)
                {
                    if (!int.TryParse(TextBox_FedModelID.Text, out fedID))
                    {
                        return;
                    }
                }
                graph = new BuildGraph(GraphData.refBimrlCommon);
                graph.generateBiDirectionalGraph(fedID, "CIRCULATION");
            }

            List <List <string> > results = graph.getkShortestPath(TextBox_StartNode.Text, TextBox_EndNode.Text, kPaths);

            if (results != null)
            {
                TextBox_Output.Text = "";
                int k = 1;
                foreach (List <string> result in results)
                {
                    TextBox_Output.Text += "** Path # " + k++.ToString() + " :\n";
                    foreach (string res in result)
                    {
                        TextBox_Output.Text += res + "\n";
                    }
                    TextBox_Output.Text += "\n";
                }
            }
            else
            {
                TextBox_Output.Text = "No result!";
            }
        }
Exemplo n.º 21
0
        public void Should_return_undirected_graph()
        {
            var Graph = BuildGraph.SetGraphType(1);

            Graph.Should().BeOfType <UndirectedGraph>();
        }
Exemplo n.º 22
0
        public int GetCoverScore(BuildGraph.GridPosition position)
        {
            var result = CountBits(lowCover[position.x, position.y]) +
                CountBits(highCover[position.x, position.y]) * 2;

            return 24 - result;
        }
Exemplo n.º 23
0
 public int GetCoverScore(BuildGraph.GridPosition position, Vector3 fromDirection)
 {
     var result = 0;
     var dir = Cover.GetDirection(fromDirection);
     if (((CoverDirection)lowCover[position.x, position.y] & dir) != 0)
         result++;
     if (((CoverDirection)highCover[position.x, position.y] & dir) != 0)
         result+=2;
     return 3 - result;
 }
Exemplo n.º 24
0
        /// Parse the output for includes and error messages.
        /// Returns true if no errors, false if any irrecoverable error.
        /// TODO: This algorithm is imperfect, because the "NOTE: including file:" messages do not distinguish
        /// between quoted-form versus angle-bracket-form includes.  Since the rules on header search are
        /// different between the two, there is always a chance that we will guess a wrong generated file is
        /// a dependency of this translation.
        public static bool ParseShowIncludesText(
            BuildGraph buildGraph,
            string compilerOutput,
            string compileDir,
            IList<string> includeDirs,
            HashSet<string> includes)
        {
            bool foundError = false;

            // includesList is ordered, since the search algorithm requires it
            IList<string> includesList = new List<string>();

            using (StringReader sr = new StringReader(compilerOutput)) {
                for (string line = sr.ReadLine(); line != null; line = sr.ReadLine()) {
                    if (line.StartsWith(ExistingIncludePrefix)) {
                        int pathStart;
                        for (pathStart = ExistingIncludePrefix.Length; pathStart < line.Length; pathStart++) {
                            if (line[pathStart] != ' ') {
                                break;
                            }
                        }
                        string path = line.Substring(pathStart);
                        string absPath = QRPath.GetCanonical(path);
                        includesList.Add(absPath);
                    }
                    else if (line.Contains(MissingIncludeError)) {
                        // C1083 is the "missing include file" error
                        // Extract the missing file-name and add it to inputs.
                        int prefixIndex = line.IndexOf(MissingIncludePrefix);
                        if (prefixIndex > 0) {
                            int fileNameStartIndex = prefixIndex + MissingIncludePrefix.Length;
                            int cursor = fileNameStartIndex;
                            for (; cursor < line.Length; cursor++) {
                                if (line[cursor] == '\'') {
                                    break;
                                }
                            }
                            string path = line.Substring(fileNameStartIndex, cursor - fileNameStartIndex);
                            string absPath = SearchIncludePathsForGeneratedFile(
                                buildGraph, compileDir, includeDirs, path);
                            if (absPath != null) {
                                includesList.Add(absPath);
                            }
                            else {
                                // Trace an error that the missing include can never exist in this build.
                                Trace.TraceError("Missing header '{0}' not generated by any Translation.", path);
                                foundError = true;
                            }
                        }
                    }
                    else if (line.Contains("error")) {
                        foundError = true;
                    }
                }
            }

            foreach (string include in includesList) {
                includes.Add(include);
            }
            return !foundError;
        }
Exemplo n.º 25
0
        private string CompileOrClean(string filePath)
        {
            BuildGraph buildGraph = new BuildGraph();
            var cscp = new CSharpCompileParams();
            cscp.BuildFileDir = Path.Combine(m_currentDir, m_outputDir);
            cscp.Sources.Add(filePath);
            cscp.OutputFilePath =
                Path.Combine(cscp.BuildFileDir, Path.GetFileName(filePath)) + ".dll";
            cscp.TargetFormat = CSharpTargetFormats.Library;
            cscp.FrameworkVersion = CSharpFrameworkVersion.V3_5;
            cscp.CompileDir = m_currentDir;
            cscp.Debug = true;
            cscp.Platform = CSharpPlatforms.AnyCpu;
            foreach (Assembly assembly in UsingAssemblies) {
                if (assembly != null) {
                    cscp.AssemblyReferences.Add(assembly.Location);
                }
            }
            var csc = new CSharpCompile(buildGraph, cscp);

            BuildOptions options = new BuildOptions();
            options.FileDecider = new FileSizeDateDecider();
            options.RemoveEmptyDirectories = true;

            var targets = new [] { cscp.OutputFilePath };
            BuildAction buildAction = m_wipe ? BuildAction.Clean : BuildAction.Build;
            BuildResults results = buildGraph.Execute(
                buildAction,
                options,
                targets,
                true);

            if (!results.Success) {
                throw new InvalidOperationException();
            }

            return cscp.OutputFilePath;
        }
 void Awake()
 {
     instance = this;
     renderer.enabled = false;
 }
Exemplo n.º 27
0
 public MsvcPreProcess(BuildGraph buildGraph, MsvcPreProcessParams p)
     : base(buildGraph)
 {
     m_params = p.Canonicalize();
 }
Exemplo n.º 28
0
        /// Returns path to the specified include file. 
        /// TODO: still needs work.  The full algorithm to emulate is here:
        /// http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
        private static string SearchIncludePathsForGeneratedFile(
            BuildGraph buildGraph,
            string compileDir,
            IList<string> includeDirs,
            string path)
        {
            if (Path.IsPathRooted(path)) {
                return path;
            }

            foreach (string includeDir in includeDirs) {
                string absPath = QRPath.GetAbsolutePath(path, includeDir);
                BuildFile buildFile = buildGraph.GetBuildFile(absPath);
                if (buildFile != null && buildFile.BuildNode != null) {
                    return absPath;
                }
            }

            // Try the compileDir as a fallback.
            {
                string absPath = QRPath.GetAbsolutePath(path, compileDir);
                BuildFile buildFile = buildGraph.GetBuildFile(absPath);
                if (buildFile != null && buildFile.BuildNode != null) {
                    return absPath;
                }
            }

            // No path
            return null;
        }
Exemplo n.º 29
0
 public MsvcCompile(BuildGraph buildGraph, MsvcCompileParams p)
     : base(buildGraph)
 {
     m_params = p.Canonicalize();
 }
Exemplo n.º 30
0
 public CSharpCompile(BuildGraph buildGraph, CSharpCompileParams p)
     : base(buildGraph)
 {
     m_params = p.Canonicalize();
 }
Exemplo n.º 31
0
 public MsvcLib(BuildGraph buildGraph, MsvcLibParams p)
     : base(buildGraph)
 {
     m_params = p.Canonicalize();
 }
            /// <summary>
            /// Populates the given graph based on the given compilation. This will produce a call graph that
            /// contains all relationships amongst all callables in the compilation.
            /// </summary>
            public static void PopulateGraph(GraphBuilder graph, QsCompilation compilation)
            {
                var walker = new BuildGraph(graph);

                walker.OnCompilation(compilation);
            }
Exemplo n.º 33
0
        public void invalid_graph_type_should_return_null()
        {
            var graph = BuildGraph.SetGraphType(3);

            graph.Should().BeNull();
        }
Exemplo n.º 34
0
 void Awake()
 {
     instance         = this;
     renderer.enabled = false;
 }
Exemplo n.º 35
0
        public IResponse Execute(ICruiseRequest cruiseRequest)
        {
            cruiseRequest.Request.RefreshInterval = RefreshInterval;

            Hashtable         velocityContext  = new Hashtable();
            IProjectSpecifier projectSpecifier = cruiseRequest.ProjectSpecifier;
            IServerSpecifier  serverSpecifier  = FindServer(projectSpecifier);
            var sessionToken = cruiseRequest.RetrieveSessionToken();

            IBuildSpecifier[] buildSpecifiers = farmService.GetMostRecentBuildSpecifiers(projectSpecifier, 1, sessionToken);
            if (buildSpecifiers.Length == 1)
            {
                velocityContext["mostRecentBuildUrl"] = linkFactory.CreateProjectLink(projectSpecifier, LatestBuildReportProjectPlugin.ACTION_NAME).Url;
            }

            velocityContext["projectName"]     = projectSpecifier.ProjectName;
            velocityContext["server"]          = serverSpecifier;
            velocityContext["externalLinks"]   = farmService.GetExternalLinks(projectSpecifier, sessionToken);
            velocityContext["noLogsAvailable"] = (buildSpecifiers.Length == 0);

            velocityContext["StatusMessage"] = ForceBuildIfNecessary(projectSpecifier, cruiseRequest.Request, sessionToken);
            ProjectStatus status = FindProjectStatus(projectSpecifier, cruiseRequest);

            velocityContext["status"] = status;
            velocityContext["StartStopButtonName"]        = (status.Status == ProjectIntegratorState.Running) ? "StopBuild" : "StartBuild";
            velocityContext["StartStopButtonValue"]       = (status.Status == ProjectIntegratorState.Running) ? "Stop" : "Start";
            velocityContext["ForceAbortBuildButtonName"]  = (status.Activity.IsSleeping() ? "ForceBuild" : "AbortBuild");
            velocityContext["ForceAbortBuildButtonValue"] = (status.Activity.IsSleeping() ? "Force" : "Abort");
            velocityContext["ParametersUrl"]       = urlBuilder.BuildProjectUrl(ProjectParametersAction.ActionName, projectSpecifier);
            velocityContext["AllowForceBuild"]     = (serverSpecifier.AllowForceBuild && status.ShowForceBuildButton);
            velocityContext["AllowStartStopBuild"] = (serverSpecifier.AllowStartStopBuild && status.ShowStartStopButton);


            if (cruiseRequest.Request.ApplicationPath == "/")
            {
                velocityContext["applicationPath"] = string.Empty;
            }
            else
            {
                velocityContext["applicationPath"] = cruiseRequest.Request.ApplicationPath;
            }

            velocityContext["rssDataPresent"] = farmService.GetRSSFeed(projectSpecifier, sessionToken).Length > 0;

            // I (willemsruben) can not figure out why the line below does not work :-(
            // velocityContext["rss"] = linkFactory.CreateProjectLink(projectSpecifier, WebDashboard.Plugins.RSS.RSSFeed.ACTION_NAME).Url;
            //
            velocityContext["rss"] = RSSLinkBuilder.CreateRSSLink(linkFactory, projectSpecifier);

            velocityContext["ohloh"] = farmService.GetLinkedSiteId(projectSpecifier, sessionToken, "ohloh") ?? string.Empty;

            string subReportData = GetPluginSubReport(cruiseRequest, projectSpecifier, buildSpecifiers);

            if (subReportData != null && subReportData != String.Empty)
            {
                velocityContext["pluginInfo"] = subReportData;
            }



            BuildGraph GraphMaker;
            // if the amount of builds exceed this, foresee extra column(s) for the days
            //   adjusting the Y-axis of the graph
            Int32 MaxBuildTreshhold = 15;
            // Limits the X-axis to this amount of days
            Int32 MaxAmountOfDaysToDisplay = 15;
            // the amount of columns to foresee for 1 day in the graph
            Int32 DateMultiPlier;

            GraphMaker = new BuildGraph(
                farmService.GetMostRecentBuildSpecifiers(projectSpecifier, AmountOfBuildsToRetrieve, sessionToken),
                this.linkFactory,
                Translations.RetrieveCurrent());

            velocityContext["graphDayInfo"]        = GraphMaker.GetBuildHistory(MaxAmountOfDaysToDisplay);
            velocityContext["highestAmountPerDay"] = GraphMaker.HighestAmountPerDay;

            DateMultiPlier = (GraphMaker.HighestAmountPerDay / MaxBuildTreshhold) + 1;
            velocityContext["dateMultiPlier"] = DateMultiPlier;


            Int32 okpercent = 100;

            if (GraphMaker.AmountOfOKBuilds + GraphMaker.AmountOfFailedBuilds > 0)
            {
                okpercent = 100 * GraphMaker.AmountOfOKBuilds / (GraphMaker.AmountOfOKBuilds + GraphMaker.AmountOfFailedBuilds);
            }
            velocityContext["OKPercent"]  = okpercent;
            velocityContext["NOKPercent"] = 100 - okpercent;

            return(viewGenerator.GenerateView(@"ProjectReport.vm", velocityContext));
        }