/// <summary> /// Constructor /// </summary> /// <param name="requestProcessors">List of <see cref="IRequestProcessor"/> that could process requests.</param> public MessageBus(IRequestProcessor[] requestProcessors) { if ((requestProcessors == null) || (requestProcessors.Length == 0)) throw new ArgumentException("requestProcessors should have at least one IRequestProcessor."); Contract.EndContractBlock(); this.requestProcessors = requestProcessors; }
public OneWayRequestSuite() : base(40, 20) { IoC.Container = new Agatha.Unity.Container(); serviceLayerConfiguration = new ServiceLayerConfiguration(Assembly.GetExecutingAssembly(), Assembly.GetExecutingAssembly(), IoC.Container) { BusinessExceptionType = typeof(BusinessException), SecurityExceptionType = typeof(SecurityException), CacheManagerImplementation = typeof(CacheManagerSpy) }; serviceLayerConfiguration.Initialize(); // i want to take advantage of the automatic initialization, so i'm just resolving the requestprocessor instead of creating it requestProcessor = IoC.Container.Resolve<IRequestProcessor>(); // the cache manager is a singleton so i can just resolve it and it'll be the same one the request processor uses cacheManager = (CacheManagerSpy)IoC.Container.Resolve<ICacheManager>(); firstOneWayRequestHandler = MockRepository.GenerateMock<IOneWayRequestHandler<FirstOneWayRequest>>(); secondOneWayRequestHandler = MockRepository.GenerateMock<IOneWayRequestHandler<SecondOneWayRequest>>(); thirdOneWayRequestHandler = MockRepository.GenerateMock<IOneWayRequestHandler<ThirdOneWayRequest>>(); IoC.Container.RegisterInstance(firstOneWayRequestHandler); IoC.Container.RegisterInstance(secondOneWayRequestHandler); IoC.Container.RegisterInstance(thirdOneWayRequestHandler); }
public HttpServer(Uri uri) { _uri = uri; _scheduler = KayakScheduler.Factory.Create(new SchedulerDelegate()); _requestProcessor = new RequestProcessor(new EndpointMatchingRule(), new RequestHandlerList()); _requestWasCalled = new RequestWasCalled(_requestProcessor); _requestWasNotCalled = new RequestWasNotCalled(_requestProcessor); _requestHandlerFactory = new RequestHandlerFactory(_requestProcessor); }
public RequestProcessor(HttpListenerContext context, Dictionary<string, IRequestProcessor> processors, IRequestProcessor defaultProcessor, ICustomLogger logger) { _logger = logger; try { var result = HttpStatusCode.OK; result = !processors.ContainsKey(context.Request.Url.LocalPath.ToLower()) ? defaultProcessor.Process(context, null) : processors[context.Request.Url.LocalPath.ToLower()].Process(context, _presenter); _logger.LogRequest(context.Request.HttpMethod, context.Request.Url.ToString(), result); } catch (MethodNotAllowedException ex) { var result = _presenter.FormatError(HttpStatusCode.MethodNotAllowed, ex.Message); var responseArray = Encoding.UTF8.GetBytes(result); context.Response.StatusCode = (int) HttpStatusCode.MethodNotAllowed; context.Response.ContentType = "text/html; charset=utf-8"; context.Response.ContentLength64 = responseArray.Length; context.Response.OutputStream.Write(responseArray, 0, responseArray.Length); context.Response.OutputStream.Close(); _logger.LogRequest(ex.RequestedMethod, ex.Query, HttpStatusCode.MethodNotAllowed); } catch (MissedParamsException ex) { var result = _presenter.FormatError(HttpStatusCode.Forbidden, ex.Message); var responseArray = Encoding.UTF8.GetBytes(result); context.Response.StatusCode = (int) HttpStatusCode.Forbidden; context.Response.ContentType = "text/html; charset=utf-8"; context.Response.ContentLength64 = responseArray.Length; context.Response.OutputStream.Write(responseArray, 0, responseArray.Length); context.Response.OutputStream.Close(); _logger.LogRequest(context.Request.HttpMethod, ex.Query, HttpStatusCode.Forbidden); } catch (ArgumentNullException ex) { } catch (Exception ex) { if (context != null) { context.Response.StatusCode = (int) HttpStatusCode.InternalServerError; context.Response.OutputStream.Close(); } } }
public OccurrencesAdminListView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
// For testing only internal void Initialize(IRequestProcessor requestProcessor) { _requestProcessor = requestProcessor; _http1Connection = requestProcessor as Http1Connection; _protocolSelectionState = ProtocolSelectionState.Selected; }
public ProviderDataProxy(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public RegistrationFormListView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
/// <summary> /// utility method to perform HTTP POST for Twitter requests with side-effects /// </summary> /// <param name="url">URL of request</param> /// <param name="parameters">parameters to post</param> /// <param name="requestProcessor">IRequestProcessor to handle response</param> /// <returns>response from server, handled by the requestProcessor</returns> public IList ExecuteTwitter(string url, Dictionary <string, string> parameters, IRequestProcessor requestProcessor) { string paramsJoined = string.Empty; paramsJoined = string.Join( "&", (from param in parameters where !string.IsNullOrEmpty(param.Value) select param.Key + "=" + OAuthTwitter.OAuthParameterUrlEncode(param.Value)) .ToArray()); url += "?" + paramsJoined; var req = WebRequest.Create(url) as HttpWebRequest; if (AuthorizedViaOAuth) { req.Headers.Add( HttpRequestHeader.Authorization, OAuthTwitter.GetOAuthAuthorizationHeader(url, null)); } else { req.Credentials = new NetworkCredential(UserName, Password); } var bytes = Encoding.UTF8.GetBytes(paramsJoined); req.ContentLength = bytes.Length; req.Method = "POST"; req.ContentType = "x-www-form-urlencoded"; req.UserAgent = UserAgent; req.ServicePoint.Expect100Continue = false; string responseXML; using (var reqStream = req.GetRequestStream()) { reqStream.Write(bytes, 0, bytes.Length); WebResponse resp = null; try { resp = req.GetResponse(); using (var respStream = resp.GetResponseStream()) using (var respRdr = new StreamReader(respStream)) { responseXML = respRdr.ReadToEnd(); } } catch (WebException wex) { var twitterQueryEx = CreateTwitterQueryException(wex); throw twitterQueryEx; } finally { if (resp != null) { resp.Close(); } } } var responseXElem = XElement.Parse(responseXML); var results = requestProcessor.ProcessResults(responseXElem); return(results); }
public EventTypeAdminDetailView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public RequestBehaviorBuilder WithRequest(Action <ActualRequest> action, Func <ActualRequest, bool> matchFunc = null) { processor = new RequestProcessor(matchFunc ?? (r => true), action); return(this); }
public RequestBehaviorBuilder WithMultipartRequest(Action <ActualRequest <MultipartContentProvider> > action) { processor = new RequestProcessor <MultipartContentProvider>((r => true), action); return(this); }
public Stream ProcessRequest(HttpContextServiceHost ctx) { DateTime startTime = DateTime.Now; bool logged = false; Exception raisedException = null; try { try { // Intialize the service host first, since most of the logic depends on it. _serviceHost = ctx;// new HttpContextServiceHost(messageBody); //_serviceHost.ValidateRequestHttpVerbAndSegments(); // Create the configuration. The first call will initialize the configuration // and all other calls will be a no-op. CreateConfiguration(CurrentScope()); // Raise event for user code InvokeOnSyncRequestStart(); _requestDescription = new RequestParser(_serviceHost, _syncConfiguration).ParseIncomingRequest(); string email; Guid userId = Logon(ctx, out email); ctx.UserId = userId.ToString(); ctx.UserEMail = email; Common.Logon.CheckLicense(CurrentScope(), ctx.Headers["deviceId"]); Common.Logon.CheckCoreVersion(CurrentScope(), ctx.Headers["coreversion"]); ctx.ResourceVersion = Common.Logon.GetResourceVersion(CurrentScope()); //add request parameters _requestDescription.RequestParams = new Dictionary <string, object>(); _requestDescription.RequestParams.Add("@UserId", userId); if (null == _requestDescription.SyncBlob || 0 == _requestDescription.SyncBlob.Length) { InitializeNewClient(userId, "Default"); } _requestProcessor = RequestProcessorFactory.GetRequestProcessorInstance(_requestDescription.RequestCommand, _syncConfiguration, _serviceHost); _outgoingMessage = _requestProcessor.ProcessRequest(_requestDescription); // Add sync properties var responseProperties = _outgoingMessage.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty; if (null != responseProperties) { responseProperties.Headers[SyncServiceConstants.SYNC_SERVICE_VERSION_KEY] = SyncServiceConstants.SYNC_SERVICE_VERSION_VALUE; responseProperties.Headers[SyncServiceConstants.SYNC_SERVICE_USERID] = userId.ToString(); } // Raise event for user code InvokeOnEndSyncRequest(_outgoingMessage); } catch (SyncServiceException syncServiceException) { raisedException = syncServiceException; ProcessSyncServiceException(ctx, syncServiceException); //_outgoingMessage is set inside } catch (DbSyncException dbSyncException) { raisedException = dbSyncException; if (dbSyncException.Message.StartsWith("Cannot find a valid scope")) { _outgoingMessage = CreateExceptionMessage(ctx, HttpStatusCode.Conflict, dbSyncException.Message); } else { _outgoingMessage = CreateExceptionMessageEx(dbSyncException, ctx); } } catch (Exception exception) { if (WebUtil.IsFatalException(exception)) { throw; } raisedException = exception; if (_outgoingMessage == null) { _outgoingMessage = CreateExceptionMessageEx(exception, ctx); } if (_outgoingMessage == null) { _outgoingMessage = CreateMessageFromUnhandledException(ctx, exception); } } return(MessageToStream(_outgoingMessage, ctx)); } finally { if (!logged) { logged = LogRequestInfo(startTime, ctx.Headers); } if (raisedException != null) { LogException(raisedException); } LogToDb(_requestDescription.RequestCommand, ctx, startTime, ctx.Headers, raisedException); } }
public Func <IEnumerable <ActualRequest <T> > > RetrieveAll <T>(T schema = default(T)) { processor = processor ?? new AlwaysMatchProcessor <T>(); return(() => processor.Matches.OfType <ActualRequest <T> >()); }
public Func <IEnumerable <ActualRequest> > RetrieveAll() { processor = processor ?? new AlwaysMatchProcessor(); return(() => processor.Matches.OfType <ActualRequest>()); }
public Func <ActualRequest> Retrieve() { processor = processor ?? new AlwaysMatchProcessor(); return(() => (ActualRequest)processor.Matches.LastOrDefault()); }
public Func <ActualRequest <T> > Retrieve <T>(T schema = default(T)) { processor = processor ?? new AlwaysMatchProcessor <T>(); return(() => (ActualRequest <T>)processor.Matches.LastOrDefault()); }
public RequestBehaviorBuilder MatchRequest <TModel>(Func <ActualRequest <TModel>, bool> matchFunc = null) { processor = new RequestProcessor <TModel>(matchFunc ?? (r => true), r => { }); return(this); }
public AuthorizeDotNetAdminDetailView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public ServiceAdminListView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public void run() { // if everything in critical section was OK // send "release" message to the coordinator Client client = new Client(Server.getInstance().getSocketAddress(), Utils.getDefaultSocketAddress()); try { node = client.nodeList.Values.Last(); node.sendMessage("release", client.getIP()); } catch (Exception e) { Console.WriteLine("Exception while calling method" + " RequestProcessor.sendMessage " + "with message RELEASE\n"); } }
public SpecialtyDataProxy(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public RequestHandler(string path, IRequestProcessor requestProcessor) { Path = path; RequestProcessor = requestProcessor; QueryParams = new Dictionary <string, string>(); }
public async Task ProcessRequestsAsync <TContext>(IHttpApplication <TContext> httpApplication) { try { // Ensure TimeoutControl._lastTimestamp is initialized before anything that could set timeouts runs. _timeoutControl.Initialize(_systemClock.UtcNowTicks); IRequestProcessor requestProcessor = null; switch (SelectProtocol()) { case HttpProtocols.Http1: // _http1Connection must be initialized before adding the connection to the connection manager requestProcessor = _http1Connection = new Http1Connection <TContext>(_context); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.Http2: // _http2Connection must be initialized before yielding control to the transport thread, // to prevent a race condition where _http2Connection.Abort() is called just as // _http2Connection is about to be initialized. requestProcessor = new Http2Connection(_context); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.Http3: requestProcessor = new Http3Connection(_context); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.None: // An error was already logged in SelectProtocol(), but we should close the connection. break; default: // SelectProtocol() only returns Http1, Http2 or None. throw new NotSupportedException($"{nameof(SelectProtocol)} returned something other than Http1, Http2, Http3 or None."); } _requestProcessor = requestProcessor; if (requestProcessor != null) { var connectionHeartbeatFeature = _context.ConnectionFeatures.Get <IConnectionHeartbeatFeature>(); var connectionLifetimeNotificationFeature = _context.ConnectionFeatures.Get <IConnectionLifetimeNotificationFeature>(); // These features should never be null in Kestrel itself, if this middleware is ever refactored to run outside of kestrel, // we'll need to handle these missing. Debug.Assert(connectionHeartbeatFeature != null, nameof(IConnectionHeartbeatFeature) + " is missing!"); Debug.Assert(connectionLifetimeNotificationFeature != null, nameof(IConnectionLifetimeNotificationFeature) + " is missing!"); // Register the various callbacks once we're going to start processing requests // The heart beat for various timeouts connectionHeartbeatFeature?.OnHeartbeat(state => ((HttpConnection)state).Tick(), this); // Register for graceful shutdown of the server using var shutdownRegistration = connectionLifetimeNotificationFeature?.ConnectionClosedRequested.Register(state => ((HttpConnection)state).StopProcessingNextRequest(), this); // Register for connection close using var closedRegistration = _context.ConnectionContext.ConnectionClosed.Register(state => ((HttpConnection)state).OnConnectionClosed(), this); await requestProcessor.ProcessRequestsAsync(httpApplication); } } catch (Exception ex) { Log.LogCritical(0, ex, $"Unexpected exception in {nameof(HttpConnection)}.{nameof(ProcessRequestsAsync)}."); } finally { if (_http1Connection?.IsUpgraded == true) { _context.ServiceContext.ConnectionManager.UpgradedConnectionCount.ReleaseOne(); } } }
public EventDataProxy(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public PolymorphicController(IQueryProcessor queryProcessor, IRequestProcessor requestProcessor) { _queryProcessor = queryProcessor; _requestProcessor = requestProcessor; }
public PaymentGatewayListView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public DeliveryRequestsController(IRequestProcessor requestProcessor, ILogger <DeliveryRequestsController> logger) { this.requestProcessor = requestProcessor; this.logger = logger; }
public SettingsDataProxyBase(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public ServiceInstanceAdminDetailView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public SocketHandler(IRequestProcessor requestProcessor, ISocketNotifier notifier) { _requestProcessor = requestProcessor; _notifier = notifier; }
public IRequestProcessorChain Add(IRequestProcessor requestProcessor) { RequestProcessors.Add(requestProcessor); return(this); }
private bool IsAuthorized(IRequestProcessor processor) { var result = true; var attribute = (EditAuthorizationAttribute)processor.GetType().GetCustomAttributes(typeof(EditAuthorizationAttribute), false).FirstOrDefault(); if (null != attribute && attribute.RequiresAuthorization) result = _editAuthorizer.Authorize(); return result; }
/// <summary> /// Creates a new instance of the relation processor. /// </summary> public BaseLinkRelation(IHtmlLinkElement link, IRequestProcessor processor) { _link = link; _processor = processor; }
public AuthenticationDataProxy(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public Builder RequestProcessor(IRequestProcessor processor) { m_requestProcessor = processor; return(this); }
public ClinicalInterestsAdminListView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
private SimpleServer(String host, int port, AuthenticationSchemes scheme, AuthenticationSchemeSelector authSchemeSelector, IRequestProcessor requestProcessor) { Host = host; Port = port; m_authScheme = scheme; m_authSchemeSelector = authSchemeSelector; m_requestProcessor = requestProcessor; if (Port <= 0) { throw new ArgumentException("Need a port higher than 0"); } if (m_requestProcessor == null) { throw new ArgumentException("No work prcessor configured"); } }
public LanguageAdminDetailView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
/// <summary> /// Registers a request processor from the specified address. /// </summary> /// <param name="address">The address.</param> /// <param name="requestProcessor">The request processor to be registered.</param> /// <remarks> /// Client must create a pair of links (sending and receiving) at the address. The /// source.address on the sending link should contain an unique address in the client /// and it should be specified in target.address on the receiving link. /// </remarks> public void RegisterRequestProcessor(string address, IRequestProcessor requestProcessor) { AddProcessor(this.requestProcessors, address, new RequestProcessor(requestProcessor)); }
public string receiveMessage(string message, string requesterIP) { // if the received message is "request" if (message.Equals("request", StringComparison.InvariantCultureIgnoreCase)) { //if critical section is empty, access has to be granted if (Server.getInstance().isCriticalSectionEmpty()) { // so send "GRANTED" Server.getInstance().assignToCriticalSection(requesterIP); return "GRANTED"; } else // someone is in the critical section { // queue the request, return DENIED Server.getInstance().queueRequest(requesterIP); return "DENIED"; } } else if (message.Equals("release", StringComparison.InvariantCultureIgnoreCase)) { // requester is done with critical section // remove the requesterIP from critical section Server.getInstance().removeFromCriticalSection(requesterIP); // if queue is not empty, dequeue first and reply "GRANTED" if (!Server.getInstance().isQueueEmpty()) { string newRequesterIP = Server.getInstance().dequeue(); //assign critical section new enterer ip Server.getInstance().assignToCriticalSection(newRequesterIP); //print out who is the new enterer Console.WriteLine("New Critical Section Enterer IP: " + newRequesterIP); Client client = Server.getInstance().getClientByIP(newRequesterIP); // get the random English word string randomEnglishWord = Server.getInstance() .generateRandomEnglishWord(); // method to write this generated word to // client's // buffer to check it later whether or not // written // word exists in the resulting master string client.rememberWord(randomEnglishWord); try { node = client.nodeList.Values.Last(); object reply = node.enterCS(client.getIP(),randomEnglishWord); Console.WriteLine((string)reply); } catch (Exception e) { Console.WriteLine("Exception while calling method" + " RequestProcessor.enterCS\n"); } //to prevent deadlock, because the same thread can //access the sendMessage again ThreadStart threadDelegate = new ThreadStart(run); Thread tempThread = new Thread(threadDelegate); tempThread.Start(); return "GRANTED"; } else // queue is already empty, so reply GRANTED { return "GRANTED"; } } else { return "GRANTED"; } }
public RequestProcessor(IRequestProcessor processor) { this.processor = processor; this.requestLinks = new List <ListenerLink>(); this.responseLinks = new Dictionary <string, ListenerLink>(StringComparer.OrdinalIgnoreCase); }
public RequestWasNotCalled(IRequestProcessor requestProcessor) { _requestProcessor = requestProcessor; }
/// <summary> /// Search the where clause for query parameters /// </summary> /// <param name="expression">Input query expression tree</param> /// <param name="reqProc">Processor specific to this request type</param> /// <returns>Name/value pairs of query parameters</returns> static Dictionary <string, string> GetRequestParameters <T>(Expression expression, IRequestProcessor <T> reqProc) { var parameters = new Dictionary <string, string>(); // GHK FIX: Handle all wheres MethodCallExpression[] whereExpressions = new WhereClauseFinder().GetAllWheres(expression); foreach (var whereExpression in whereExpressions) { var lambdaExpression = (LambdaExpression)((UnaryExpression)(whereExpression.Arguments[1])).Operand; // translate variable references in expression into constants lambdaExpression = (LambdaExpression)Evaluator.PartialEval(lambdaExpression); Dictionary <string, string> newParameters = reqProc.GetParameters(lambdaExpression); foreach (var newParameter in newParameters) { if (!parameters.ContainsKey(newParameter.Key)) { parameters.Add(newParameter.Key, newParameter.Value); } } } return(parameters); }
public LocationAdminDetailView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public async Task ProcessRequestsAsync <TContext>(IHttpApplication <TContext> httpApplication) { try { AdaptedPipeline adaptedPipeline = null; var adaptedPipelineTask = Task.CompletedTask; // _adaptedTransport must be set prior to wiring up callbacks // to allow the connection to be aborted prior to protocol selection. _adaptedTransport = _context.Transport; if (_context.ConnectionAdapters.Count > 0) { adaptedPipeline = new AdaptedPipeline(_adaptedTransport, new Pipe(AdaptedInputPipeOptions), new Pipe(AdaptedOutputPipeOptions), Log); _adaptedTransport = adaptedPipeline; } // This feature should never be null in Kestrel var connectionHeartbeatFeature = _context.ConnectionFeatures.Get <IConnectionHeartbeatFeature>(); Debug.Assert(connectionHeartbeatFeature != null, nameof(IConnectionHeartbeatFeature) + " is missing!"); connectionHeartbeatFeature?.OnHeartbeat(state => ((HttpConnection)state).Tick(), this); var connectionLifetimeNotificationFeature = _context.ConnectionFeatures.Get <IConnectionLifetimeNotificationFeature>(); Debug.Assert(connectionLifetimeNotificationFeature != null, nameof(IConnectionLifetimeNotificationFeature) + " is missing!"); using (connectionLifetimeNotificationFeature?.ConnectionClosedRequested.Register(state => ((HttpConnection)state).StopProcessingNextRequest(), this)) { _lastTimestamp = _context.ServiceContext.SystemClock.UtcNow.Ticks; _context.ConnectionFeatures.Set <IConnectionTimeoutFeature>(this); if (adaptedPipeline != null) { // Stream can be null here and run async will close the connection in that case var stream = await ApplyConnectionAdaptersAsync(); adaptedPipelineTask = adaptedPipeline.RunAsync(stream); } IRequestProcessor requestProcessor = null; lock (_protocolSelectionLock) { // Ensure that the connection hasn't already been stopped. if (_protocolSelectionState == ProtocolSelectionState.Initializing) { switch (SelectProtocol()) { case HttpProtocols.Http1: // _http1Connection must be initialized before adding the connection to the connection manager requestProcessor = _http1Connection = CreateHttp1Connection(_adaptedTransport); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.Http2: // _http2Connection must be initialized before yielding control to the transport thread, // to prevent a race condition where _http2Connection.Abort() is called just as // _http2Connection is about to be initialized. requestProcessor = CreateHttp2Connection(_adaptedTransport); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.None: // An error was already logged in SelectProtocol(), but we should close the connection. Abort(ex: null); break; default: // SelectProtocol() only returns Http1, Http2 or None. throw new NotSupportedException($"{nameof(SelectProtocol)} returned something other than Http1, Http2 or None."); } _requestProcessor = requestProcessor; } } _context.Transport.Input.OnWriterCompleted( (_, state) => ((HttpConnection)state).OnInputOrOutputCompleted(), this); _context.Transport.Output.OnReaderCompleted( (_, state) => ((HttpConnection)state).OnInputOrOutputCompleted(), this); if (requestProcessor != null) { await requestProcessor.ProcessRequestsAsync(httpApplication); } await adaptedPipelineTask; } } catch (Exception ex) { Log.LogCritical(0, ex, $"Unexpected exception in {nameof(HttpConnection)}.{nameof(ProcessRequestsAsync)}."); } finally { DisposeAdaptedConnections(); if (_http1Connection?.IsUpgraded == true) { _context.ServiceContext.ConnectionManager.UpgradedConnectionCount.ReleaseOne(); } } }
public EducationTypesAdminDetailView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
// For testing only internal void Initialize(IDuplexPipe transport) { _requestProcessor = _http1Connection = CreateHttp1Connection(transport); _protocolSelectionState = ProtocolSelectionState.Selected; }
public RegistrantSearchAdminDetailView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public RequestDispatcher(IRequestProcessor requestProcessor, ICacheManager cacheManager) { this.requestProcessor = requestProcessor; this.cacheManager = cacheManager; InitializeState(); }
public ApiHelper(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public AdminSettingsView(IRequestProcessor requestProcessor) : base(requestProcessor) { }
/// <summary>Initializes this object.</summary> /// <param name="instance">The instance that create this object</param> /// <param name="t2gManager">The manager to interact with T2G application.</param> /// <param name="sessionManager">Manager for session.</param> /// <param name="notificationSender">The object to use to send notifications.</param> /// <param name="requestProcessor">The request processor instance.</param> /// <param name="remoteDataStoreFactory">The remote data store factory.</param> /// <param name="rtpisDataStore">The rtpis data store.</param> private static void Initialize( RealTimeService instance, IT2GManager t2gManager, ISessionManagerExtended sessionManager, INotificationSender notificationSender, IRequestProcessor requestProcessor, IRemoteDataStoreFactory remoteDataStoreFactory, IRTPISDataStore rtpisDataStore) { if (instance == null) { throw new ArgumentNullException("instance"); } if (t2gManager == null) { throw new ArgumentNullException("t2gManager"); } if (sessionManager == null) { throw new ArgumentNullException("sessionManager"); } if (notificationSender == null) { throw new ArgumentNullException("notificationSender"); } if (requestProcessor == null) { throw new ArgumentNullException("requestProcessor"); } if (remoteDataStoreFactory == null) { throw new ArgumentNullException("remoteDataStoreFactory"); } if (rtpisDataStore == null) { throw new ArgumentNullException("rtpisDataStore"); } lock (_initializationLock) { try { if (_initializationCount != 0) { Uninitialize(true); } RealTimeService._instanceCreator = instance; RealTimeService._t2gManager = t2gManager; RealTimeService._sessionManager = sessionManager; RealTimeService._notificationSender = notificationSender; RealTimeService._remoteDataStoreFactory = remoteDataStoreFactory; RealTimeService._rtpisDataStore = rtpisDataStore; RealTimeService._requestProcessor = requestProcessor; _initializationCount++; } catch (System.Exception e) { Uninitialize(true); LogManager.WriteLog(TraceType.ERROR, e.Message, "PIS.Ground.RealTime.RealTimeService.Initialize", e, EventIdEnum.RealTime); } } }
public ServicesDataProxy(IRequestProcessor requestProcessor) : base(requestProcessor) { }
public override IResponse Apply(IRequestProcessor processor) => processor.HandleRequest(this);
public void ruN(int index1) { StringBuilder result = new StringBuilder(""); List<Client> clientList = Server.getInstance().getShallowCopyClients(); Client[] clients = clientList.ToArray(); Client[] clientsOtherThanThis = Server.getInstance() .getClientsArrayOtherThan(clients[index1]); //set the state of this client to wanted, because //it wants to access critical section clients[index1].setWanted(true); //and before submitting request, the client must update its //logical clock, so //update clock, which will increment default timestamp //basically Ricart&Agrawala is using extended Lamport clock //in extended lamport clock, for each send event, the node //has to update its clock (increment timestamp) clients[index1].updateClock(); Client clienT = new Client(Server.getInstance().getSocketAddress(), Utils.getDefaultSocketAddress()); object reply = null; node = clienT.nodeList.Values.Last(); foreach( Client client in clientsOtherThanThis) { bool isRequestSendingOK = false; try { Console.WriteLine("Client " + clients[index1].getIP() + " with timeStamp " + clients[index1].getClock() + " sending \"request\" to client " + client.getIP() + "\n"); result.Append("Client " + clients[index1].getIP() + " with timeStamp " + clients[index1].getClock() + " sending \"request\" to client " + client.getIP() + "\n"); reply = node.sendmessage("request", clients[index1].getIP(), clients[index1].getClock(), client.getIP()); //if we have reached here request sending has been successful isRequestSendingOK = true; } catch(Exception e) { Console.WriteLine("Exception while executing the " + "RequestProcessor.sendMessage method for" + " each client other than this client"); result.Append("Exception while executing the " + "RequestProcessor.sendMessage method for" + " each client other than this client\n"); } if (isRequestSendingOK) { //cast reply to string string replyString = (string)reply; if (replyString.Contains(",")) { //now split and get OK sender's timestamp string[] splitComponents = replyString.Split(','); if (splitComponents[0].Equals("OK", StringComparison.InvariantCultureIgnoreCase)) { //update the logical clock, when received OK //from the other node, because it is receive event clients[index1].updateClock(int.Parse(splitComponents[1])); //increment the OK count for this client clients[index1].incrementOKCount(); } } } } //so, number of OKCount is the same as number of clients //other than this. In other words, if received "OK" from //all clients that this client has sent the request to while (clients[index1].getOKCount() != clientsOtherThanThis.Length) { //wait } if (clients[index1].getOKCount() == clientsOtherThanThis.Length) { //now this client can enter the critical section //set the using flag for this client clients[index1].setUsing(true); Server.getInstance().assignToCriticalSection(clients[index1].getIP()); // get the random English word string randomEnglishWord = Server.getInstance().generateRandomEnglishWord(); // method to write this generated word to // client's // buffer to check it later whether or not // written // word exists in the resulting master string clients[index1].rememberWord(randomEnglishWord); // now enter the critical section where the word // will be written // to the coordinator's master string // boolean variable to hold whether // criticalSection entrance was OK bool isCriticalSectionSuccess = false; try { // params will contain the client's ip who // will enter // the critical section and and the // randomEnglishWord reply = node.enterCS(clients[index1].getIP(), randomEnglishWord); // reply could be like // "Node with ip has written some word" Console.WriteLine((string)reply); result.Append((string)reply); //if we have reached here critical section completed successfully isCriticalSectionSuccess = true; } catch (Exception e) { Console.WriteLine("Exception while calling method" + " RequestProcessor.enterCS\n"); } if (isCriticalSectionSuccess) { // update clock when sending OK clients[index1].updateClock(); int oksSent = 0; int numberOfNodesOkToBeSent = clients[index1].getRequestQueue().Count(); //get the queue, send OK to all processes in own queue //and empty queue. foreach (string IP in clients[index1].getRequestQueue()) { try { result.Append("Client " + clients[index1].getIP() + " with timeStamp " + clients[index1].getClock() + " sending \"OK\" to client " + IP + "\n"); node.sendmessage("OK", clients[index1].getIP(), clients[index1].getClock(), IP); oksSent++; } catch (Exception e) { Console.WriteLine("Exception while executing the " + "RequestProcessor.sendMessage method for" + " each client other than this client"); } } //if all oks sent successfully if (oksSent == numberOfNodesOkToBeSent) { Server.getInstance().removeFromCriticalSection(clients[index1].getIP()); //now empty queue, set using and wanted flags to false //and resetOKCount to 0. clients[index1].emptyRequestQueue(); clients[index1].setUsing(false); clients[index1].setWanted(false); clients[index1].resetOKCount(); } } } }
private async Task ProcessRequestsAsync <TContext>(IHttpApplication <TContext> httpApplication) { try { // TODO: When we start tracking all connection middleware for shutdown, go back // to logging connections tart and stop in ConnectionDispatcher so we get these // logs for all connection middleware. Log.ConnectionStart(ConnectionId); KestrelEventSource.Log.ConnectionStart(this); AdaptedPipeline adaptedPipeline = null; var adaptedPipelineTask = Task.CompletedTask; // _adaptedTransport must be set prior to adding the connection to the manager in order // to allow the connection to be aported prior to protocol selection. _adaptedTransport = _context.Transport; var application = _context.Application; if (_context.ConnectionAdapters.Count > 0) { adaptedPipeline = new AdaptedPipeline(_adaptedTransport, new Pipe(AdaptedInputPipeOptions), new Pipe(AdaptedOutputPipeOptions), Log); _adaptedTransport = adaptedPipeline; } // Do this before the first await so we don't yield control to the transport until we've // added the connection to the connection manager _context.ServiceContext.ConnectionManager.AddConnection(_context.HttpConnectionId, this); _lastTimestamp = _context.ServiceContext.SystemClock.UtcNow.Ticks; _context.ConnectionFeatures.Set <IConnectionTimeoutFeature>(this); if (adaptedPipeline != null) { // Stream can be null here and run async will close the connection in that case var stream = await ApplyConnectionAdaptersAsync(); adaptedPipelineTask = adaptedPipeline.RunAsync(stream); } IRequestProcessor requestProcessor = null; lock (_protocolSelectionLock) { // Ensure that the connection hasn't already been stopped. if (_protocolSelectionState == ProtocolSelectionState.Initializing) { switch (SelectProtocol()) { case HttpProtocols.Http1: // _http1Connection must be initialized before adding the connection to the connection manager requestProcessor = _http1Connection = CreateHttp1Connection(_adaptedTransport, application); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.Http2: // _http2Connection must be initialized before yielding control to the transport thread, // to prevent a race condition where _http2Connection.Abort() is called just as // _http2Connection is about to be initialized. requestProcessor = CreateHttp2Connection(_adaptedTransport, application); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.None: // An error was already logged in SelectProtocol(), but we should close the connection. Abort(ex: null); break; default: // SelectProtocol() only returns Http1, Http2 or None. throw new NotSupportedException($"{nameof(SelectProtocol)} returned something other than Http1, Http2 or None."); } _requestProcessor = requestProcessor; } } if (requestProcessor != null) { await requestProcessor.ProcessRequestsAsync(httpApplication); } await adaptedPipelineTask; await _socketClosedTcs.Task; } catch (Exception ex) { Log.LogCritical(0, ex, $"Unexpected exception in {nameof(HttpConnection)}.{nameof(ProcessRequestsAsync)}."); } finally { _context.ServiceContext.ConnectionManager.RemoveConnection(_context.HttpConnectionId); DisposeAdaptedConnections(); if (_http1Connection?.IsUpgraded == true) { _context.ServiceContext.ConnectionManager.UpgradedConnectionCount.ReleaseOne(); } Log.ConnectionStop(ConnectionId); KestrelEventSource.Log.ConnectionStop(this); } }
public GlobalAdminDataProxy(IRequestProcessor requestProcessor) : base(requestProcessor) { }
/// <summary> /// performs HTTP POST file upload to Twitter /// </summary> /// <param name="fileName">name of file to upload</param> /// <param name="url">url to upload to</param> /// <returns>IQueryable</returns> public IList PostTwitterFile(string filePath, Dictionary <string, string> parameters, string url, IRequestProcessor requestProcessor) { var file = Path.GetFileName(filePath); string imageType; switch (Path.GetExtension(file).ToLower()) { case ".jpg": case ".jpeg": imageType = "jpg"; break; case ".gif": imageType = "gif"; break; case ".png": imageType = "png"; break; default: throw new ArgumentException( "Can't recognize the extension of the file you're uploading. Please choose either a *.gif, *.jpg, *.jpeg, or *.png file.", filePath); } string contentBoundaryBase = DateTime.Now.Ticks.ToString("x"); string beginContentBoundary = string.Format("--{0}\r\n", contentBoundaryBase); var contentDisposition = string.Format("Content-Disposition:form-data); name=\"image\"); filename=\"{0}\"\r\nContent-Type: image/{1}\r\n\r\n", file, imageType); var endContentBoundary = string.Format("\r\n--{0}--\r\n", contentBoundaryBase); var formDataSB = new StringBuilder(); if (parameters != null && parameters.Count > 0) { foreach (var param in parameters) { formDataSB.AppendFormat("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", contentBoundaryBase, param.Key, param.Value); } } byte[] fileBytes = null; string fileByteString = null; Encoding encoding = Encoding.GetEncoding("iso-8859-1"); using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[4096]; var memStr = new MemoryStream(); memStr.Position = 0; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStr.Write(buffer, 0, bytesRead); } memStr.Position = 0; fileByteString = encoding.GetString(memStr.GetBuffer()); } fileBytes = encoding.GetBytes( formDataSB.ToString() + beginContentBoundary + contentDisposition + fileByteString + endContentBoundary); var req = (HttpWebRequest)WebRequest.Create(url); req.ServicePoint.Expect100Continue = false; req.ContentType = "multipart/form-data;boundary=" + contentBoundaryBase; req.PreAuthenticate = true; req.AllowWriteStreamBuffering = true; req.Method = "POST"; req.UserAgent = UserAgent; req.ContentLength = fileBytes.Length; if (AuthorizedViaOAuth) { req.Headers.Add( HttpRequestHeader.Authorization, OAuthTwitter.GetOAuthAuthorizationHeader(url, null)); } else { req.Credentials = new NetworkCredential(UserName, Password); } string responseXML = null; using (var reqStream = req.GetRequestStream()) { reqStream.Write(fileBytes, 0, fileBytes.Length); reqStream.Flush(); } WebResponse resp = null; try { resp = req.GetResponse(); using (var respStream = resp.GetResponseStream()) using (var respRdr = new StreamReader(respStream)) { responseXML = respRdr.ReadToEnd(); } } catch (WebException wex) { var twitterQueryEx = CreateTwitterQueryException(wex); throw twitterQueryEx; } finally { if (resp != null) { resp.Close(); } } var responseXElem = XElement.Parse(responseXML); var results = requestProcessor.ProcessResults(responseXElem); return(results); }