예제 #1
0
        public static bool TryGetGraphException(HttpResponseMessage responseMessage, out GraphException exception)
        {
            if (responseMessage == null)
            {
                exception = null;
                return(false);
            }
            var content = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();

            if (string.IsNullOrEmpty(content))
            {
                exception = null;
                return(false);
            }
            try
            {
                exception = JsonSerializer.Deserialize <GraphException>(content, new JsonSerializerOptions()
                {
                    IgnoreNullValues = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });
                return(true);
            }
            catch
            {
                exception = null;
                return(false);
            }
        }
예제 #2
0
        public static Optional <GraphPath <T> > FindShortestPath <T>(this IGraph <T> graph,
                                                                     T startingVertex, T destinationVertex)
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }
            var metadata = new MetadataProvider().GetMetadata(graph);

            if (metadata.Unweighted && metadata.AllPositiveWeights)
            {
                return(graph.FindShortestPath(startingVertex, destinationVertex, o => o.UseUnweightedGraph()));
            }

            if (metadata.Weighted && metadata.AllPositiveWeights)
            {
                return(graph.FindShortestPath(startingVertex, destinationVertex, o => o.UseDijkstra()));
            }

            if (metadata.HasNegativeWeights && metadata.Type == GraphType.Directed)
            {
                return(graph.FindShortestPath(startingVertex, destinationVertex, o => o.UseBellmanFord()));
            }

            // if (metadata.HasNegativeWeights && metadata.Type == GraphType.Undirected)
            // Using Edmonds' Minimum Weight Perfect Matching Algorithm to solve shortest path problems for undirected graph with negative-weight edges
            // TODO: implement shortest path algorithm for Undirected graph with negative weights
            throw GraphException <T> .WhenNoShortestPathNotSupported(graph, metadata);
        }
예제 #3
0
        public static bool TryGetGraphException(HttpResponseMessage responseMessage, out GraphException exception)
        {
            if (responseMessage == null)
            {
                exception = null;
                return(false);
            }
            var content = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();

            if (string.IsNullOrEmpty(content))
            {
                exception = null;
                return(false);
            }
            try
            {
                exception = JsonConvert.DeserializeObject <GraphException>(content);
                return(true);
            }
            catch
            {
                exception = null;
                return(false);
            }
        }
        /// <summary>
        /// Resolve the error code to an appropriate exception.
        /// </summary>
        /// <param name="statusCode">Http status code.</param>
        /// <param name="errorCode">ErrorResponse code.</param>
        /// <param name="errorMessage">ErrorResponse message.</param>
        /// <returns>Sub class of GraphException, based on the error code.</returns>
        public static GraphException ResolveErrorCode(
            HttpStatusCode statusCode, ODataError oDataError)
        {
            GraphException graphException = null;

            string errorCode    = String.Empty;
            string errorMessage = String.Empty;
            List <ExtendedErrorValue> extendedErrorValues = null;

            if (oDataError != null && oDataError.Error != null)
            {
                errorCode = oDataError.Error.Code;

                if (oDataError.Error.Message != null)
                {
                    errorMessage = oDataError.Error.Message.MessageValue;
                }

                extendedErrorValues = oDataError.Error.Values;
            }

            if (ErrorCodes.ExceptionErrorCodeMap.ContainsKey(errorCode))
            {
                Type            exceptionType   = ErrorCodes.ExceptionErrorCodeMap[errorCode];
                ConstructorInfo constructorInfo =
                    exceptionType.GetConstructor(new [] { typeof(HttpStatusCode), typeof(string) });

                if (constructorInfo != null)
                {
                    graphException = constructorInfo.Invoke(new object[] { statusCode, errorMessage }) as GraphException ??
                                     new GraphException(statusCode, errorCode, errorMessage);

                    graphException.Code           = errorCode;
                    graphException.HttpStatusCode = statusCode;
                    graphException.ErrorMessage   = errorMessage;
                }
            }

            if (graphException == null)
            {
                graphException = new GraphException(statusCode, errorCode, errorMessage);
            }

            if (extendedErrorValues != null)
            {
                graphException.ExtendedErrors = new Dictionary <string, string>();

                extendedErrorValues.ForEach(x => graphException.ExtendedErrors[x.Item] = x.Value);
            }

            graphException.ErrorResponse = oDataError;

            return(graphException);
        }
        /// <summary>
        /// Parses the error message into an exception object.
        /// </summary>
        /// <param name="webException">Web exception.</param>
        /// <returns>Aad exception object.</returns>
        public static GraphException ParseWebException(WebException webException)
        {
            GraphException graphException = null;
            HttpStatusCode statusCode     = HttpStatusCode.Unused;
            string         responseUri    = String.Empty;

            if (webException == null)
            {
                throw new ArgumentNullException("webException");
            }

            if (webException.Response != null)
            {
                statusCode  = ((HttpWebResponse)webException.Response).StatusCode;
                responseUri = webException.Response.ResponseUri.ToString();
                Stream responseStream = webException.Response.GetResponseStream();

                if (responseStream != null)
                {
                    string errorMessage;

                    using (StreamReader sr = new StreamReader(responseStream))
                    {
                        errorMessage = sr.ReadToEnd();
                    }

                    graphException = ErrorResolver.ParseErrorMessageString(statusCode, errorMessage);

                    if (webException.Response.Headers != null)
                    {
                        Utils.LogResponseHeaders(webException.Response.Headers);
                        graphException.ResponseHeaders = webException.Response.Headers;
                    }

                    webException.Response.Close();
                }
            }

            if (graphException == null)
            {
                graphException = new GraphException(statusCode, webException.Message);
            }

            graphException.ResponseUri = responseUri;
            return(graphException);
        }
        /// <summary>
        /// Parses the error message into an exception object.
        /// </summary>
        /// <param name="webException">Web exception.</param>
        /// <returns>Aad exception object.</returns>
        public static GraphException ParseWebException(WebException webException)
        {
            GraphException graphException = null;
            HttpStatusCode statusCode = HttpStatusCode.Unused;
            string responseUri = String.Empty;

            if (webException == null)
            {
                throw new ArgumentNullException("webException");
            }

            if (webException.Response != null)
            {
                statusCode = ((HttpWebResponse) webException.Response).StatusCode;
                responseUri = webException.Response.ResponseUri.ToString();
                Stream responseStream = webException.Response.GetResponseStream();

                if (responseStream != null)
                {
                    string errorMessage;

                    using (StreamReader sr = new StreamReader(responseStream))
                    {
                        errorMessage = sr.ReadToEnd();
                    }

                    graphException = ErrorResolver.ParseErrorMessageString(statusCode, errorMessage);

                    if (webException.Response.Headers != null)
                    {
                        Utils.LogResponseHeaders(webException.Response.Headers);
                        graphException.ResponseHeaders = webException.Response.Headers;
                    }

                    webException.Response.Close();
                }
            }

            if (graphException == null)
            {
                graphException = new GraphException(statusCode, webException.Message);
            }

            graphException.ResponseUri = responseUri;
            return graphException;
        }
예제 #7
0
        public static Optional <IEnumerable <WeightedEdge <T> > > FindSpanningTree <T>(this IGraph <T> graph)
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }
            var metadata = new MetadataProvider().GetMetadata(graph);

            if (metadata.Type == GraphType.Directed)
            {
                if (metadata.Disconnected)
                {
                    return(graph.FindSpanningTree(o => o.UseKruskals()));
                }

                return(graph.FindSpanningTree(o => o.UsePrims()));
            }

            // TODO: implement Spanning Tree algorithm for Undirected Connected & Disconnected (Forests) graphs
            // For directed graphs, the equivalent notion of a spanning tree is spanning arborescence. A minimum weight spanning arborescence can be found using Edmonds' algorithm. => https://brainly.in/question/3337585
            throw GraphException <T> .WhenSpanningTreeNotSupported(graph, metadata);
        }
예제 #8
0
        public Optional <IEnumerable <WeightedEdge <T> > > FindSpanningTreeEdges(IGraph <T> graph)
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }
            if (graph.Count == 0)
            {
                return(Optional <IEnumerable <WeightedEdge <T> > > .None());
            }

            var edgesToProcess    = CreatePriorityQueueAndEnqueueUniqueEdges(graph);
            var processedVertices = new HashSet <T>(graph.Comparer);
            var edgeLookup        = CreateEdgeLookupByVertex(graph);
            var spanningTree      = new List <WeightedEdge <T> >();

            while (edgesToProcess.Count > 0 && spanningTree.Count < graph.Count - 1)
            {
                var edge = edgesToProcess.Pop().Single();

                if (HasCycle(edgeLookup, edge))
                {
                    continue;
                }

                edgeLookup[edge.Source].Add(edge.Destination);
                spanningTree.Add(edge);
                processedVertices = MarkEdgeAsProcessed(edge, processedVertices);
            }

            if (processedVertices.Count != graph.Count)
            {
                throw GraphException <T> .WhenNoMinimumSpanningTree(graph);
            }

            return(spanningTree);
        }
        /// <summary>
        /// Resolve the error code to an appropriate exception.
        /// </summary>
        /// <param name="statusCode">Http status code.</param>
        /// <param name="errorCode">ErrorResponse code.</param>
        /// <param name="errorMessage">ErrorResponse message.</param>
        /// <returns>Sub class of GraphException, based on the error code.</returns>
        public static GraphException ResolveErrorCode(
            HttpStatusCode statusCode, ODataError oDataError)
        {
            GraphException graphException = null;

            string errorCode = String.Empty;
            string errorMessage = String.Empty;
            List<ExtendedErrorValue> extendedErrorValues = null;

            if (oDataError != null && oDataError.Error != null)
            {
                errorCode = oDataError.Error.Code;

                if (oDataError.Error.Message != null)
                {
                    errorMessage = oDataError.Error.Message.MessageValue;
                }

                extendedErrorValues = oDataError.Error.Values;
            }

            if (ErrorCodes.ExceptionErrorCodeMap.ContainsKey(errorCode))
            {
                Type exceptionType = ErrorCodes.ExceptionErrorCodeMap[errorCode];
                ConstructorInfo constructorInfo = 
                    exceptionType.GetConstructor(new [] { typeof(HttpStatusCode), typeof(string) });

                if (constructorInfo != null)
                {
                    graphException = constructorInfo.Invoke(new object[] { statusCode, errorMessage }) as GraphException ??
                                   new GraphException(statusCode, errorCode, errorMessage);

                    graphException.Code = errorCode;
                    graphException.HttpStatusCode = statusCode;
                    graphException.ErrorMessage = errorMessage;
                }
            }

            if (graphException == null)
            {
                graphException = new GraphException(statusCode, errorCode, errorMessage);
            }

            if (extendedErrorValues != null)
            {
                graphException.ExtendedErrors = new Dictionary<string, string>();

                extendedErrorValues.ForEach(x => graphException.ExtendedErrors[x.Item] = x.Value);
            }

            graphException.ErrorResponse = oDataError;

            return graphException;
        }