示例#1
0
        public void AddGraph(GraphDto graphDto)
        {
            var graph = graphDtoToGraphMapping.Map(graphDto);

            winContext.Graphs.Add(graph);
            winContext.SaveChanges();
        }
示例#2
0
        public async Task <GraphDto> Graph()
        {
            try
            {
                // var act = _context.Set.FromSql("[dbo].[usp_GetAllActivity] @paramStationId ={2023}");

                //var abc = _efHepler.ExecuteProcedure(
                //"[dbo].[usp_GetAllActivity]",
                //new[]
                //{
                //        new SqlParameter("@paramStationId",2023)
                //});
                //Model = (from IDictionary<string, object> model in await abc
                //         select new GraphDto
                //         {
                //             Activity = model.GetSafe<int>("Activity"),

                //         }).ToList();
                var g = new GraphDto();
                return(await Task.FromResult(g));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
示例#3
0
        public ActionResult FindRoles(GraphViewModel graphViewModel)
        {
            try
            {
                if (graphViewModel.Graph.Edges.Count != 0 && graphViewModel.Graph.GraphSet.Count == 0)
                {
                    foreach (Edge <UserDto> edge in graphViewModel.Graph.Edges)
                    {
                        graphViewModel.Graph.CreateGraphSet(edge);
                    }
                }

                FetchItemServiceResponse <Graph <UserDto> > response = _graphService.DetectRolesInGraph(graphViewModel.Graph);

                if (response.Succeeded)
                {
                    graphViewModel.Graph = response.Item;
                    FetchItemServiceResponse <SSRMRolesDto> ssrmRolesCounts = _graphService.FetchSSRMRolesCounts(graphViewModel.Graph);
                    graphViewModel.SsrmRolesDto = ssrmRolesCounts.Item;

                    List <NodeDto> nodes = graphViewModel.Graph.Nodes.Select(x => new NodeDto()
                    {
                        id    = x.Id,
                        label = x.NodeElement.Name,
                        group = (graphViewModel.GraphDto.nodes.First(y => y.id == x.Id).group),
                        title = $"Node degree: {x.Degree}",
                        size  = GetNodeSizeBasedOnRole(x),
                        shape = (graphViewModel.GraphDto.nodes.First(y => y.id == x.Id).shape)
                    }).ToList();
                    List <EdgeDto> edges = graphViewModel.Graph.Edges.Select(x => new EdgeDto()
                    {
                        from = x.Node1.Id, to = x.Node2.Id
                    }).ToList();

                    if (nodes.FirstOrDefault(x => x.id == graphViewModel.SelectedEgoId) != null)
                    {
                        nodes.First(x => x.id == graphViewModel.SelectedEgoId).size = 25;
                    }

                    foreach (Node <UserDto> node in graphViewModel.Graph.Nodes.Where(x => x.Role != 0))
                    {
                        nodes.First(x => x.id == node.Id).shape = GetNodeShapeBasedOnRole(node);
                    }
                    graphViewModel.Graph.SetCommunityNodes();
                    GraphDto graphDto = new GraphDto
                    {
                        nodes = nodes,
                        edges = edges
                    };
                    graphViewModel.RolesDetected = true;
                    graphViewModel.GraphDto      = graphDto;
                }
            }
            catch (Exception e)
            {
                return(new HttpStatusCodeResult(500, e.Message));
            }
            return(View("GraphView_partial", graphViewModel));
        }
示例#4
0
        public static async Task <ClientHelper> AsyncNew(WorkerHostInfo worker,
                                                         GraphDto graph)
        {
            var task = new Task <ClientHelper>(() => new ClientHelper(worker, graph));

            task.Start();
            return(await task);
        }
示例#5
0
        //Get GraphDto and export it.
        public void Export(IGraph graph, string path)
        {
            this.graph = graph;

            GraphDto graphDto = GetDto();

            Export(graphDto, path);
        }
示例#6
0
        public ActionResult FindCommunities(GraphViewModel graphViewModel)
        {
            try
            {
                if (graphViewModel.Graph.Edges.Count != 0)
                {
                    foreach (Edge <UserDto> edge in graphViewModel.Graph.Edges)
                    {
                        graphViewModel.Graph.CreateGraphSet(edge);
                    }
                }

                if (graphViewModel.Graph.Communities.Count > 0)
                {
                    graphViewModel.Graph.Communities = new HashSet <Community <UserDto> >();
                }

                Dictionary <int, int>         partition   = LouvainCommunity.BestPartition(graphViewModel.Graph);
                Dictionary <int, List <int> > communities = new Dictionary <int, List <int> >();
                foreach (KeyValuePair <int, int> kvp in partition)
                {
                    List <int> nodeset;
                    if (!communities.TryGetValue(kvp.Value, out nodeset))
                    {
                        nodeset = communities[kvp.Value] = new List <int>();
                    }
                    nodeset.Add(kvp.Key);
                }
                graphViewModel.Graph.SetCommunities(communities);

                graphViewModel.Graph.SetDegrees();
                List <NodeDto> nodes = graphViewModel.Graph.Nodes.Select(x => new NodeDto()
                {
                    id    = x.Id,
                    label = x.NodeElement.Name,
                    group = x.CommunityId,
                    title = $"Node degree: {x.Degree}",
                    size  = (graphViewModel.GraphDto.nodes.First(y => y.id == x.Id).size)
                }).ToList();
                List <EdgeDto> edges = graphViewModel.Graph.Edges.Select(x => new EdgeDto()
                {
                    from = x.Node1.Id, to = x.Node2.Id
                }).ToList();

                GraphDto graphDto = new GraphDto
                {
                    nodes = nodes,
                    edges = edges
                };

                graphViewModel.GraphDto = graphDto;
            }
            catch (Exception e)
            {
                return(new HttpStatusCodeResult(500, e.Message));
            }
            return(View("GraphView_partial", graphViewModel));
        }
示例#7
0
        public async Task <(string, string)> GetGraphFromCache(string graphName)
        {
            string cacheKeyLink = "GRAPH_" + graphName;
            string GRAPH        = await _distributedCache.GetStringAsync(cacheKeyLink);

            GraphDto graph = JsonConvert.DeserializeObject <GraphDto>(GRAPH);

            return(JsonConvert.SerializeObject(graph.Links), JsonConvert.SerializeObject(graph.Nodes));
        }
示例#8
0
        public Graph(GraphDto graph, ISelectionService <BlackboardElement> selectionService, ICommandProvider commandProvider, IActionsDatabase actionsDatabase,
                     IOutputManager outputManager) : base(selectionService)
        {
            Id       = Guid.NewGuid();
            NodeList = new ActionList(this, commandProvider, actionsDatabase);

            _cmdProvider = commandProvider;
            _output      = outputManager;
        }
示例#9
0
        //Using a XmlSerializer export the GraphDto object to a xml file at a specified path.
        public void Export(GraphDto graphDto, string path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(GraphDto), new XmlRootAttribute("Graph"));

            StreamWriter streamWriter = new StreamWriter(path);

            serializer.Serialize(streamWriter, graphDto);

            streamWriter.Dispose();
        }
示例#10
0
        public void Save(string name, GraphDto data)
        {
            if (!Directory.Exists(m_RootPath)) Directory.CreateDirectory(m_RootPath);

            string path = GetUniqueFilePath(name);
            using (var writer = File.CreateText(path))
            {
                JsonSerializer.Create().Serialize(writer, data);
            }
        }
示例#11
0
        //Import the GraphDto from a xml file then get the new graph then set the current max layer
        public IGraph Import(string path, out int currentMaxLayer)
        {
            GraphDto graphDto = ImportGraphDtoFromXml(path);

            GetGraphFromDto(graphDto, out IGraph graph);

            //Set the maxLayer to the highest number.
            currentMaxLayer = graph.Nodes.OrderByDescending(n => n.Layer).ToArray()[0].Layer;

            return(graph);
        }
示例#12
0
        public ActionResult GetSelectedValue(GraphViewModel model, string teamMemberId)
        {
            try
            {
                int    id = int.Parse(teamMemberId);
                string connectionString = GetConnectionStringBasedOnSelectedMember(teamMemberId);

                if (model.FromDate != null || model.ToDate != null)
                {
                    List <DateTime> startAndEndDateOfConversations = GetStartAndEndDateOfConversations(teamMemberId);
                    model.FromDate = startAndEndDateOfConversations.First().ToString("MM/dd/yyyy");
                    model.ToDate   = startAndEndDateOfConversations.Last().ToString("MM/dd/yyyy");
                }

                DateTime from = DateTime.ParseExact(model.FromDate, "MM/dd/yyyy", null);
                DateTime to   = DateTime.ParseExact(model.ToDate, "MM/dd/yyyy", null);

                FetchItemServiceResponse <Graph <UserDto> > responseGraph = _graphService.FetchEmailsGraph(connectionString, from, to);

                responseGraph.Item.SetDegrees();

                List <NodeDto> nodes = responseGraph.Item.Nodes.Select(x => new NodeDto()
                {
                    id    = x.Id,
                    label = x.NodeElement.Name,
                    title = $"Node degree: {x.Degree}",
                    size  = 10,
                    color = "#f5cbee"
                }).ToList();
                List <EdgeDto> edges = responseGraph.Item.Edges.Select(x => new EdgeDto()
                {
                    from = x.Node1.Id, to = x.Node2.Id
                }).ToList();

                GraphDto graphDto = new GraphDto
                {
                    nodes = nodes,
                    edges = edges
                };


                model.TeamMembers          = TeamMembers;
                model.SelectedTeamMemberId = id;
                model.Graph    = responseGraph.Item;
                model.GraphDto = graphDto;
            }
            catch (Exception e)
            {
                return(new HttpStatusCodeResult(500, e.Message));
            }

            return(View("GraphView_partial", model));
        }
示例#13
0
        public GraphDto GenerateGraph()
        {
            var maxNumberOfEdges = _numberOfNodes / Density;
            var tmp             = GetEmptyGraph(_numberOfNodes);
            var consistentGraph = GetConsistentGraph(tmp);
            var graphDto        = new GraphDto
            {
                AdjMatrix = ConvertToMatrix(FillRestOfEdges(consistentGraph, maxNumberOfEdges))
            };

            return(graphDto);
        }
示例#14
0
        public Guid StartTask(GraphDto graph)
        {
            var helper = new GraphHelper(graph);

            if (_graphHelpers.ContainsKey(helper.Id))
            {
                throw new SessionAlreadyExistsException();
            }
            _graphHelpers.TryAdd(helper.Id, helper);
            _logger.LogDebug("TASK REGISTERED");
            return(helper.Id);
        }
示例#15
0
        public async Task <GraphDto> GetGraphBySensorId(int SensorId, int days)
        {
            DateTime date = DateTime.Now.AddDays(-days);

            IEnumerable <History> histories = await unitOfWork.HistoryRepo.GetHistoriesBySensorIdAndDate(SensorId, date);

            if (!histories.Any())
            {
                return new GraphDto {
                           IsCorrect = false
                }
            }
            ;

            Sensor   sensor = histories.FirstOrDefault().Sensor;
            GraphDto graph  = mapper.Map <Sensor, GraphDto>(sensor);

            graph.Dates  = new List <DateTimeOffset>();
            graph.Values = new List <dynamic>();

            foreach (History history in histories)
            {
                switch (graph.MeasurementType)
                {
                case MeasurementType.Int when history.IntValue.HasValue:
                    graph.Dates.Add(history.Date);
                    graph.Values.Add(history.IntValue.Value);
                    break;

                case MeasurementType.Double when history.DoubleValue.HasValue:
                    graph.Dates.Add(history.Date);
                    graph.Values.Add(history.DoubleValue.Value);
                    break;

                case MeasurementType.Bool when history.BoolValue.HasValue:
                    graph.Dates.Add(history.Date);
                    graph.Values.Add(history.BoolValue.Value ? 1 : 0);
                    break;

                case MeasurementType.String when !String.IsNullOrEmpty(history.StringValue):
                    graph.Dates.Add(history.Date);
                    graph.Values.Add(history.StringValue);
                    break;
                }
            }
            if (!graph.Dates.Any())
            {
                graph.IsCorrect = false;
            }
            return(graph);
        }
示例#16
0
        //Using a XmlSerializer import the data from a specified xml file into a GraphDto object
        private static GraphDto ImportGraphDtoFromXml(string path)
        {
            XmlRootAttribute rootAttribute = new XmlRootAttribute("Graph");

            XmlSerializer serializer = new XmlSerializer(typeof(GraphDto), rootAttribute);

            StreamReader streamReader = new StreamReader(path);

            GraphDto graphDto = (GraphDto)serializer.Deserialize(streamReader);

            streamReader.Dispose();

            return(graphDto);
        }
示例#17
0
        public IActionResult BeginTask(GraphDto graph)
        {
            if (HttpContext.Request.Cookies.ContainsKey(CookieKey))
            {
                throw new SessionAlreadyExistsException();
            }
            var guid = _taskService.StartTask(graph);

            HttpContext.Response.Cookies.Append(CookieKey, guid.ToString(), new CookieOptions()
            {
                HttpOnly = true, SameSite = SameSiteMode.Strict
            });
            return(NoContent());
        }
示例#18
0
        public void Save(string name, GraphDto data)
        {
            if (!Directory.Exists(m_RootPath))
            {
                Directory.CreateDirectory(m_RootPath);
            }

            string path = GetUniqueFilePath(name);

            using (var writer = File.CreateText(path))
            {
                JsonSerializer.Create().Serialize(writer, data);
            }
        }
示例#19
0
        public ActionResult <IEnumerable <EdgeDto> > PostGraph(GraphDto graphDto)
        {
            var graph     = Mapper.ToGraphModel(graphDto);
            var terminals = graph.Nodes.FindAll(node => node.IsTerminal);

            if (terminals.Count < 2)
            {
                return(BadRequest("You must specify at least 2 terminals"));
            }

            var nodeSolution = FindPath(terminals[0], terminals[0], graph.Nodes.Count);
            var solution     = Mapper.ToEdgeDtos(nodeSolution);

            return(Ok(solution));
        }
        //Returns Count of employeed in each industry
        public GraphDto GetData()
        {
            appContext.Database.Log = s => { System.Diagnostics.Debug.WriteLine(s); };
            GraphDto graphdata = new GraphDto();

            graphdata.Agriculture          = appContext.Population.Count(p => string.Equals(p.OccupationIndustry, "Agriculture"));
            graphdata.Software             = appContext.Population.Count(p => string.Equals(p.OccupationIndustry, "Software"));
            graphdata.Management           = appContext.Population.Count(p => string.Equals(p.OccupationIndustry, "Management"));
            graphdata.Entertainment        = appContext.Population.Count(p => string.Equals(p.OccupationIndustry, "Entertainment"));
            graphdata.Other                = appContext.Population.Count(p => string.Equals(p.OccupationIndustry, "Other"));
            graphdata.HAndT                = appContext.Population.Count(p => string.Equals(p.OccupationIndustry, "Hospitality and Tourism"));
            graphdata.EducationAndTraining = appContext.Population.Count(p => string.Equals(p.OccupationIndustry, "Education and Training"));
            graphdata.Manufacturing        = appContext.Population.Count(p => string.Equals(p.OccupationIndustry, "Manufacturing"));
            return(graphdata);
        }
示例#21
0
        public static GraphDto ToGraphDto(CanvasModel canvas)
        {
            var graphDto = new GraphDto()
            {
                Nodes = new List <NodeDto>(canvas.Nodes.ConvertAll(ToNodeDto)),
                Edges = new List <EdgeDto>(canvas.Edges.ConvertAll(ToEdgeDto))
            };

            foreach (var terminal in canvas.Terminals)
            {
                graphDto.Nodes.Find(node => node.Id == terminal.Id).IsTerminal = true;
            }

            return(graphDto);
        }
示例#22
0
        public async Task SaveGraphToCache(Graph newGraph)
        {
            var options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromDays(400));
            (List <GraphNodeDTO> nodes, List <GraphLinkDTO> links) = GraphMapperService.MapGraphToDTOs(newGraph);
            GraphDto graphDto = new GraphDto
            {
                Links = links,
                Nodes = nodes
            };
            string GRAPH         = JsonConvert.SerializeObject(graphDto);
            string cacheGraphKey = "GRAPH_" + newGraph.Name;
            await _distributedCache.SetStringAsync(cacheGraphKey, GRAPH, options);
        }
示例#23
0
        public void UpdateGraph(int id, GraphDto graphDto)
        {
            var actualGraph = winContext.Graphs
                              .SingleOrDefault(g => g.Id == id);

            if (actualGraph == null)
            {
                return;
            }

            var graph = graphDtoToGraphMapping.Map(graphDto);

            graphUpdater.Update(actualGraph, graph);

            winContext.SaveChanges();
        }
示例#24
0
        //Get the data for nodes and links from GraphDto and add them to the new graph than set the source and destination if any
        private static void GetGraphFromDto(GraphDto graphDto, out IGraph graph)
        {
            graph = new Graph(graphDto.Nodes.Count + 1);

            foreach (NodeDto nodeDto in graphDto.Nodes)
            {
                graph.AddExistingNode(nodeDto.Layer, nodeDto.NodeNumber, nodeDto.CenterX, nodeDto.CenterY);
            }

            foreach (NodeDto nodeDto in graphDto.Nodes)
            {
                foreach (LinkDto linkDto in nodeDto.ConnectedLinks)
                {
                    INode node1 = graph.Nodes.First(n => n.NodeNumber == linkDto.Node1);
                    INode node2 = graph.Nodes.First(n => n.NodeNumber == linkDto.Node2);

                    bool linkExists = node1.ConnectedLinks.Any(l =>
                                                               (l.ConnectedNodes.Item1 == node1 && l.ConnectedNodes.Item2 == node2) ||
                                                               (l.ConnectedNodes.Item1 == node2 && l.ConnectedNodes.Item2 == node1));

                    if (!linkExists)
                    {
                        graph.AddLink(node1, node2, linkDto.Weight);
                    }
                }
            }

            if (graphDto.Source != 0)
            {
                graph.Source = graph.Nodes.First(n => n.NodeNumber == graphDto.Source);
            }
            else
            {
                graph.Source = null;
            }

            if (graphDto.Destination != 0)
            {
                graph.Destination = graph.Nodes.First(n => n.NodeNumber == graphDto.Destination);
            }
            else
            {
                graph.Destination = null;
            }
        }
示例#25
0
        public static GraphModel ToGraphModel(GraphDto graphDto)
        {
            var graph = new GraphModel
            {
                Nodes = graphDto.Nodes.ConvertAll(ToNodeModel)
            };

            foreach (var edge in graphDto.Edges)
            {
                var edge1 = graph.Nodes.Find(node => node.Id == edge.End1);
                var edge2 = graph.Nodes.Find(node => node.Id == edge.End2);

                edge1.Edges.Add(edge2);
                edge2.Edges.Add(edge1);
            }

            return(graph);
        }
示例#26
0
        public async Task <IActionResult> Graph(int sensorId, int days = 30)
        {
            GraphDto graph = await _historyManager.GetGraphBySensorId(sensorId, days);

            GraphViewModel result = _mapper.Map <GraphDto, GraphViewModel>(graph);

            if (result.IsCorrect)
            {
                result.Days      = days;
                result.longDates = new List <long>();
                foreach (DateTimeOffset date in graph.Dates)
                {
                    DateTimeOffset unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    result.longDates.Add((long)date.Subtract(unixEpoch).TotalMilliseconds);
                }
            }
            return(View(result));
        }
示例#27
0
        public void Save(GraphDto graph)
        {
            if (graph == null)
            {
                throw new ArgumentException(nameof(graph));
            }

            var id = graph.Id;

            if (_savedStates.ContainsKey(id))
            {
                _savedStates[id] = graph;
            }
            else
            {
                _savedStates.Add(id, graph);
            }
        }
        public static GraphViewModel ToViewModel(this GraphDto item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            var vm = GraphViewModelCreator.Create(item.Id);

            vm.Name = item.Name;

            foreach (var point in item.Points)
            {
                vm.Points.Add(point.ToViewModel(vm));
            }

            return(vm);
        }
示例#29
0
        /// <summary> Из ДТО в граф </summary>
        public static IGraph ConvertBack(GraphDto value)
        {
            if (value.AllowMultipleEdges)
            {
                throw new InvalidOperationException("Данный тип графов не поддерживается.");
            }
            var graph = value.Directed
                            ? (
                !value.IsWeighted
                                      ? (IGraph) new DirectedGraph()
                                      : (IGraph) new DirectedWeightedGraph()
                )
                            : (IGraph) new UndirectedGraph();

            value.Vertices.ForEach(v => graph.AddVertex(VertexToDtoConverter.ConvertBack(v)));
            value.Edges.ForEach(e => graph.AddEdge(EdgeToDtoConverter.ConvertBack(e, graph.Vertices)));

            return(graph);
        }
示例#30
0
        private ClientHelper(WorkerHostInfo worker,
                             GraphDto graph)
        {
            _restClient = new RestClient(worker.Uri + "/api")
            {
                CookieContainer  = new CookieContainer(),
                ReadWriteTimeout = 500000,
                Timeout          = 500000
            };
            _workerHost = worker;

            var registerRequest = new RestRequest("/task", Method.POST);
            var graphJson       = JsonSerializer.Serialize(graph);

            registerRequest.AddJsonBody(graphJson);
            var response = _restClient.Execute(registerRequest);

            if (!response.IsSuccessful)
            {
                ThrowExceptionOnNotSuccessfulResponse(response);
            }
        }
示例#31
0
        public async Task <IActionResult> GraphQL([FromBody] GraphDto query)
        {
            var inputs = query.Variables.ToInputs();
            var schema = new Schema()
            {
                Query = new EmployeeQuery(EmployeeRepository)
            };

            var result = await new DocumentExecuter().ExecuteAsync(x =>
            {
                x.Schema        = schema;
                x.Query         = query.Query;
                x.OperationName = query.OperationName;
                x.Inputs        = inputs;
            });

            if (result.Errors?.Count > 0)
            {
                return(BadRequest(new { errors = result.Errors.Select(x => x.Message) }));
            }

            return(Ok(result.Data));
        }
示例#32
0
 public void Save(GraphDto data)
 {
     Save(data.Name, data);
 }