private static async void MainAsync(string cachePath, double zoomLevel) { var browserSettings = new BrowserSettings(); var requestContextSettings = new RequestContextSettings { CachePath = cachePath }; // RequestContext can be shared between browser instances and allows for custom settings // e.g. CachePath using(var requestContext = new RequestContext(requestContextSettings)) using (var browser = new ChromiumWebBrowser(TestUrl, browserSettings, requestContext)) { if (zoomLevel > 1) { browser.FrameLoadStart += (s, argsi) => { var b = (ChromiumWebBrowser)s; if (argsi.Frame.IsMain) { b.SetZoomLevel(zoomLevel); } }; } await LoadPageAsync(browser); // Wait for the screenshot to be taken. await browser.ScreenshotAsync().ContinueWith(DisplayBitmap); await LoadPageAsync(browser, "http://github.com"); // Wait for the screenshot to be taken. await browser.ScreenshotAsync().ContinueWith(DisplayBitmap); } }
/// <summary> /// Redirects to another page. /// </summary> /// <param name="context"></param> /// <param name="action"></param> /// <returns></returns> private ProcessingResult ProcessRedirect(RequestContext context, IActionResult action) { var redirect = (Redirect) action; context.Response.Status = HttpStatusCode.Redirect; context.Response.Add(new StringHeader("Location", redirect.Location)); return ProcessingResult.SendResponse; }
protected async Task HandleLaunchRequest( LaunchRequestArguments launchParams, RequestContext<object> requestContext) { // Execute the given PowerShell script and send the response. // Note that we aren't waiting for execution to complete here // because the debugger could stop while the script executes. Task executeTask = editorSession.PowerShellContext .ExecuteScriptAtPath(launchParams.Program) .ContinueWith( async (t) => { Logger.Write(LogLevel.Verbose, "Execution completed, terminating..."); await requestContext.SendEvent( TerminatedEvent.Type, null); // Stop the server this.Stop(); }); await requestContext.SendResult(null); }
public override Task Render(RequestContext ctx, StringWriter stream, IDummy authObj) { #if MONO AddResource(new JsResource(Constants.kWebRoot, "/js/faqPageCompiled.js", true)); #endif // render head base.Render(ctx, stream, authObj); using (new DivContainer(stream, HtmlAttributes.@class, "jumbotron clearfix")) { using (new DivContainer(stream, HtmlAttributes.@class, "container")) { using (new DivContainer(stream, HtmlAttributes.@class, "row")) { using (new DivContainer(stream, HtmlAttributes.@class, "col-xs-12")) { BaseComponent.SPAN(stream, "Maintenance", HtmlAttributes.@class, "noTopMargin h1"); P("Metaexchange is currently in maintenance mode, please check back soon."); } } } } return null; }
/// <summary> /// Create a new OffScreen Chromium Browser /// </summary> /// <param name="address">Initial address (url) to load</param> /// <param name="browserSettings">The browser settings to use. If null, the default settings are used.</param> /// <param name="requestContext">See <see cref="RequestContext" /> for more details. Defaults to null</param> /// <param name="automaticallyCreateBrowser">automatically create the underlying Browser</param> /// <param name="blendPopup">Should the popup be blended in the background in the rendering</param> /// <exception cref="System.InvalidOperationException">Cef::Initialize() failed</exception> public ChromiumWebBrowser(string address = "", BrowserSettings browserSettings = null, RequestContext requestContext = null, bool automaticallyCreateBrowser = true) { if (!Cef.IsInitialized && !Cef.Initialize()) { throw new InvalidOperationException("Cef::Initialize() failed"); } BitmapFactory = new BitmapFactory(BitmapLock); ResourceHandlerFactory = new DefaultResourceHandlerFactory(); BrowserSettings = browserSettings ?? new BrowserSettings(); RequestContext = requestContext; Cef.AddDisposable(this); Address = address; managedCefBrowserAdapter = new ManagedCefBrowserAdapter(this, true); if (automaticallyCreateBrowser) { CreateBrowser(IntPtr.Zero); } popupPosition = new Point(); popupSize = new Size(); }
/// <summary> /// Process a request. /// </summary> /// <param name="context">Request information</param> /// <returns>What to do next.</returns> public ProcessingResult Process(RequestContext context) { var uri = context.Request.Uri.AbsolutePath.TrimEnd('/'); ControllerMapping mapping; if (!_controllers.TryGetValue(uri, out mapping)) return ProcessingResult.Continue; int pos = uri.LastIndexOf('/'); var actionName = uri.Substring(pos + 1); var controller = _controllerFactory.Create(mapping.ControllerType); var actions = mapping.FindAction(actionName); var form = context.Request.Form; var queryString = context.Request.QueryString; foreach (var action in actions) { foreach (var parameter in action.GetParameters()) { var actionParameter = parameter; var httpParameter = form.FirstOrDefault( p => p.Name.Equals(actionParameter.Name, StringComparison.OrdinalIgnoreCase)) ?? queryString.FirstOrDefault( p => p.Name.Equals(actionParameter.Name, StringComparison.OrdinalIgnoreCase)); } } var result = mapping.Invoke(controller, actionName, null); return ProcessingResult.SendResponse; }
/// <summary> /// </summary> /// <param name="context"></param> /// <param name="model"></param> /// <returns></returns> public StatusCode getForecast( RequestContext context, WeatherStationModel model ) { return StatusCodes.BadNotImplemented; }
public override V3Message execute(Request message, RequestContext context) { Object returnValue = null; #if(FULL_BUILD) if (body.body == null) body.body = new object[0]; else if (!body.body.GetType().IsArray) body.body = new object[] { body.body }; try { if (Registry.ServiceRegistry.GetMapping(destination).Equals("*")) destination = source; ThreadContext.getProperties()[ORBConstants.REQUEST_HEADERS] = headers; ThreadContext.getProperties()[ORBConstants.CLIENT_ID] = clientId; returnValue = Invoker.handleInvoke( message, destination, operation, (Object[])( (Object[])body.body )[0], context ); } catch (Exception exception) { return new ErrMessage(messageId, exception); } #endif return new AckMessage(messageId, clientId, returnValue); }
protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType) { try { if (controllerType == null) return base.GetControllerInstance(requestContext, null); var controller = funqBuilder.CreateInstance(controllerType) as IController; return controller ?? base.GetControllerInstance(requestContext, controllerType); } catch (HttpException ex) { if (ex.GetHttpCode() == 404) { try { if (ServiceStackController.CatchAllController != null) { return ServiceStackController.CatchAllController(requestContext); } } catch { } //ignore not found CatchAllController } throw; } }
public async Task<ViewEngineResult> FindView(RequestContext requestContext, string viewName) { var actionDescriptor = _actionDescriptorProvider.CreateDescriptor(requestContext) as ControllerBasedActionDescriptor; if (actionDescriptor == null) { return null; } if (String.IsNullOrEmpty(viewName)) { viewName = actionDescriptor.ActionName; } string controllerName = actionDescriptor.ControllerName; var searchedLocations = new List<string>(_viewLocationFormats.Length); for (int i = 0; i < _viewLocationFormats.Length; i++) { string path = String.Format(CultureInfo.InvariantCulture, _viewLocationFormats[i], viewName, controllerName); IView view = await _virtualPathFactory.CreateInstance(path); if (view != null) { return ViewEngineResult.Found(view); } searchedLocations.Add(path); } return ViewEngineResult.NotFound(searchedLocations); }
public MetricsServices(RequestContext c, SearchQueryRepository queries ) { context = c; this.SearchQueries = queries; }
public static MetricsServices InstantiateForMemory(RequestContext c) { return new MetricsServices(c, SearchQueryRepository.InstantiateForMemory(c) ); }
public void CanAddItemToOrderAndCalculate() { RequestContext c = new RequestContext(); MerchantTribeApplication app = MerchantTribeApplication.InstantiateForMemory(c); c.CurrentStore = new Accounts.Store(); c.CurrentStore.Id = 1; Order target = new Order(); LineItem li = new LineItem() { BasePricePerItem = 19.99m, ProductName = "Sample Product", ProductSku = "ABC123", Quantity = 2 }; target.Items.Add(li); app.CalculateOrder(target); Assert.AreEqual(39.98m, target.TotalOrderBeforeDiscounts, "SubTotal was Incorrect"); Assert.AreEqual(39.98m, target.TotalGrand, "Grand Total was incorrect"); bool upsertResult = app.OrderServices.Orders.Upsert(target); Assert.IsTrue(upsertResult, "Order Upsert Failed"); Assert.AreEqual(c.CurrentStore.Id, target.StoreId, "Order store ID was not set correctly"); Assert.AreNotEqual(string.Empty, target.bvin, "Order failed to get a bvin"); Assert.AreEqual(1, target.Items.Count, "Item count should be one"); Assert.AreEqual(target.bvin, target.Items[0].OrderBvin, "Line item didn't receive order bvin"); Assert.AreEqual(target.StoreId, target.Items[0].StoreId, "Line item didn't recieve storeid"); }
public static ScheduleService InstantiateForMemory(RequestContext c) { return new ScheduleService(c, QueuedTaskRepository.InstantiateForMemory(c) ); }
/// <summary> /// Called when [execute]. /// </summary> /// <param name="context">The context.</param> /// <returns>Base return container</returns> public override BaseReturnContainer OnExecute(RequestContext context) { GetUserTagsRequestContainer requestContainer = context.InParam as GetUserTagsRequestContainer; GetUserTagsReturnContainer returnContainer = new GetUserTagsReturnContainer(); ISqlProvider sqlProvider = (ISqlProvider)ProviderFactory.Instance.CreateProvider<ISqlProvider>(requestContainer.ProviderName); Dictionary<string, object> parameters = new Dictionary<string, object>() { { "@userId", requestContainer.UserId }, { "@deleted", false } }; DataSet returnedData = sqlProvider.ExecuteQuery(SqlQueries.GetUserProfileQuery, parameters); if (returnedData.Tables.Count > 0 && returnedData.Tables[0].Rows.Count == 1) { DataRow row = returnedData.Tables[0].Rows[0]; returnContainer.Tags = row["Tags"].ToString().Split(new string[] { Constants.QuerySeparator }, StringSplitOptions.RemoveEmptyEntries).ToList<string>(); double tempDouble; double.TryParse(row["AreaOfService"].ToString(), out tempDouble); returnContainer.AreaOfService = tempDouble; returnContainer.ReturnCode = ReturnCodes.C101; } else { // User does not exist returnContainer.ReturnCode = ReturnCodes.C001; } return returnContainer; }
public void SetsMetaHeaders() { var request = new RequestContext(HttpMethods.Get, Enumerable.Empty<KeyValuePair<string, object>>()); request.Prepare(); Assert.AreEqual("dotnet", request.Request.Headers["X-Mashape-Language"]); Assert.AreEqual("0.1", request.Request.Headers["X-Mashape-Version"]); }
public BusinessObjectsPropertiesRenderForeignKeyConstructorForDbContext(MyMeta.ITable table, RequestContext context) { this._context = context; this._table = table; this._script = context.ScriptSettings; this._output = context.Zeus.Output; }
public ActionResult GetAllRequests(int?page) { int pageSize = 5; int pageNumber = (page ?? 1); var colection = new RequestContext().Requests.OrderByDescending(x => x.InitialDate); return View(colection.ToPagedList(pageNumber, pageSize)); }
public static MembershipServices InstantiateForDatabase(RequestContext c) { return new MembershipServices(c, UserQuestionRepository.InstantiateForDatabase(c), CustomerAccountRepository.InstantiateForDatabase(c) ); }
public override void Authenticate(RequestContext<AuthenticateRequest, AuthenticateResponse> requestContext) { SslConnection connection = _context.Connection as SslConnection; X509Certificate cert = connection.ClientCertificate; string certHashString = cert.GetCertHashString(); foreach(User user in ServerContext.AccessControlList.Users) { SslAuthenticationParameters auth = (SslAuthenticationParameters)user.GetAuthentication("ssl_auth"); if(auth != null && auth.CertificateHash.Equals(certHashString)) { ServerContext.ServerAuthenticationContext.AuthenticatedPermissionMember = user; AuthenticateResponse response = requestContext.CreateResponse(); response.Succeeded = true; response.Execute(); return; } } _log.WarnFormat("Could not find user associated with certificate '{0}'", certHashString); AuthenticateResponse errorResponse = requestContext.CreateResponse(); errorResponse.Succeeded = false; errorResponse.CustomErrorMessage = "No client associated with specified certificate!"; errorResponse.Execute(); }
protected async Task HandleInitializeRequest( InitializeRequest initializeParams, RequestContext<InitializeResult> requestContext) { // Grab the workspace path from the parameters editorSession.Workspace.WorkspacePath = initializeParams.RootPath; await requestContext.SendResult( new InitializeResult { Capabilities = new ServerCapabilities { TextDocumentSync = TextDocumentSyncKind.Incremental, DefinitionProvider = true, ReferencesProvider = true, DocumentHighlightProvider = true, DocumentSymbolProvider = true, WorkspaceSymbolProvider = true, HoverProvider = true, CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new string[] { ".", "-", ":", "\\" } }, SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new string[] { " " } // TODO: Other characters here? } } }); }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path)); } return (IController)_kernel.Resolve(controllerType); }
public string GenerateUrl(string areacode, int days) { var values = new { areacode = areacode, days = days }; RequestContext requestContext = new RequestContext(); requestContext.HttpContext = new HttpContextWrapper(HttpContext.Current); requestContext.RouteData = RouteData; return RouteTable.Routes.GetVirtualPath(requestContext, new RouteValueDictionary(values)).VirtualPath; }
public ActionResult GetRequestsById(int? page) { string id = User.Identity.GetUserId(); var collection = new RequestContext().Requests.Where(x => x.ClientID == id).OrderByDescending(x => x.InitialDate); int pageSize = 5; int pageNumber = (page ?? 1); return View("GetAllRequests", collection.ToPagedList(pageNumber,pageSize)); }
/// <summary> /// This renders short properties with DataAnnotations Attributes. /// </summary> /// <param name="column">The IColumn object</param> /// <param name="context">The RequestContext</param> /// <param name="omitList">Comma-delimited list of properties to omit</param> public BusinessObjectsPropertyRenderDataAnnotationsForDbContext(MyMeta.IColumn column, RequestContext context, string omitList) : this(column, context) { if (!string.IsNullOrEmpty(omitList)) this._omitList = omitList.ToLower().Split(','); else this._omitList = new string[0]; }
/// <summary> /// Sets Content-Type to "application/javascript" and sends the java script as the body. /// </summary> /// <param name="context"></param> /// <param name="action"></param> /// <returns></returns> private ProcessingResult ProcessExecuteJavascript(RequestContext context, IActionResult action) { var js = (ExecuteJavascript)action; context.Response.ContentType.Value = "application/javascript"; byte[] bytes = Encoding.UTF8.GetBytes(js.Value); context.Response.Body.Write(bytes, 0, bytes.Length); return ProcessingResult.SendResponse; }
/// <summary> /// Creates a javascript alert. /// </summary> /// <param name="context"></param> /// <param name="action"></param> /// <returns></returns> private ProcessingResult ProcessJavascriptAlert(RequestContext context, IActionResult action) { var alert = (JavascriptAlert) action; context.Response.ContentType.Value = "application/javascript"; string body = "alert('" + alert.Message.Replace("'", "\\'").Replace("\n", "\\n").Replace("\r", "") + "');"; byte[] bytes = Encoding.UTF8.GetBytes(body); context.Response.Body.Write(bytes, 0, bytes.Length); return ProcessingResult.SendResponse; }
public MembershipServices(RequestContext c, UserQuestionRepository questions, CustomerAccountRepository customers ) { context = c; this.UserQuestions = questions; this.Customers = customers; }
public void SetsTheProperMethod() { foreach (var method in AllMethods) { var request = new RequestContext(method, Enumerable.Empty<KeyValuePair<string, object>>()); request.Prepare(); Assert.AreEqual(method.ToString().ToUpper(), request.Request.Method); } }
public static AccountService InstantiateForMemory(RequestContext c) { return new AccountService(c, UserAccountRepository.InstantiateForMemory(c), AuthTokenRepository.InstantiateForMemory(c), ApiKeyRepository.InstantiateForMemory(c), StoreUserRelationshipRepository.InstantiateForMemory(c), StoreRepository.InstantiateForMemory(c)); }
public static string GetStringToSignForStandardSignedKeyAuth(RequestContext requestContext, NephosUriComponents uriComponents, SupportedAuthScheme requestAuthScheme, bool isFileService = false) { return(AuthenticationManagerHelper.GetStringToSignForStandardSharedKeyAuth(requestContext, uriComponents, SupportedAuthScheme.SharedKey, isFileService)); }
public abstract bool IsCondition(RequestContext context);
IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { return(new AsyncHttpHandler()); }
protected override void Initialize(RequestContext requestContext) { NoCheckRole = true; base.Initialize(requestContext); }
public static ScheduleService InstantiateForDatabase(RequestContext c) { return(new ScheduleService(c, QueuedTaskRepository.InstantiateForDatabase(c) )); }
public iOSTokenCacheAccessor(RequestContext requestContext) : this() { _requestContext = requestContext; }
public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext) { return(new CurrentUserImageHandler()); }
public override Task <bool> IsUserLocalAsync(RequestContext requestContext) { return(Task.FromResult(false)); }
public virtual string GetCustomizedCacheKey(RequestContext request) { return(null); }
protected override async Task <GetSyntaxTreeSymbolResponse> HandleMessage(GetSyntaxTreeSymbolRequest parameters, RequestContext <GetSyntaxTreeSymbolResponse> context) { ALSyntaxTree syntaxTree = this.Server.SyntaxTrees.FindOrCreate(parameters.path, false); ALSyntaxTreeSymbol symbol = syntaxTree.GetSyntaxTreeSymbolByPath(parameters.symbolPath); if (symbol != null) { symbol = symbol.CreateSerializableCopy(); } GetSyntaxTreeSymbolResponse response = new GetSyntaxTreeSymbolResponse(); response.symbol = symbol; return(response); }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return(controllerType == null ? null : (IController)_kernel.Get(controllerType)); }
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { return(base.GetVirtualPath(requestContext, RemoveDomainTokens(values))); }
public void RequestContext_ActivityId_ExportToMessage() { Guid activityId = Guid.NewGuid(); Guid activityId2 = Guid.NewGuid(); Guid nullActivityId = Guid.Empty; Message msg = new Message(); msg.RequestContextData = RequestContext.Export(); if (msg.RequestContextData != null) { foreach (var kvp in msg.RequestContextData) { headers.Add(kvp.Key, kvp.Value); } } ; Assert.False(headers.ContainsKey(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER), "ActivityId should not be be present " + headers.ToStrings(separator: ",")); TestCleanup(); #if !NETSTANDARD Trace.CorrelationManager.ActivityId = activityId; #else RequestContext.ActivityId.Value = activityId; #endif msg = new Message(); msg.RequestContextData = RequestContext.Export(); if (msg.RequestContextData != null) { foreach (var kvp in msg.RequestContextData) { headers.Add(kvp.Key, kvp.Value); } } ; Assert.True(headers.ContainsKey(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER), "ActivityId #1 should be present " + headers.ToStrings(separator: ",")); object result = headers[RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER]; Assert.NotNull(result); // ActivityId #1 should not be null Assert.Equal(activityId, result); // "E2E ActivityId #1 not propagated correctly" #if !NETSTANDARD Assert.Equal(activityId, Trace.CorrelationManager.ActivityId); // "Original E2E ActivityId #1 should not have changed" #else Assert.Equal(activityId, RequestContext.ActivityId.Value); // "Original E2E ActivityId #1 should not have changed" #endif TestCleanup(); #if !NETSTANDARD Trace.CorrelationManager.ActivityId = nullActivityId; #else RequestContext.ActivityId.Value = nullActivityId; #endif msg = new Message(); msg.RequestContextData = RequestContext.Export(); if (msg.RequestContextData != null) { foreach (var kvp in msg.RequestContextData) { headers.Add(kvp.Key, kvp.Value); } } ; Assert.False(headers.ContainsKey(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER), "Null ActivityId should not be present " + headers.ToStrings(separator: ",")); TestCleanup(); #if !NETSTANDARD Trace.CorrelationManager.ActivityId = activityId2; #else RequestContext.ActivityId.Value = activityId2; #endif msg = new Message(); msg.RequestContextData = RequestContext.Export(); foreach (var kvp in msg.RequestContextData) { headers.Add(kvp.Key, kvp.Value); } ; Assert.True(headers.ContainsKey(RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER), "ActivityId #2 should be present " + headers.ToStrings(separator: ",")); result = headers[RequestContext.E2_E_TRACING_ACTIVITY_ID_HEADER]; Assert.NotNull(result); // ActivityId #2 should not be null Assert.Equal(activityId2, result); // "E2E ActivityId #2 not propagated correctly" #if !NETSTANDARD Assert.Equal(activityId2, Trace.CorrelationManager.ActivityId); // "Original E2E ActivityId #2 should not have changed" #else Assert.Equal(activityId2, RequestContext.ActivityId.Value); // "Original E2E ActivityId #2 should not have changed" #endif TestCleanup(); }
public virtual async Task <Response> GetCascadeDeleteJobDetailsAsync(string jobId, RequestContext context = null) #pragma warning restore AZC0002 { Argument.AssertNotNull(jobId, nameof(jobId)); using var scope = _clientDiagnostics.CreateScope("OAuthTokensClient.GetCascadeDeleteJobDetails"); scope.Start(); try { using HttpMessage message = CreateGetCascadeDeleteJobDetailsRequest(jobId, context); return(await _pipeline.ProcessMessageAsync(message, _clientDiagnostics, context).ConfigureAwait(false)); } catch (Exception e) { scope.Failed(e); throw; } }
public IHttpHandler GetHttpHandler(RequestContext requestContext) { return(new CustomHttpHandler()); }
public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName) { return(SessionStateBehavior.Default); }
public virtual IUrlHelper CreateUrlHelper(RequestContext requestContext) { return(new UrlHelperAdapter(requestContext, this.GetRoutes())); }
public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName) { var controllerSessionBehavior = ControllerFactory.GetControllerSessionBehavior(requestContext, controllerName); return(controllerSessionBehavior); }
public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new HttpHandler(requestContext); }
private async Task SendAndReceiveFromQueueAdapter(IQueueAdapterFactory adapterFactory, IProviderConfiguration config) { IQueueAdapter adapter = await adapterFactory.CreateAdapter(); IQueueAdapterCache cache = adapterFactory.GetQueueAdapterCache(); // Create receiver per queue IStreamQueueMapper mapper = adapterFactory.GetStreamQueueMapper(); Dictionary <QueueId, IQueueAdapterReceiver> receivers = mapper.GetAllQueues().ToDictionary(queueId => queueId, adapter.CreateReceiver); Dictionary <QueueId, IQueueCache> caches = mapper.GetAllQueues().ToDictionary(queueId => queueId, cache.CreateQueueCache); await Task.WhenAll(receivers.Values.Select(receiver => receiver.Initialize(TimeSpan.FromSeconds(5)))); // test using 2 streams Guid streamId1 = Guid.NewGuid(); Guid streamId2 = Guid.NewGuid(); int receivedBatches = 0; var streamsPerQueue = new ConcurrentDictionary <QueueId, HashSet <IStreamIdentity> >(); // reader threads (at most 2 active queues because only two streams) var work = new List <Task>(); foreach (KeyValuePair <QueueId, IQueueAdapterReceiver> receiverKvp in receivers) { QueueId queueId = receiverKvp.Key; var receiver = receiverKvp.Value; var qCache = caches[queueId]; Task task = Task.Factory.StartNew(() => { while (receivedBatches < NumBatches) { var messages = receiver.GetQueueMessagesAsync(CloudQueueMessage.MaxNumberOfMessagesToPeek).Result.ToArray(); if (!messages.Any()) { continue; } foreach (IBatchContainer message in messages) { streamsPerQueue.AddOrUpdate(queueId, id => new HashSet <IStreamIdentity> { new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()) }, (id, set) => { set.Add(new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString())); return(set); }); output.WriteLine("Queue {0} received message on stream {1}", queueId, message.StreamGuid); Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents <int>().Count()); // "Half the events were ints" Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents <string>().Count()); // "Half the events were strings" } Interlocked.Add(ref receivedBatches, messages.Length); qCache.AddToCache(messages); } }); work.Add(task); } // send events List <object> events = CreateEvents(NumMessagesPerBatch); work.Add(Task.Factory.StartNew(() => Enumerable.Range(0, NumBatches) .Select(i => i % 2 == 0 ? streamId1 : streamId2) .ToList() .ForEach(streamId => adapter.QueueMessageBatchAsync(streamId, streamId.ToString(), events.Take(NumMessagesPerBatch).ToArray(), null, RequestContext.Export(this.fixture.SerializationManager)).Wait()))); await Task.WhenAll(work); // Make sure we got back everything we sent Assert.Equal(NumBatches, receivedBatches); // check to see if all the events are in the cache and we can enumerate through them StreamSequenceToken firstInCache = new EventSequenceTokenV2(0); foreach (KeyValuePair <QueueId, HashSet <IStreamIdentity> > kvp in streamsPerQueue) { var receiver = receivers[kvp.Key]; var qCache = caches[kvp.Key]; foreach (IStreamIdentity streamGuid in kvp.Value) { // read all messages in cache for stream IQueueCacheCursor cursor = qCache.GetCacheCursor(streamGuid, firstInCache); int messageCount = 0; StreamSequenceToken tenthInCache = null; StreamSequenceToken lastToken = firstInCache; while (cursor.MoveNext()) { Exception ex; messageCount++; IBatchContainer batch = cursor.GetCurrent(out ex); output.WriteLine("Token: {0}", batch.SequenceToken); Assert.True(batch.SequenceToken.CompareTo(lastToken) >= 0, $"order check for event {messageCount}"); lastToken = batch.SequenceToken; if (messageCount == 10) { tenthInCache = batch.SequenceToken; } } output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid); Assert.Equal(NumBatches / 2, messageCount); Assert.NotNull(tenthInCache); // read all messages from the 10th cursor = qCache.GetCacheCursor(streamGuid, tenthInCache); messageCount = 0; while (cursor.MoveNext()) { messageCount++; } output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid); const int expected = NumBatches / 2 - 10 + 1; // all except the first 10, including the 10th (10 + 1) Assert.Equal(expected, messageCount); } } }
public HttpHandler(RequestContext context) { this.RequestContext = context; }
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { return(null); }
public ScheduleService(RequestContext c, QueuedTaskRepository queuedTasks) { context = c; this.QueuedTasks = queuedTasks; }
public void AddByTeant(RequestContext context, Guid TenantId, T entity) { entity.TenantId = Guid.NewGuid(); Add(context, entity); }
public override IController CreateController(RequestContext requestContext, string controllerName) { // use our own controller return(base.CreateController(requestContext, "Blocks")); }
public virtual async Task <Response> GetOAuthConnectionLinkAsync(RequestContent content, RequestContext context = null) #pragma warning restore AZC0002 { using var scope = _clientDiagnostics.CreateScope("OAuthTokensClient.GetOAuthConnectionLink"); scope.Start(); try { using HttpMessage message = CreateGetOAuthConnectionLinkRequest(content, context); return(await _pipeline.ProcessMessageAsync(message, _clientDiagnostics, context).ConfigureAwait(false)); } catch (Exception e) { scope.Failed(e); throw; } }
protected virtual String GetDbProviderPrefix(RequestContext context) { return(context.SmartSqlMap.SmartSqlMapConfig.Database.DbProvider.ParameterPrefix); }
public IHttpHandler GetHttpHandler(RequestContext requestContext) { return(new MetricsMvcHttpHandler(requestContext)); }
// Override this method if you want to customize the controller/action/parameters to which // mobile users would be redirected. This lets you redirect users to the mobile equivalent // of whatever resource they originally requested. protected virtual RouteValueDictionary GetRedirectionRouteValues(RequestContext requestContext) { return(new RouteValueDictionary(new { area = "Mobile", controller = "Home", action = "Index" })); }
public virtual AsyncPageable <BinaryData> GetOAuthTokensAsync(IEnumerable <string> authProviderIds = null, IEnumerable <string> farmerIds = null, bool?isValid = null, DateTimeOffset?minCreatedDateTime = null, DateTimeOffset?maxCreatedDateTime = null, DateTimeOffset?minLastModifiedDateTime = null, DateTimeOffset?maxLastModifiedDateTime = null, int?maxPageSize = null, string skipToken = null, RequestContext context = null) #pragma warning restore AZC0002 { return(PageableHelpers.CreateAsyncPageable(CreateEnumerableAsync, _clientDiagnostics, "OAuthTokensClient.GetOAuthTokens")); async IAsyncEnumerable <Page <BinaryData> > CreateEnumerableAsync(string nextLink, int?pageSizeHint, [EnumeratorCancellation] CancellationToken cancellationToken = default)