/// <summary> /// Checks if the user has authorization to go to the target route. /// </summary> /// <param name="logger"></param> /// <param name="routeAuthorizationManager"></param> /// <param name="routingContext"></param> /// <returns></returns> public static async Task <bool> CheckRouteAuthorizationAsync( ILogger logger, IRouteAuthorizationManager routeAuthorizationManager, RoutingContext routingContext) { try { var routeAuthResult = await routeAuthorizationManager.CheckAuthorization(routingContext); var granted = routeAuthResult.Equals(RouteAuthorizationResult.Granted); logger.Information(granted ? "RouteEntry authorization granted." : "RouteEntry authorization denied."); return(granted); } catch (Exception e) { logger.Error(e, "Exception checking route authorization."); throw; } }
/// <summary> /// This is a helper method which is called to ensure that the singleton context is created and the nice url and routing /// context is created and assigned. /// </summary> /// <param name="httpContext"></param> /// <param name="applicationContext"></param> /// <param name="replaceContext"> /// if set to true will replace the current singleton with a new one, this is generally only ever used because /// during application startup the base url domain will not be available so after app startup we'll replace the current /// context with a new one in which we can access the httpcontext.Request object. /// </param> /// <returns> /// The Singleton context object /// </returns> /// <remarks> /// This is created in order to standardize the creation of the singleton. Normally it is created during a request /// in the UmbracoModule, however this module does not execute during application startup so we need to ensure it /// during the startup process as well. /// See: http://issues.umbraco.org/issue/U4-1890, http://issues.umbraco.org/issue/U4-1717 /// </remarks> public static UmbracoContext EnsureContext(HttpContextBase httpContext, ApplicationContext applicationContext, bool replaceContext, bool?preview) { if (UmbracoContext.Current != null) { if (!replaceContext) { return(UmbracoContext.Current); } UmbracoContext.Current._replacing = true; } var umbracoContext = new UmbracoContext( httpContext, applicationContext, PublishedCachesResolver.Current.Caches, preview); // create the nice urls provider // there's one per request because there are some behavior parameters that can be changed var urlProvider = new UrlProvider( umbracoContext, UrlProviderResolver.Current.Providers); // create the RoutingContext, and assign var routingContext = new RoutingContext( umbracoContext, ContentFinderResolver.Current.Finders, ContentLastChanceFinderResolver.Current.Finder, urlProvider); //assign the routing context back umbracoContext.RoutingContext = routingContext; //assign the singleton UmbracoContext.Current = umbracoContext; return(UmbracoContext.Current); }
/// <summary> /// Begins to process a request. /// </summary> /// <param name="httpContext"></param> void BeginRequest(HttpContextBase httpContext) { // do not process if client-side request if (IsClientSideRequest(httpContext.Request.Url)) { return; } // ok, process // create the LegacyRequestInitializer // and initialize legacy stuff var legacyRequestInitializer = new LegacyRequestInitializer(httpContext.Request.Url, httpContext); legacyRequestInitializer.InitializeRequest(); // create the UmbracoContext singleton, one per request, and assign var umbracoContext = new UmbracoContext( httpContext, ApplicationContext.Current, RoutesCacheResolver.Current.RoutesCache); UmbracoContext.Current = umbracoContext; // create the nice urls provider var niceUrls = new NiceUrlProvider(PublishedContentStoreResolver.Current.PublishedContentStore, umbracoContext); // create the RoutingContext, and assign var routingContext = new RoutingContext( umbracoContext, DocumentLookupsResolver.Current.DocumentLookups, LastChanceLookupResolver.Current.LastChanceLookup, PublishedContentStoreResolver.Current.PublishedContentStore, niceUrls); umbracoContext.RoutingContext = routingContext; }
private void HandleAnnouncement(UdpClientRemoteInfo remoteInfo, AnnouncementDto x) { announcementsReceivedCounter.Increment(); var peerIdentity = x.Identity; var peerId = peerIdentity.Id; bool isNewlyDiscoveredRoute = false; RoutingContext addedRoutingContext = null; UdpUnicaster addedUnicaster = null; var routingContext = routingContextsByPeerId.GetOrAdd( peerId, add => { isNewlyDiscoveredRoute = true; var unicastReceivePort = int.Parse((string)x.Identity.Properties[UdpConstants.kUnicastPortIdentityPropertyKey]); var unicastIpAddress = remoteInfo.IPEndpoint.Address; var unicastEndpoint = new IPEndPoint(unicastIpAddress, unicastReceivePort); var unicastRemoteInfo = new UdpClientRemoteInfo { Socket = remoteInfo.Socket, IPEndpoint = unicastEndpoint }; addedUnicaster = udpUnicasterFactory.Create(unicastRemoteInfo); return(addedRoutingContext = new RoutingContext(addedUnicaster)); }); if (addedRoutingContext == routingContext) { addedUnicaster.Initialize(); } if (isNewlyDiscoveredRoute) { routingTable.Register(peerId, routingContext); } peerTable.GetOrAdd(peerId).HandleInboundPeerIdentityUpdate(peerIdentity); }
public void Activate <T>(RoutingContext <T> context) { Assert.AreEqual(_bodyType, typeof(T), "The type of body was not as expected"); }
public RequestRoutingContextProxy(RoutingContext <TInput> input, Request <TInput> request) { _input = input; _request = new RequestProxy <TInput, TOutput>(request); _priority = input.Priority - 1000; }
public void RightActivate(RoutingContext <T> context, Action <RoutingContext <T> > callback) { _betaMemory.RightActivate(context, callback); }
protected void Any(RoutingContext <T> match, Action <RoutingContext <T> > callback) { _contexts.Any(match, callback); }
public void RightActivate(RoutingContext <T> context, Action <RoutingContext <T> > callback) { Any(context, callback); }
public void Activate <T>(RoutingContext <T> context) { _types.Get(typeof(T), CreateMissingAlphaNode <T>).Activate(context); }
public BrokeredMessageRoutingException(RoutingContext destinationRouterContext, Exception causeOfRoutingFailure) : this(destinationRouterContext, causeOfRoutingFailure, "Routing message to destination message failed.") { }
public BrokeredMessageRoutingException(RoutingContext destinationRouterContext, string message) : this(destinationRouterContext, null, message) { }
public MessageRoutingContextProxy(RoutingContext <TInput> input, Message <TInput> message) { _input = input; _message = new MessageProxy <TInput, TOutput>(message); _priority = input.Priority - 1000; }
/// <summary> /// Adds the <typeparamref name="TDimension"/> in the Default /// <see cref="RoutingContext"/>. /// </summary> /// <typeparam name="TDimension"></typeparam> /// <param name="context"></param> /// <param name="args"></param> /// <returns></returns> public static RoutingContext AddDefaultDimension <TDimension>(this RoutingContext context, params object[] args) where TDimension : Dimension => context.AddDimension <RoutingContext, TDimension>(args);
/// <summary> /// Note, that StringMatchRouter.SetTemplateMatchingStrings must not set any handler in RoutingContext. /// It can only customize routing by TemplateMatchingStrings. It can add|remove|edit /// current list of strings. /// <para></para> /// TemplateMatchingStrings used only for fast searching of [BotRoute(temlate)] in Dictionary. /// <para></para> /// After each IRouter processing mvc middleware will search all TemplateMatchingStrings in dictionary. /// If not find - call next router. /// </summary> protected abstract Task SetTemplateMatchingStrings(RoutingContext routeContext, IList <string> templateMatchingStrings);
public void Activate(RoutingContext <T> context) { context.Match(message => _output.Activate(message), request => { }, response => { }); }
public BrokeredMessageRoutingException(RoutingContext destinationRouterContext, Exception causeOfRoutingFailure, string message) : base(message, causeOfRoutingFailure) { RoutingContext = destinationRouterContext ?? throw new ArgumentNullException(nameof(destinationRouterContext), "A destination routing context is required."); }
public void Activate(RoutingContext <T> context) { Add(context); }
public void Activate(RoutingContext <TChannel> context) { _channel.Send(context.Body); }
protected void Add(RoutingContext <T> message) { _contexts.Add(message); }
public LiteServServer(RoutingContext routes) { _routes = routes; }
public void Activate(RoutingContext <T> context) { context.Match(message => UpgradeMessageToRequest(context, message), request => _output.Activate(request), response => { }); }
/// <summary> /// Constructs the Dimension with <paramref name="context"/> and /// <paramref name="coefficient"/>. /// </summary> /// <param name="context"></param> /// <param name="coefficient"></param> public ThirdsDimension(RoutingContext context, int coefficient) : base(context, coefficient) { if (coefficient > 0) { //// TODO: TBD: unary might not be evaluating quite like we expect... //var evaluatorIndex = this.RegisterUnaryTransitEvaluationCallback(this.OnEvaluateEven); //// TODO: TBD: tried different approaches adding dimension to the model to no avail... // Estimate Vehicle Capacity given calculated weights averaged by Vehicle Count. long nodeCalculatorTotal = this.Calculator.Expand(this.Context.NodeCount).Sum(); /* Have tried, with seemingly no success, to adjust capacity and so forth, but could not land on an assignment solution, apparently. Unclear at this point how to get a status when that happens. */ var estimatedCap = nodeCalculatorTotal; // / this.Context.VehicleCount; //var estimatedCap = (long)this.Calculator.Expand(this.Context.NodeCount).Sum() / this.Context.VehicleCount; /* Based on: https://developers.google.com/optimization/routing/penalties * Unary would probably work as well, but we do go as far as to do a delta calc. */ var evaluatorIndex = this.RegisterTransitEvaluationCallback(this.OnEvaluateEven); //// TODO: TBD: not sure arc cost eval is even necessary... //this.SetArcCostEvaluators(evaluatorIndex); //// Cap literally count of nodes, allow odd scheduling, and divide among the vehicles. //var estimatedCap = (this.Context.NodeCount / 2L) / this.Context.VehicleCount; var estimatedCaps = Enumerable.Range(0, this.Context.VehicleCount).Select(_ => estimatedCap).ToArray(); this.AddDimension(evaluatorIndex, estimatedCaps); //this.AddDimension(evaluatorIndex, estimatedCap); // TODO: TBD: not sure, either approach should work? whether RDorD versus MD? this.RoutingDimensionOrDie.SetGlobalSpanCostCoefficient(coefficient); //this.MutableDimension.SetGlobalSpanCostCoefficient(coefficient); #if false // TODO: TBD: tried to add a disjunction, but did not land in a solution... //const long evenPenalty = 100; ///* Based on: https://developers.google.com/optimization/routing/penalties // * NodeToIndex and IndexToNode are key, key, KEY. Cannot overstate this enough. */ //var oddIndices = this.NodesToIndices(Enumerable.Range(0, this.Context.NodeCount) // .Where(x => x != 0 && x % 2 == 1).ToArray()).ToArray(); ///* Which, we think, should prohibit scheduling Odd nodes. // * https://developers.google.com/optimization/reference/constraint_solver/routing/RoutingModel */ //oddIndices.Select(x => new long[] { x }).ToList().ForEach( // y => this.AddDisjunction(evenPenalty, y)); //// Disjunction should be prohibiting odd number scheduling. //this.AddDisjunction(evenPenalty, oddIndices); #endif #if true // TODO: TBD: whereas "this" approach seemed to "work", but it also seems like a brute force way of describing the problem // Sets allowed vehicles for each node. var vehicleCount = this.Context.VehicleCount; var nodeCount = this.Context.NodeCount; // Confirmed this does have the effect we think it should have on solution outcomes. for (var vehicleIndex = 0; vehicleIndex < vehicleCount; vehicleIndex++) { void OnSetAllowedVehiclesForNode(int nodeIndex) => this.SetAllowedVehiclesForNode(nodeIndex, vehicleIndex); Enumerable.Range(0, nodeCount) .Where(x => x > 0 && x % vehicleCount == vehicleIndex) .ToList().ForEach(OnSetAllowedVehiclesForNode); } #endif } }
public void Activate(RoutingContext <T> context) { _rightActivation.RightActivate(context, match => _betaMemory.Activate(match)); }
void RoutingContext <T> .Convert <TResult>(Action <RoutingContext <TResult> > callback) { RoutingContext <TResult> proxy = _proxyFactoryCache[typeof(TResult)].CreateProxy <TResult>(this, _message); callback(proxy); }
public void Activate(RoutingContext <T> context) { TProperty key = _getKey(context.Body); _successors.Retrieve(key).All(activation => activation.Activate(context)); }
private void HandleAnnouncement(UdpClientRemoteInfo remoteInfo, AnnouncementDto x) { announcementsReceivedCounter.Increment(); var peerIdentity = x.Identity; var peerId = peerIdentity.Id; bool isNewlyDiscoveredRoute = false; RoutingContext addedRoutingContext = null; UdpUnicaster addedUnicaster = null; var routingContext = routingContextsByPeerId.GetOrAdd( peerId, add => { isNewlyDiscoveredRoute = true; var unicastReceivePort = int.Parse((string)x.Identity.Properties[UdpConstants.kUnicastPortIdentityPropertyKey]); var unicastIpAddress = remoteInfo.IPEndpoint.Address; var unicastEndpoint = new IPEndPoint(unicastIpAddress, unicastReceivePort); var unicastRemoteInfo = new UdpClientRemoteInfo { Socket = remoteInfo.Socket, IPEndpoint = unicastEndpoint }; addedUnicaster = udpUnicasterFactory.Create(unicastRemoteInfo); return addedRoutingContext = new RoutingContext(addedUnicaster); }); if (addedRoutingContext == routingContext) { addedUnicaster.Initialize(); } if (isNewlyDiscoveredRoute) { routingTable.Register(peerId, routingContext); } peerTable.GetOrAdd(peerId).HandleInboundPeerIdentityUpdate(peerIdentity); }
public void Add(RoutingContext <T> message) { _messages.Add(message); CallbackPendingJoins(message); }
public void TimeWindowBackground(TScope scope, RoutingContext context, DistanceMatrix matrix, IEnumerable <int[]> expectedPaths) { $"Verify {nameof(scope)} not null".x(() => scope = this.Scope.AssertNotNull() ); $"Verify {nameof(scope)}.{nameof(scope.Matrix)} not null".x(() => matrix = scope.Matrix.AssertNotNull() ); $"Verify {nameof(scope)}.{nameof(scope.Context)} not null".x(() => context = scope.Context.AssertNotNull() );; $"Arrange {nameof(scope)}.{nameof(scope.ExpectedTotalDistance)}".x(() => expectedPaths = scope.ExpectedPaths.AssertEqual(scope.VehicleCount, x => x.Count) ); // TODO: TBD: which even this is a bit boilerplate, for academic case study... $"Add {typeof(TDimension).Name} to {nameof(scope)}.{nameof(scope.Context)}".x( () => scope.Context.AddDefaultDimension <TDimension>(scope) ); IEnumerable <(int vehicle, int node, long index, long min, long max)> OnSummarizeAssignments( RoutingDimension dim, Assignment solution, IEnumerable <RouteAssignmentItem> assignments) => assignments.Select(x => (vehicle: x.Vehicle, node: x.Node, index: x.Index, var: dim.CumulVar(x.Index))) .Select(_ => (_.vehicle, _.node, _.index, min: solution.Min(_.var), max: solution.Max(_.var))); void OnScopeProblemSolverAfterAssignmentVehicle(object sender, DefaultRoutingAssignmentEventArgs e) { var context_Dim = context.Dimensions.OfType <TDimension>().AssertCollectionNotEmpty() .SingleOrDefault().AssertNotNull(); var e_Summary = OnSummarizeAssignments(context_Dim.MutableDimension, e.Solution, e.Assignments).ToArray(); var vehicle = e_Summary.Select(_ => _.vehicle).Distinct() .ToArray().AssertEqual(1, _ => _.Length).Single(); this.OutputHelper.WriteLine($"Route for vehicle {vehicle}"); this.OutputHelper.WriteLine(Join(" -> ", e_Summary.Select(_ => $"{_.node} Time({_.min}, {_.max})"))); // Verified by Distinct Vehicle above that we have at least One. this.OutputHelper.WriteLine($"Time of the route: {e_Summary.Last().min} {scope.DistanceUnit}"); } void OnScopeProblemSolverAfterAssignment(object sender, DefaultRoutingAssignmentEventArgs e) { var context_Dim = context.Dimensions.OfType <TDimension>().AssertCollectionNotEmpty() .SingleOrDefault().AssertNotNull(); var e_Summary = OnSummarizeAssignments(context_Dim.MutableDimension, e.Solution, e.Assignments).ToArray(); this.OutputHelper.WriteLine($"Total time of all routes: {e_Summary.GroupBy(_ => _.vehicle).Sum(_ => _.Last().min)}" + $" {scope.DistanceUnit}"); } $"And connect appropriate event handlers".x(() => { scope.ProblemSolver.AfterAssignmentVehicle += OnScopeProblemSolverAfterAssignmentVehicle; scope.ProblemSolver.AfterAssignment += OnScopeProblemSolverAfterAssignment; }).Rollback(() => { // TODO: TBD: which is occurring "after" scope has been disposed? // And disconnect on Rollback. scope.ProblemSolver.AfterAssignmentVehicle -= OnScopeProblemSolverAfterAssignmentVehicle; scope.ProblemSolver.AfterAssignment -= OnScopeProblemSolverAfterAssignment; }); }
public override void Initialize() { base.Initialize(); var routeData = new RouteData(); routeData.Values["controller"] = "DummyTestController"; routeData.Values["action"] = "Index"; settings = SettingsForTests.GenerateMockSettings(); routingContext = GetRoutingContext("http://localhost", -1, routeData, umbracoSettings: settings); umbracoContext = routingContext.UmbracoContext; httpContext = umbracoContext.HttpContext; var httpContextMock = Mock.Get(httpContext); httpContextMock.Setup(x => x.Items).Returns( new ListDictionary() { { HttpContextExtensions.HttpContextItemName, umbracoContext } } ); response = httpContext.Response; responseMock = Mock.Get(response); responseMock.Setup(r => r.ContentType).Returns("text/html"); responseMock.SetupProperty(r => r.Filter, Stream.Null); var experimentsPipeline = new ExperimentsPipeline(); experimentsPipeline.OnApplicationStarted(null, ApplicationContext); var originalMock = new Mock <IPublishedContent>(); originalMock.Setup(c => c.Properties).Returns(new List <IPublishedProperty>()); experimentMock = new Mock <IExperiment>(); experimentMock.Setup(e => e.Id).Returns("TESTPERIMENT"); publishedContentVariationMock = new Mock <IPublishedContentVariation>(); publishedContentVariationMock.SetupAllProperties(); publishedContentVariationMock.SetupProperty(p => p.Content, originalMock.Object); variedContent = new VariedContent(originalMock.Object, new [] { publishedContentVariationMock.Object }); var docRequest = new PublishedContentRequest( new Uri("/", UriKind.Relative), routingContext, settings.WebRouting, s => Enumerable.Empty <string>()) { PublishedContent = variedContent }; umbracoContext.PublishedContentRequest = docRequest; var viewContext = new Mock <ViewContext>(); viewContext.Setup(c => c.HttpContext).Returns(httpContext); actionExecutedMock = new Mock <ActionExecutedContext>(MockBehavior.Strict); actionExecutedMock.Setup(f => f.IsChildAction).Returns(false); actionExecutedMock.Setup(f => f.HttpContext).Returns(httpContext); resultExecutedMock = new Mock <ResultExecutedContext>(MockBehavior.Strict); resultExecutedMock.Setup(f => f.HttpContext).Returns(httpContext); htmlHelper = new HtmlHelper(viewContext.Object, Mock.Of <IViewDataContainer>()); }
public async Task <IRouteAuthorizationResult> CheckAuthorization(RoutingContext routingContext) { return(RouteAuthorizationResult.Granted); }