public async Task ShouldUseUserDefinedCloudWhenEnvironmentIsSetToAUserDefinedCloud()
        {
            GraphSession.Initialize(() => new GraphSession());

            // Arrange
            GraphEnvironment userDefinedEnvironment = new GraphEnvironment
            {
                Name            = "Canary",
                AzureADEndpoint = "https://login.microsoftonline.com",
                GraphEndpoint   = "https://canary.graph.microsoft.com"
            };

            GraphSession.Instance.Environment = userDefinedEnvironment;
            Uri requestUrl         = new Uri($"https://graph.microsoft.com/v1.0/users?{topParam}&{selectParam}");
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl);

            // Act
            var response = await this._invoker.SendAsync(httpRequestMessage, new CancellationToken());

            var sentRequestQuery = response.RequestMessage.RequestUri.Query;

            // Assert
            Assert.Equal(requestUrl.Scheme, response.RequestMessage.RequestUri.Scheme);
            Assert.Equal("canary.graph.microsoft.com", response.RequestMessage.RequestUri.Host);
            Assert.Contains(topParam, sentRequestQuery);
            Assert.Contains($"${selectParam}", sentRequestQuery);
            Assert.Equal(2, sentRequestQuery.Split('&').Length);

            GraphSession.Reset();
        }
コード例 #2
0
        public List <GraphEnvironment> GetResult(GraphEnvironment environment)
        {
            var results = new List <GraphEnvironment>();

            this.CalculateInitialROI(environment);

            var seedsQuantity = int.Parse(ConfigurationManager.AppSettings["MaxSeeds"]);

            var seedsResult       = new List <GraphEnvironment>();
            var backupResult      = new List <GraphEnvironment>();
            var originalGraphs    = new Queue <Graph>();
            var originalCapacity  = environment.Trucks.FirstOrDefault().Capacity;
            var originalTimeLimit = environment.Trucks.FirstOrDefault().TimeLimit;
            var origGraph         = environment.Graph.Clone();

            for (int i = 0; i < seedsQuantity; i++)
            {
                var auxEnv   = environment.Clone();
                var auxGraph = environment.Graph.Clone();
                seedsResult.Add(auxEnv);
                originalGraphs.Enqueue(auxGraph);
            }

            foreach (var env in seedsResult)
            {
                this.MakeSeedResult(env);
                backupResult.Add(env.CloneWithTravel());
            }


            foreach (var actualSeed in seedsResult)
            {
                //pasar un clon del grafo inicial porque los arcos viajan con profit en 0
                var worker = new LocalSearchWorker(actualSeed, originalGraphs.Dequeue(), originalCapacity, originalTimeLimit);
                worker.Run();

                results.Add(worker.resultSeed);
            }


            //Parallel.ForEach(seedsResult, (actualSeed) =>
            //{
            //    var worker = new LocalSearchWorker(actualSeed);
            //    worker.Run();

            //    results.Add(worker.resultSeed);
            //});
            var average = getAverageDiference(results, backupResult);

            Console.WriteLine("\nAverage diference percentage: " + average.ToString() + "%\n");
            var resultList = new List <GraphEnvironment>();

            var resultIndex = results.IndexOf(results.Where(x => x.AccumulatedProfit == results.Max(y => y.AccumulatedProfit)).FirstOrDefault());

            backupResult[resultIndex].SimulateTravel(origGraph, originalCapacity, originalTimeLimit);
            resultList.Add(backupResult[resultIndex]);
            // results[resultIndex].Trucks.ToList().ForEach(x => this.RemakeNodeTravel(x));
            resultList.Add(results[resultIndex]);
            return(resultList);
        }
コード例 #3
0
        public void ShouldSerializeAndDeserializeSettings()
        {
            GraphSession.Initialize(() => new GraphSession());

            // Arrange
            GraphSession.Instance.DataStore = new MockDataStore();
            GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead));

            GraphEnvironment userDefinedEnv = new GraphEnvironment
            {
                Name            = "TestCloud",
                Type            = GraphEnvironmentConstants.EnvironmentType.UserDefined,
                AzureADEndpoint = "https://tester.com",
                GraphEndpoint   = "https://tester.com"
            };

            settings.EnvironmentTable[userDefinedEnv.Name] = userDefinedEnv;

            // Act
            string serializedSettings = settings.ToString();

            settings.TryDeserializeObject(serializedSettings, out GraphSettings deserializedSettings, new GraphSettingsConverter());
            deserializedSettings.TryGetEnvironment(userDefinedEnv.Name, out IGraphEnvironment deserializedEnv);

            // Assert
            Assert.NotNull(deserializedSettings);
            Assert.NotNull(deserializedEnv);
            Assert.Equal(serializedSettings, deserializedSettings.ToString());
            Assert.Equal(userDefinedEnv.GraphEndpoint, deserializedEnv.GraphEndpoint);

            GraphSession.Reset();
        }
コード例 #4
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            if (ShouldProcess("adding environment", Name))
            {
                if (GraphEnvironment.BuiltInEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase)))
                {
                    throw new InvalidOperationException(
                              ErrorConstants.Message.CannotModifyBuiltInEnvironment.FormatCurrentCulture("add", Name));
                }

                GraphSettings settings = this.GetContextSettings();
                if (!settings.TryGetEnvironment(Name, out IGraphEnvironment newEnvironment))
                {
                    newEnvironment = new GraphEnvironment {
                        Name = Name
                    };
                }

                newEnvironment.AzureADEndpoint = AzureADEndpoint.GetBaseUrl();
                newEnvironment.GraphEndpoint   = GraphEndpoint.GetBaseUrl();
                newEnvironment.Type            = GraphEnvironmentConstants.EnvironmentType.UserDefined;
                bool isSuccess = settings.TrySetEnvironment(newEnvironment, out IGraphEnvironment mergedEnvironment);

                // Update environment session object.
                if (isSuccess && GraphSession.Instance.Environment?.Name == mergedEnvironment?.Name)
                {
                    GraphSession.Instance.Environment = mergedEnvironment;
                }

                WriteObject(mergedEnvironment);
            }
        }
コード例 #5
0
        private bool IsValidTravel(Truck truck,  GraphEnvironment environment)
        {
            var totalcost = truck.ArcsTravel.Sum(x => x.Cost);
            var totaldemand = truck.ArcsTravel.Sum(x => x.Demand);

            return truck.Capacity <= totaldemand && truck.TimeLimit <= totalcost;
        }
コード例 #6
0
 public LocalSearchWorker(GraphEnvironment seed, Graph graph, int capacity, int timeLimit)
 {
     this.resultSeed = seed;
     this.originalGraph = graph;
     this.originalCapacity = capacity;
     this.originalTimeLimit = timeLimit;
 }
コード例 #7
0
        internal Index GetIndex(string indexName)
        {
            Index index = new Index();

            index.SetLocation(UriHelper.ConcatUri(GraphEnvironment.GetBaseUri(), "db/data/index/node/" + indexName));
            return(index);
        }
        public async Task ShouldUseGermanyCloudWhenEnvironmentIsSetToGermany()
        {
            GraphSession.Initialize(() => new GraphSession());

            // Arrange
            GraphEnvironment germanyEnvironment = GraphEnvironment.BuiltInEnvironments[GraphEnvironmentConstants.EnvironmentName.Germany];

            GraphSession.Instance.Environment = germanyEnvironment;
            Uri requestUrl         = new Uri($"https://graph.microsoft.com/beta/users?{topParam}&{selectParam}");
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl);

            // Act
            var response = await this._invoker.SendAsync(httpRequestMessage, new CancellationToken());

            var sentRequestQuery = response.RequestMessage.RequestUri.Query;

            // Assert
            Assert.Equal(requestUrl.Scheme, response.RequestMessage.RequestUri.Scheme);
            Assert.Equal("graph.microsoft.de", response.RequestMessage.RequestUri.Host);
            Assert.Contains(topParam, sentRequestQuery);
            Assert.Contains(selectParam, sentRequestQuery);
            Assert.Equal(2, sentRequestQuery.Split('&').Length);

            GraphSession.Reset();
        }
コード例 #9
0
        public void Initialize()
        {
            GraphEnvironment.SetBaseUri("http://localhost:7474/");

            ModelBuilder.Add(new OrderConfiguration());
            ModelBuilder.Add(new OrderItemConfiguration());
            ModelBuilder.Add(new ProductConfiguration());
        }
コード例 #10
0
        public Node GetNode(string nodeId)
        {
            var  uri  = UriHelper.ConcatUri(GraphEnvironment.GetBaseUri(), "db/data/node/" + nodeId);
            Node node = new Node();

            node.SetLocation(uri);
            return(this.GetNode(node));
        }
コード例 #11
0
ファイル: InheritedEntityTest.cs プロジェクト: khoadd/Neo4jD
 public void Initialize()
 {
     GraphEnvironment.SetBaseUri("http://localhost:7474/");
     ModelBuilder.Add(new MyClassConfig());
     ModelBuilder.Add(new ManagerConfig());
     //Add the assemblies to the builder. We should pass Assembly path and Assmebly Name.
     ModelBuilder.AddAssembly((new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath);
 }
コード例 #12
0
        internal Index GetAutoIndex()
        {
            Index index = new Index();

            index.SetLocation(UriHelper.ConcatUri(GraphEnvironment.GetBaseUri(), "db/data/index/auto/node"));

            return(index);
        }
コード例 #13
0
        public RequestResult GetGermlinExecutionResult(Node node, string query)
        {
            query = query.Replace("#id", node.Id.ToString());
            var uri    = UriHelper.ConcatUri(GraphEnvironment.GetBaseUri(), "db/data/ext/GremlinPlugin/graphdb/execute_script");
            var result = _graphRequest.Post(RequestType.POST, uri, query);

            return(result);
        }
コード例 #14
0
        public Node CreateNode(Node node)
        {
            var uri    = UriHelper.ConcatUri(GraphEnvironment.GetBaseUri(), "db/data/node");
            var result = _graphRequest.Post(RequestType.POST, uri, node.GetProperties());

            node.SetLocation(result.GetLocation());

            return(node);
        }
コード例 #15
0
 private bool IsFeasible(GraphEnvironment environment)
 {
     var result = true;
     
     foreach(var truck in environment.Trucks)
     {
         if (!IsValidTravel(truck, environment)) return false ;
     }
     
     return result;
 }
コード例 #16
0
        internal Index Create(string indexName)
        {
            JObject indexNameJson = new JObject();

            indexNameJson.Add("name", new JValue(indexName));

            Index index = new Index();

            index.SetLocation(UriHelper.ConcatUri(GraphEnvironment.GetBaseUri(), "db/data/index/node/" + indexName));
            var response = _graphRequest.Post(RequestType.POST, UriHelper.ConcatUri(GraphEnvironment.GetBaseUri(), "db/data/index/node/"), indexNameJson.ToString());

            //Console.WriteLine(response.GetResponseData());
            return(index);
        }
コード例 #17
0
        public void CalculateInitialROI(GraphEnvironment environment)
        {
            double costRelation   = int.Parse(ConfigurationManager.AppSettings["CostRelation"]);
            double demandRelation = 100 - costRelation;

            foreach (var arc in environment.Graph.Arcs)
            {
                double profit = arc.Profit;
                double cost   = arc.Cost;
                double demand = arc.Demand;

                arc.ROI = ((profit / cost) * costRelation) + ((profit / demand) * demandRelation);
            }
        }
コード例 #18
0
        public void Run()
        {
            var maxIterations = int.Parse(ConfigurationManager.AppSettings["MaxIterations"]);

            for (int j = 0; j < maxIterations; j++)
            {
                var localSolution = this.MakeLocalSolution(resultSeed, originalCapacity, originalTimeLimit);
                if(localSolution != null)
                {
                    localSolution.SimulateTravel(this.originalGraph, this.originalCapacity, this.originalTimeLimit);
                }

                if (localSolution != null && localSolution.IsBetter(resultSeed)) resultSeed = localSolution;                
            }
            
        }
コード例 #19
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            if (ShouldProcess("updating environment", Name))
            {
                if (GraphEnvironment.BuiltInEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase)))
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                                                                      "Cannot change built-in environment {0}.", Name));
                }

                GraphSettings settings = this.GetContextSettings();
                if (!settings.TryGetEnvironment(Name, out IGraphEnvironment newEnvironment))
                {
                    newEnvironment = new GraphEnvironment {
                        Name = Name
                    };
                }

                if (MyInvocation.BoundParameters.ContainsKey(nameof(AzureADEndpoint)))
                {
                    newEnvironment.AzureADEndpoint = AzureADEndpoint.GetBaseUrl();
                }

                if (MyInvocation.BoundParameters.ContainsKey(nameof(GraphEndpoint)))
                {
                    newEnvironment.GraphEndpoint = GraphEndpoint.GetBaseUrl();
                }

                ValidateEnvironment(newEnvironment);
                newEnvironment.Type = GraphEnvironmentConstants.EnvironmentType.UserDefined;
                bool isSuccess = settings.TrySetEnvironment(newEnvironment, out IGraphEnvironment mergedEnvironment);

                // Update environment session object.
                if (isSuccess && GraphSession.Instance.Environment?.Name == mergedEnvironment?.Name)
                {
                    GraphSession.Instance.Environment = mergedEnvironment;
                }

                WriteObject(mergedEnvironment);
            }
        }
コード例 #20
0
        private void MakeSeedResult(GraphEnvironment environment)
        {
            var profit = 0;

            Finished = false;

            var trucksToRoad = environment.Trucks;

            while (!Finished)
            {
                foreach (var truck in trucksToRoad)
                {
                    this.MakeNextStep(truck, environment);
                    //truck.PrintStatus();
                }

                CheckStatus(trucksToRoad);
            }
        }
        /// <summary>
        /// Merges two <see cref="IGraphEnvironment"/> into one.
        /// </summary>
        /// <param name="environment1">The environment to merge into.</param>
        /// <param name="environment2">The environment to merge.</param>
        /// <returns>A merged <see cref="IGraphEnvironment"/>.</returns>
        public static IGraphEnvironment Merge(this IGraphEnvironment environment1, IGraphEnvironment environment2)
        {
            if (environment1 == null || environment2 == null)
            {
                throw new ArgumentNullException(nameof(environment1));
            }
            if (!string.Equals(environment1.Name, environment2.Name, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Environment names do not match.");
            }

            GraphEnvironment mergedEnvironment = new GraphEnvironment
            {
                Name            = environment1.Name,
                Type            = environment1.Type,
                AzureADEndpoint = environment1.AzureADEndpoint ?? environment2.AzureADEndpoint,
                GraphEndpoint   = environment1.GraphEndpoint ?? environment2.GraphEndpoint
            };

            return(mergedEnvironment);
        }
コード例 #22
0
        private void MakeNextStep(Truck truck, GraphEnvironment graphEnvironment)
        {
            var graph         = graphEnvironment.Graph;
            var nextArcs      = GetNextArcs(truck.ActualNode, graph.Arcs);
            var availableArcs = nextArcs.Where(x => this.CanVisit(truck, graph, x.first.Id == truck.ActualNode ? x.second : x.first)).ToList();

            if (availableArcs.Count > 0 &&
                !(truck.Capacity < graphEnvironment.MinimumDemand &&
                  truck.ActualNode == 1))
            {
                var bestArc = this.GetBestsArcsWithRandomPercentage(availableArcs, truck.Travel, truck, graphEnvironment.MinimumDemand);
                //Console.WriteLine("\n");
                //Console.WriteLine("Arco seleccionado:");
                //bestArc.Print();
                graphEnvironment.AccumulatedProfit += truck.AddToTravel(bestArc);
            }
            else
            {
                truck.IsFinished = true;
            }
        }
コード例 #23
0
        public void ShouldSaveSettingsToConfiguredDataStore()
        {
            GraphSession.Initialize(() => new GraphSession());

            // Arrange
            GraphSession.Instance.DataStore = new MockDataStore();
            GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead));

            GraphEnvironment userDefinedEnv = new GraphEnvironment
            {
                Name            = "TestCloud",
                Type            = GraphEnvironmentConstants.EnvironmentType.UserDefined,
                AzureADEndpoint = "https://tester.com",
                GraphEndpoint   = "https://tester.com"
            };
            string expectedSettingsContent = @"{
  ""EnvironmentTable"": {
    ""TestCloud"": {
      ""Name"": ""TestCloud"",
      ""AzureADEndpoint"": ""https://tester.com"",
      ""GraphEndpoint"": ""https://tester.com"",
      ""Type"": ""User-defined""
    }
  }
}";

            // Act
            // Saves settings to disk store.
            settings.TrySetEnvironment(userDefinedEnv, out IGraphEnvironment savedEnvironment);
            string settingsContent = GraphSession.Instance.DataStore.ReadFileAsText(Constants.SettingFilePath).Substring(1).TrimEnd(new[] { '\0' });

            // Assert
            Assert.NotEmpty(settingsContent);
            Assert.Equal(expectedSettingsContent, settingsContent);

            GraphSession.Reset();
        }
コード例 #24
0
        public void ShouldRemoveSettingsFromConfiguredDataStore()
        {
            GraphSession.Initialize(() => new GraphSession());

            // Arrange
            GraphSession.Instance.DataStore = new MockDataStore();
            GraphSettings    settings      = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead));
            GraphEnvironment myNewCloudEnv = new GraphEnvironment
            {
                Name            = "MyNewCloud",
                Type            = GraphEnvironmentConstants.EnvironmentType.UserDefined,
                AzureADEndpoint = "https://login.MyNewCloud.com",
                GraphEndpoint   = "https://graph.MyNewCloud.com"
            };
            GraphEnvironment trialCloudEnv = new GraphEnvironment
            {
                Name            = "TrialCloud",
                Type            = GraphEnvironmentConstants.EnvironmentType.UserDefined,
                AzureADEndpoint = "https://login.TrialCloud.com",
                GraphEndpoint   = "https://graph.TrialCloud.com"
            };

            settings.TrySetEnvironment(myNewCloudEnv, out IGraphEnvironment mergedMyNewCloudEnv);
            settings.TrySetEnvironment(trialCloudEnv, out IGraphEnvironment mergedTrialCloudEnv);

            // Act
            settings.RemoveEnvironment(trialCloudEnv.Name);
            string settingsContent = GraphSession.Instance.DataStore.ReadFileAsText(Constants.SettingFilePath);

            // Assert
            Assert.NotEmpty(settingsContent);
            // 5 built-in + 1 user-defined
            Assert.Equal(6, settings.Environments.Count());

            GraphSession.Reset();
        }
コード例 #25
0
        public Relationship GetRelationship(string relationShipId)
        {
            var uri = UriHelper.ConcatUri(GraphEnvironment.GetBaseUri(), "db/data/relationship/" + relationShipId);

            return(this.GetRelationship(uri));
        }
コード例 #26
0
        public GraphEnvironment MakeLocalSolution(GraphEnvironment environment, int originalCapacity, int originalTimeLimit)
        {
            var result = environment.Clone();

            var auxtrucks = new List<Truck>();
            foreach(var truck in environment.Trucks)
            {
                var arcsTravel = new List<Arc>();
                foreach(var arc in truck.ArcsTravel)
                {
                    arcsTravel.Add(arc);
                }

                var auxTruck = new Truck()
                {
                    ActualNode = 1,
                    ArcsTravel = arcsTravel,
                    Capacity = originalCapacity,
                    Id = truck.Id,
                    IsFinished = truck.IsFinished,
                    TimeLimit = originalTimeLimit,
                    Travel = new List<Node>()
                };

                auxTruck.Travel.Add(truck.Travel.Where(y => y.Id == auxTruck.ActualNode).FirstOrDefault());

                auxtrucks.Add(auxTruck);

            }

            result.Trucks = auxtrucks;
            var randomTruck = result.Trucks[r.Next(0, environment.Trucks.Count)];
            var randomArcIndex = r.Next(0, randomTruck.ArcsTravel.Count);

            if(randomArcIndex == 0 || randomArcIndex == randomTruck.ArcsTravel.Count - 1)
            {
                return null;
            }

            var randomArc = randomTruck.ArcsTravel[randomArcIndex];
            randomTruck.ArcsTravel.RemoveAt(randomArcIndex);
            
            //devolver lista de arcos con camino de first a second
            IList<Arc> newRoad = this.GetRoadFromTo(randomArc.first, randomArc.second, environment.Graph);
            
            if(newRoad.Count == 0) { return null; }

            var firstRoad = randomTruck.ArcsTravel.Take(randomArcIndex);
            var sndRoad = randomTruck.ArcsTravel.Skip(randomArcIndex);

            var otherList = new List<Arc>();
            foreach(var arc in firstRoad)
            {
                otherList.Add(arc);
            }

            foreach (var arc in newRoad)
            {
                otherList.Add(arc);
            }

            foreach (var arc in sndRoad)
            {
                otherList.Add(arc);
            }
            
            randomTruck.ArcsTravel = otherList;

            result.Trucks.ToList().ForEach(x => this.RemakeNodeTravel(x));
            
            //checkear environment
            if (!IsFeasible(result)) { result = null; }

            return result;
            
        }
コード例 #27
0
 public void Initialize()
 {
     GraphEnvironment.SetBaseUri("http://localhost:7474/");
 }