public HttpWebRequest GenerateRequest(ICommandRequest request, string userId, HttpMethod requestMethod) { Validator.ValidateObject(request, new ValidationContext(request, null, null), true); var webRequest = (HttpWebRequest) WebRequest.Create(request.Resource); webRequest.Method = requestMethod.ToString(); webRequest.ContentType = "application/octet-stream"; var requestType = request.GetType(); var properties = requestType.GetProperties(PropertyFilters) .Where( p => (p.GetValue(request, null) != null) && (!string.IsNullOrWhiteSpace(p.GetValue(request, null).ToString()))) .Where(p => p.GetCustomAttributes(false).OfType<HeaderAttribute>().Where(h => h.Serialise).Any()) .Select(p => new { Name = p.GetCustomAttributes(false).OfType<HeaderAttribute>().Select(h => h.Name).First(), Value = p.GetValue(request, null).ToString() }).ToList(); properties.Add(new { Name = "x-emc-date", Value = DateTime.UtcNow.ToString("r") }); properties.Add(new { Name = "x-emc-uid", Value = userId }); foreach (var property in properties) { webRequest.Headers.Add(property.Name, property.Value); } return webRequest; }
private void ReceiveCommand(ICommandRequest command) { if (command.Id == "Lock") { this.lockProvider.Lock(); } }
public IRestRequest GenerateRequest(ICommandRequest request, string apiKey) { Validator.ValidateObject(request, new ValidationContext(request, null, null), true); var queryString = new StringBuilder(); var requestType = request.GetType(); var properties = requestType.GetProperties(PropertyFilters) .Where(p => (p.GetValue(request, null) != null) && (!string.IsNullOrWhiteSpace(p.GetValue(request, null).ToString()))) .Select(p => new KeyValuePair<string, string>(p.Name.ToLowerInvariant(), p.GetValue(request, null).ToString())) .ToList(); properties.Add(new KeyValuePair<string, string>("apikey", apiKey)); var orderedProperties = properties.OrderBy(p => p.Key); foreach (var property in orderedProperties) { queryString.Append(string.Format("{0}={1}&", property.Key, property.Value)); } queryString.Remove(queryString.Length - 1, 1); var escapedQueryString = HttpUtility.UrlEncode(queryString.ToString()); return new RestRequest("?" + escapedQueryString, Method.POST); }
/* * Although this method is asynchronous, it will be called for every request * and it is not recommended to make time-consuming calls within it. */ public Task <IUser> AuthenticateAsync(ICommandRequest commandRequest, CancellationToken cancellationToken) { /* * It should be safe to assume the IPrincipal is a ClaimsPrincipal. */ var claimsPrincipal = commandRequest.Principal as ClaimsPrincipal; /* * Extract role names from claimsPrincipal. */ var roles = claimsPrincipal.Claims.Where(x => x.Type == ClaimTypes.Role).Select(x => x.Value).ToArray(); /* * It is strongly suggested to change this in a way to allow only certain users access to CKFinder. * For example you may check commandRequest.RemoteIPAddress to limit access only to your local network. */ var isAuthenticated = true; /* * Create and return the user. */ var user = new User(isAuthenticated, roles); return(Task.FromResult((IUser)user)); }
public Task <IUser> AuthenticateAsync(ICommandRequest commandRequest, CancellationToken cancellationToken) { var claimsPrincipal = commandRequest.Principal as ClaimsPrincipal; var roles = claimsPrincipal?.Claims?.Where(x => x.Type == ClaimTypes.Role).Select(x => x.Value).ToArray() ?? new string[] { }; var user = new User(IsAuthenticated(roles), roles); return(Task.FromResult((IUser)user)); }
private void OnSendCommand(long nextRequestId, Type requestType, ICommandRequest request) { if (!requestIds.ContainsKey(requestType)) { requestIds.Add(requestType, new SortedSet <long>()); } requestIds[requestType].Add(nextRequestId); outgoingRequests.Add(nextRequestId, request); }
public void Execute_With_Invalid_WorkindDirectory_Should_ReturnFailure() { ICommandRequest request = Substitute.For <ICommandRequest>(); request.WorkingDirectory.Returns(""); var service = new CommandService(); var result = service.Execute(request); Assert.IsFalse(result.Success); }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <returns></returns> public Task QueueInBackground(ICommandRequest command) { _taskQueue.QueueBackground(async _ => { using var scope = _serviceScopeFactory.CreateScope(); var commandBus = scope.ServiceProvider.GetRequiredService <ICommandBus>(); await commandBus.Dispatch(command, _applicationLifetime.ApplicationStopping); }); return(Task.CompletedTask); }
public void ValidateAsync(ICommandRequest commandRequest) { var paymentProcessCommandRequest = commandRequest as PaymentProcessRequest; var expirationDate = new DateTime(paymentProcessCommandRequest.ExpirationYear, paymentProcessCommandRequest.ExpirationMonth, 1); if (expirationDate < DateTime.Today) { throw new ExpirationDateException(); } }
public void ValidateAsync(ICommandRequest commandRequest) { var paymentProcessCommandRequest = commandRequest as PaymentProcessRequest; var numberOfDenials = _paymentReadRepository.GetNumberOfDenialsForCreditCardInAContextAsync (paymentProcessCommandRequest.ContextId, paymentProcessCommandRequest.CardNumber); if (numberOfDenials.Result >= 2) { throw new PaymentDeniedThriceException(); } }
public GetFileInfoCommand( ICommandRequest commandRequest, IResourceTypeRepository resourceTypeRepository, INodeFactory nodeFactory, INodeValidator nodeValidator) { _commandRequest = commandRequest; _resourceTypeRepository = resourceTypeRepository; _nodeFactory = nodeFactory; _nodeValidator = nodeValidator; }
/// <summary> /// /// </summary> /// <typeparam name="TResponse"></typeparam> /// <param name="command"></param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns></returns> public async Task <TResponse> Dispatch <TResponse>(ICommandRequest <TResponse> command, CancellationToken cancellationToken) { await _executeMiddlewaresService.ExecuteAsync(command, cancellationToken); var wrappedHandlers = GetWrappedHandlers(command); if (wrappedHandlers == null) { throw new CommandNotRegisteredError(command.ToString()); } return(await wrappedHandlers.Handle(command, _serviceProvider, cancellationToken)); }
public Task <IUser> AuthenticateAsync(ICommandRequest commandRequest, CancellationToken cancellationToken) { var claimsPrincipal = commandRequest.Principal as ClaimsPrincipal; //var roles = claimsPrincipal?.Claims?.Where(x => x.Type == ClaimTypes.Role).Select(x => x.Value).ToArray(); var roles = claimsPrincipal.Claims.Where(x => x.Type == ClaimTypes.Role).Select(x => x.Value).ToArray(); /* * Enable CKFinder only for authenticated users. */ var isAuthenticated = claimsPrincipal.Identity.IsAuthenticated; var user = new User(isAuthenticated, roles); return(Task.FromResult((IUser)user)); }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns></returns> public async Task Dispatch(ICommandRequest command, CancellationToken cancellationToken = default) { await _executeMiddlewaresService.ExecuteAsync(command, cancellationToken); var wrappedHandlers = GetWrappedHandlers(command); if (wrappedHandlers == null) { throw new CommandNotRegisteredError(command.ToString()); } var tasks = wrappedHandlers.Select(handler => handler.Handle(command, _serviceProvider, cancellationToken)); await Task.WhenAll(tasks); }
ICommandEvent IEventSourceSerializer.Serialize <T>(ICommandRequest <T> contextRequest) { ICommandEvent data = new CommandEvent() { Command = contextRequest.Command.ToString(), ContentType = Serializer.ContentType, ModelId = "",// contextRequest.Model.Id, Source = "source", Schema = "content-item", Sort = "1", Payload = Serializer.Serialize <T>(contextRequest.Model) }; return(data); }
public HttpResponseMessage Handle(HttpRequestMessage request, ICommandRequest command) { var a = new Func <Type, HttpRequestMessage, ICommandRequest, IRestfulStrategy>((t, r, c) => { return(Activator.CreateInstance(t, c, r) as IRestfulStrategy); }); var strategy = a.Invoke(Strategies[request.Method], request, command); //var strategy = _container.Resolve(Strategies[request.Method], // new ParameterOverride("command", command), // new ParameterOverride("request", request)) as IRestfulStrategy; return(Handle(strategy)); }
private IEnumerable <CommandHandlerWrapper> GetWrappedHandlers(ICommandRequest command) { var handlerType = typeof(ICommandRequestHandler <>).MakeGenericType(command.GetType()); var wrapperType = typeof(CommandHandlerWrapper <>).MakeGenericType(command.GetType()); var handlers = (IEnumerable)_serviceProvider.GetRequiredService(typeof(IEnumerable <>).MakeGenericType(handlerType)); var instance = handlers.Cast <object>() .Select(_ => (CommandHandlerWrapper)Activator.CreateInstance(wrapperType)); var wrappedHandlers = CommandHandlers .GetOrAdd(command.GetType(), instance); return(wrappedHandlers); }
public static ICommandRequest GetCommandRequest(ICommandRequest Comm, string CardTrack, int ElId, string Cashier) { Comm.DeviceLogicalID = iniFile.FayRetailDeviceLogicalID; Comm.OperationDate = DateTime.Now; Comm.ElementID = ElId; Comm.OperationID = Guid.NewGuid().ToString().Replace("-", ""); Comm.Cashier = Cashier; if (CardTrack != "") { Comm.Card = new Card() { Track2 = CardTrack }; } return(Comm); }
public ICommandResponse Execute(ICommandRequest commandRequest) { var result = new CommandResponse(); if (!this.ioService.DirectoryIsValid(commandRequest.WorkingDirectory)) { result.Msg = "Directory not found: " + commandRequest.WorkingDirectory; result.Success = false; return(result); } // var pwd = new DirectoryInfo(commandRequest.WorkingDirectory); // var pwdCurrent = Directory.GetCurrentDirectory(); var startInfo = new ProcessStartInfo { WorkingDirectory = commandRequest.WorkingDirectory, FileName = commandRequest.Name, Arguments = commandRequest.Arguments, RedirectStandardInput = true, RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; try { Process proc = new Process { StartInfo = startInfo }; proc.Start(); outputStrategy.Execute(proc, result); proc.WaitForExit(); } catch (Exception ex) { var msg = "Error in executing process."; throw new GitCommandException(msg, ex); } return(result); }
public Task <IUser> AuthenticateAsync(ICommandRequest commandRequest, CancellationToken cancellationToken) { var aspSessionState = GetAspSessionState(commandRequest); var roles = new List <string>(); var isEditor = aspSessionState.GetNullSafeValue("isEditor", false); var isMember = aspSessionState.GetNullSafeValue("isMember", false); if (isEditor) { roles.Add("editor"); } if (isMember) { roles.Add("member"); } var isAuthenticated = isEditor || isMember; var user = new User(isAuthenticated, roles); return(Task.FromResult((IUser)user)); }
public ICommandResponse Execute(ICommandRequest commandRequest) { var result = new CommandResponse(); if (!this.ioService.DirectoryIsValid(commandRequest.WorkingDirectory)) { result.Msg = "Directory not found: " + commandRequest.WorkingDirectory; result.Success = false; return result; } // var pwd = new DirectoryInfo(commandRequest.WorkingDirectory); // var pwdCurrent = Directory.GetCurrentDirectory(); var startInfo = new ProcessStartInfo { WorkingDirectory = commandRequest.WorkingDirectory, FileName = commandRequest.Name, Arguments = commandRequest.Arguments, RedirectStandardInput = true, RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; try { Process proc = new Process{StartInfo = startInfo}; proc.Start(); outputStrategy.Execute(proc, result); proc.WaitForExit(); } catch (Exception ex) { var msg = "Error in executing process."; throw new GitCommandException(msg, ex); } return result; }
// this method makes an http request on the background to gather ASP's all session contents and returns a JSON object // if the request contains ASP's session cookie(s) private static JObject GetAspSessionState(ICommandRequest requestContext) { // building Cookie header with ASP's session cookies var aspSessionCookies = string.Join(";", requestContext.Cookies.Where(cookie => cookie.Key.StartsWith("ASPSESSIONID")) .Select(cookie => string.Join("=", cookie.Key, cookie.Value))); if (aspSessionCookies.Length == 0) { // logs can be found in /ckfinder/App_Data/logs LoggerManager.GetLoggerForCurrentClass().Info("No ASP session cookie found"); // don't make an extra request to the connector.asp, there's no session initiated return(new JObject()); } //replace this URL with your connector.asp's var publicAspSessionConnectorUrl = new Uri("http://myaspwebsite.com/connector.asp"); var localSafeAspSessionConnectorUrl = new UriBuilder(publicAspSessionConnectorUrl) { Host = requestContext.LocalIpAddress }; using (var wCli = new WebClient()) try { wCli.Headers.Add(HttpRequestHeader.Cookie, aspSessionCookies); wCli.Headers.Add(HttpRequestHeader.Host, publicAspSessionConnectorUrl.Host); return(JObject.Parse(wCli.DownloadString(localSafeAspSessionConnectorUrl.Uri))); } catch (Exception ex) // returning an empty JObject object in any fault { // logs can be found in /ckfinder/App_Data/logs LoggerManager.GetLoggerForCurrentClass().Error(ex); return(new JObject()); } }
public Option <uint> SendCommandInternal <TCommand, TResponse>(EntityId entityId, ICommandRequest <TCommand> rawRequest, Func <ICommandResponse <TCommand>, TResponse> extractResponseFunc, CommandCallback <TResponse> callback, TimeSpan?timeout, CommandDelivery commandDelivery) where TCommand : ICommandMetaclass, new() { if (!commandResponseThunksRegistered.Contains(typeof(TCommand))) { var callbackKey = RegisterCommandResponse(extractResponseFunc); dispatcherCallbackKeys.Add(callbackKey); commandResponseThunksRegistered.Add(typeof(TCommand)); } Func <uint, uint> sendRequestWithTimeoutMs = timeoutMs => SendCommandRequest(entityId, rawRequest, timeoutMs, commandDelivery); return(SendGenericCommand(callback, sendRequestWithTimeoutMs, timeout)); }
private void EnsureAbsoluteUri(ICommandRequest request) { if (request.Resource.IsAbsoluteUri) return; var relativeResourcePath = request.Resource; request.Resource = new Uri(new Uri(_baseUrl), relativeResourcePath); }
public PostMethodStrategy(HttpRequestMessage request, ICommandRequest <T> command) : base(request) { _command = command; }
void WorkerCommands_DoWork(object sender, DoWorkEventArgs e) { while (true) { if (workerCommands.CancellationPending) { return; } // if paused we will sleep for 5 seconds, and the try again // we will remove the pause if it was set more than 12 hours ago // the pause is initiated when banned from AniDB or manually by the user if (Paused) { try { if (workerCommands.CancellationPending) { return; } TimeSpan ts = DateTime.Now - pauseTime.Value; if (ts.TotalHours >= 12) { Paused = false; } } catch { // ignore } Thread.Sleep(200); continue; } CommandRequest crdb = RepoFactory.CommandRequest.GetNextDBCommandRequestGeneral(); if (crdb == null) { if (QueueCount > 0 && !ShokoService.AnidbProcessor.IsHttpBanned && !ShokoService.AnidbProcessor.IsUdpBanned) { logger.Error($"No command returned from database, but there are {QueueCount} commands left"); } return; } if (workerCommands.CancellationPending) { return; } ICommandRequest icr = CommandHelper.GetCommand(crdb); if (icr == null) { logger.Error("No implementation found for command: {0}-{1}", crdb.CommandType, crdb.CommandID); } else { QueueState = icr.PrettyDescription; if (workerCommands.CancellationPending) { return; } logger.Trace("Processing command request: {0}", crdb.CommandID); try { CurrentCommand = crdb; icr.ProcessCommand(); } catch (Exception ex) { logger.Error(ex, "ProcessCommand exception: {0}\n{1}", crdb.CommandID, ex); } finally { CurrentCommand = null; } } logger.Trace("Deleting command request: {0}", crdb.CommandID); RepoFactory.CommandRequest.Delete(crdb.CommandRequestID); QueueCount = RepoFactory.CommandRequest.GetQueuedCommandCountGeneral(); } }
void WorkerCommands_DoWork(object sender, DoWorkEventArgs e) { while (true) { if (workerCommands.CancellationPending) { return; } // if paused we will sleep for 5 seconds, and the try again if (Paused) { try { if (workerCommands.CancellationPending) { return; } } catch { // ignore } Thread.Sleep(200); continue; } CommandRequest crdb = Repo.Instance.CommandRequest.GetNextDBCommandRequestImages(); if (crdb == null) { return; } if (workerCommands.CancellationPending) { return; } ICommandRequest icr = CommandHelper.GetCommand(crdb); if (icr == null) { return; } if (workerCommands.CancellationPending) { return; } QueueState = icr.PrettyDescription; try { CurrentCommand = crdb; icr.ProcessCommand(); } catch (Exception ex) { logger.Error(ex, "ProcessCommand exception: {0}\n{1}", crdb.CommandID, ex); } finally { CurrentCommand = null; } Repo.Instance.CommandRequest.Delete(crdb.CommandRequestID); QueueCount = Repo.Instance.CommandRequest.GetQueuedCommandCountImages(); } }
void workerCommands_DoWork(object sender, DoWorkEventArgs e) { while (true) { if (workerCommands.CancellationPending) { e.Cancel = true; return; } // if paused we will sleep for 5 seconds, and the try again // we will remove the pause if it was set more than 6 hours ago // the pause is initiated when banned from AniDB or manually by the user if (Paused) { try { if (workerCommands.CancellationPending) { e.Cancel = true; return; } //logger.Trace("Images Queue is paused: {0}", pauseTime.Value); TimeSpan ts = DateTime.Now - pauseTime.Value; if (ts.TotalHours >= 6) { Paused = false; } } catch { } Thread.Sleep(5000); continue; } //logger.Trace("Looking for next command request (images)..."); CommandRequestRepository repCR = new CommandRequestRepository(); CommandRequest crdb = repCR.GetNextDBCommandRequestImages(); if (crdb == null) { return; } QueueCount = repCR.GetQueuedCommandCountImages(); //logger.Trace("{0} commands remaining in queue (images)", QueueCount); if (workerCommands.CancellationPending) { e.Cancel = true; return; } //logger.Trace("Next command request (images): {0}", crdb.CommandID); ICommandRequest icr = CommandHelper.GetCommand(crdb); if (icr == null) { //logger.Trace("No implementation found for command: {0}-{1}", crdb.CommandType, crdb.CommandID); return; } if (workerCommands.CancellationPending) { e.Cancel = true; return; } QueueState = icr.PrettyDescription; //logger.Trace("Processing command request (images): {0}", crdb.CommandID); icr.ProcessCommand(); //logger.Trace("Deleting command request (images): {0}", crdb.CommandID); repCR.Delete(crdb.CommandRequestID); QueueCount = repCR.GetQueuedCommandCountImages(); } }
void WorkerCommands_DoWork(object sender, DoWorkEventArgs e) { while (true) { if (workerCommands.CancellationPending) { return; } // if paused we will sleep for 5 seconds, and the try again if (Paused) { try { if (workerCommands.CancellationPending) { return; } } catch { // ignore } Thread.Sleep(200); continue; } CommandRequest crdb = Repo.Instance.CommandRequest.GetNextDBCommandRequestHasher(); if (crdb == null) { if (QueueCount > 0) { logger.Error($"No command returned from repo, but there are {QueueCount} commands left"); } return; } if (workerCommands.CancellationPending) { return; } ICommandRequest icr = CommandHelper.GetCommand(crdb); if (icr == null) { logger.Trace("No implementation found for command: {0}-{1}", crdb.CommandType, crdb.CommandID); return; } QueueState = icr.PrettyDescription; if (workerCommands.CancellationPending) { return; } try { CurrentCommand = crdb; icr.ProcessCommand(); } catch (Exception ex) { logger.Error(ex, "ProcessCommand exception: {0}\n{1}", crdb.CommandID, ex); } finally { CurrentCommand = null; } Repo.Instance.CommandRequest.FindAndDelete(() => Repo.Instance.CommandRequest.GetByCommandID(crdb.CommandID)); QueueCount = Repo.Instance.CommandRequest.GetQueuedCommandCountHasher(); } }
void WorkerCommands_DoWork(object sender, DoWorkEventArgs e) { while (true) { if (workerCommands.CancellationPending) { e.Cancel = true; return; } // if paused we will sleep for 5 seconds, and the try again // we will remove the pause if it was set more than 12 hours ago // the pause is initiated when banned from AniDB or manually by the user if (Paused) { try { if (workerCommands.CancellationPending) { e.Cancel = true; return; } //logger.Trace("Queue is paused: {0}", pauseTime.Value); TimeSpan ts = DateTime.Now - pauseTime.Value; if (ts.TotalHours >= 12) { Paused = false; } } catch { } Thread.Sleep(200); continue; } //logger.Trace("Looking for next command request..."); CommandRequest crdb = RepoFactory.CommandRequest.GetNextDBCommandRequestGeneral(); if (crdb == null) { return; } if (workerCommands.CancellationPending) { e.Cancel = true; return; } QueueCount = RepoFactory.CommandRequest.GetQueuedCommandCountGeneral(); //logger.Trace("{0} commands remaining in queue", QueueCount); //logger.Trace("Next command request: {0}", crdb.CommandID); ICommandRequest icr = CommandHelper.GetCommand(crdb); if (icr == null) { logger.Error("No implementation found for command: {0}-{1}", crdb.CommandType, crdb.CommandID); } else { QueueState = icr.PrettyDescription; if (workerCommands.CancellationPending) { e.Cancel = true; return; } logger.Trace("Processing command request: {0}", crdb.CommandID); try { icr.ProcessCommand(); } catch (Exception ex) { logger.Error(ex, "ProcessCommand exception: {0}\n{1}", crdb.CommandID, ex.ToString()); } } logger.Trace("Deleting command request: {0}", crdb.CommandID); RepoFactory.CommandRequest.Delete(crdb.CommandRequestID); QueueCount = RepoFactory.CommandRequest.GetQueuedCommandCountGeneral(); } }
public Task <IUser> AuthenticateAsync(ICommandRequest commandRequest, CancellationToken cancellationToken) { var user = new User(true, null); return(Task.FromResult((IUser)user)); }
void WorkerCommands_DoWork(object sender, DoWorkEventArgs e) { while (true) { if (workerCommands.CancellationPending) { e.Cancel = true; return; } // if paused we will sleep for 5 seconds, and the try again // we will remove the pause if it was set more than 6 hours ago // the pause is initiated when banned from AniDB or manually by the user if (Paused) { try { if (workerCommands.CancellationPending) { e.Cancel = true; return; } TimeSpan ts = DateTime.Now - pauseTime.Value; if (ts.TotalHours >= 6) { Paused = false; } } catch { // ignore } Thread.Sleep(200); continue; } CommandRequest crdb = RepoFactory.CommandRequest.GetNextDBCommandRequestHasher(); if (crdb == null) { if (QueueCount > 0) { logger.Error($"No command returned from repo, but there are {QueueCount} commands left"); } return; } if (workerCommands.CancellationPending) { e.Cancel = true; return; } ICommandRequest icr = CommandHelper.GetCommand(crdb); if (icr == null) { logger.Trace("No implementation found for command: {0}-{1}", crdb.CommandType, crdb.CommandID); return; } QueueState = icr.PrettyDescription; if (workerCommands.CancellationPending) { e.Cancel = true; return; } icr.ProcessCommand(); RepoFactory.CommandRequest.Delete(crdb.CommandRequestID); QueueCount = RepoFactory.CommandRequest.GetQueuedCommandCountHasher(); } }
public async void SendCommand(ICommandRequest command) { await commandHub.Invoke <string>("Join", this.corelationId); await commandHub.Invoke <string>("Lock", command.Id, this.corelationId); }
/// <summary> /// This method is required to prevent Unity compiler issues. /// </summary> private uint SendCommandRequest <TCommand>(EntityId entityId, ICommandRequest <TCommand> rawRequest, uint timeoutMs, CommandDelivery commandDelivery) where TCommand : ICommandMetaclass, new() { return(communicator.SendCommandRequest(entityId, rawRequest, timeoutMs, commandDelivery).Id); }