public IActionResult SendMessage([Bind("Body,SenderName,SenderEmail,Subject")] Message message) { //Message message2 = this.contactService.GetById(Guid.Parse("7f0a9a23-e4ab-45c5-a647-d6e1c19c0f6a")); //message2.Subject = "Change tracker tests"; //message.Id = Guid.Parse("7f0a9a23-e4ab-45c5-a647-d6e1c19c0f6a"); //message.Subject = "Attach test"; //this.contactService.UpdateMessage(message); string errorMessage = ""; var messageValidator = new MessageValidator(); var validationResult = messageValidator.Validate(message); if (validationResult.IsValid) { this.contactService.SendMessage(message); } else { foreach (var validationFailure in validationResult.Errors) { errorMessage += validationFailure.ErrorMessage + "\n"; } ViewBag.ErrorMessage = errorMessage; } return(View("Index")); }
/// <inheritdoc /> public async Task <DispatchResponse> Dispatch(Message message, CancellationToken cancellationToken = default) { MessageValidator.Validate(message); message.Id = message.Id == Guid.Empty ? Guid.NewGuid() : message.Id; return(await GetProvider(message.Queue).Dispatch(message, cancellationToken).ConfigureAwait(false)); }
public QueueMonitor(IMessageReader reader, IMessageConverter converter, MessageValidator validator, IValidationOutput output) { _reader = reader; _converter = converter; _validator = validator; _output = output; }
public void ValidateHeader_LowerCaseIsCapitalized_ShouldPass() { string header = "s000000000"; string expectedHeader = "S000000000"; Assert.AreEqual(expectedHeader, MessageValidator.ValidateHeader(header)); }
/// <summary> /// Add messages to match / process /// </summary> private void AddMessages(IEnumerable <ResolvedMessagesSet> messages) { foreach (var resultSet in messages) { var messageAttribute = resultSet.MessageAttribute; if (messageAttribute == null) { continue; } var serverMessage = messageAttribute.Server; if (!serverMessage) { _messages.Add((MessageId)messageAttribute.Id, resultSet.Type); } _messageAttributes.Add(resultSet.Type, messageAttribute); var validator = new MessageValidator(resultSet.Type); _validators.Add(resultSet.Type, validator); foreach (var parameter in validator.Parameters) { // is nested parameter if (!_nestedValidators.ContainsKey(parameter.ParameterType) && parameter.ParameterType.GetInterfaces().Contains(typeof(IMessage))) { _nestedValidators.Add(parameter.ParameterType, new MessageValidator(parameter.ParameterType)); } } } }
public OperationStatusInfo <string> SendMessage(MessageDTO messageDto) { this.loggingService.Info($"Попытка валидации сообщения {messageDto}."); // валидация var validator = new MessageValidator(); var validationResult = validator.Validate(messageDto); // проверка валидации if (!validationResult.IsValid) { return(this.operationStatusService.HandleValidationError( $"Ошибка при валидации сообщения: {messageDto}. Текст ошибки: {validationResult}", validationResult.ToString())); } try { var message = DTOService.ToEntity <MessageDTO, Message>(messageDto); message.UserFrom = null; message.UserTo = null; this.currentRepository.Insert(message); return(this.operationStatusService.HandleSuccessOperation( $"Сообщение {messageDto} успешно отправлено.", string.Empty)); } catch (Exception exception) { return(this.operationStatusService.HandleException(exception, string.Empty)); } }
public async Task ValidateMessage_AllowedUser() { // Arrange string username = "******"; ApplicationUser user = new ApplicationUser { UserName = username, Id = "id" }; Message message = new Message { IsPrivate = true, AllowedUsers = new List <AllowedUserMessages>() { new AllowedUserMessages { User = user, UserId = user.Id } } }; var mockStore = new Mock <IUserStore <ApplicationUser> >(); var mockUserManager = new Mock <UserManager <ApplicationUser> >(mockStore.Object, null, null, null, null, null, null, null, null); mockUserManager.Setup(u => u.FindByNameAsync(username)).ReturnsAsync(user); MessageValidator validator = new MessageValidator(mockUserManager.Object); // Act var result = await validator.ValidateAsync(message, username); // Assert Assert.NotNull(result); Assert.True(result.Succeeded); }
public StoreImpl(IEnumerable <Reducer> reducers, IDictionary <string, object> state, MessageValidator messageValidator) { if (reducers == null) { throw new ArgumentNullException("reducers"); } if (state == null) { throw new ArgumentNullException("state"); } if (messageValidator == null) { throw new ArgumentNullException("messageValidator"); } this.state = state; this.reducers = reducers; this.messageValidator = messageValidator; this.subscribers = new HashSet <Action <Message> >(); this.InitializeState(); }
private MessageProcessor CreateMessageProcessor(string channel, IMessageHandler messageHandler) { var messageValidator = new MessageValidator(); var messageLoader = new MessageLoader(_connectionMultiplexer); return(new MessageProcessor(channel, messageValidator, messageLoader, messageHandler, _loggerFactory.CreateLogger <MessageProcessor>())); }
public ValidationResult ValidateMessageModel(MessageDto messageModel) { var validator = new MessageValidator(); var validatorResult = validator.Validate(messageModel); return(validatorResult); }
private void AddMessages(IEnumerable <ResolvedMessagesSet> messages) { foreach (var message in messages) { if (message.MessageAttribute == null) { continue; } var attribute = message.MessageAttribute; if (!attribute.Server) { // Only cache parsable messages. _parsableMessages.Add(attribute.Id, message.Type); } // Cache attributes _messageAttributes.Add(message.Type, attribute); var validator = new MessageValidator(message.Type); _validators.Add(message.Type, validator); foreach (var parameter in validator.Parameters) { // is nested parameter if (!_nestedValidators.ContainsKey(parameter.ParameterType) && parameter.ParameterType.GetInterfaces().Contains(typeof(IMessage))) { _nestedValidators.Add(parameter.ParameterType, new MessageValidator(parameter.ParameterType)); } } } }
static TestContextValidator() { validatorScanResults = new(); TestingValidatorTypeCache typeCache = new(validatorScanResults); validator = new(typeCache); }
public async Task SendMessageInRoom(ChatMessageReadDto message, string accessToken, string roomId) { var roomConnections = await _inMemoryDb.GetConnectionsOfRoom(roomId); // means we cant send message to room where a user doesn't belong if (!ClientBelongsToThisRoom(roomConnections, Context.ConnectionId)) { return; } var isValidMessage = MessageValidator.ValidateMessage(message.Text); if (!isValidMessage) { await Clients.Caller.SendAsync("error", "message didn't pass validation"); return; } var user = await _accountService.GetProfileFromTokenSpotify(accessToken); if (user != null) { message.Sender = user.SpotifyId; var connectionsInRoom = await _inMemoryDb.GetConnectionsOfRoom(roomId); if (connectionsInRoom != null) { Task.WaitAll(new Task[] { Clients.Group($"{roomId}#host").SendAsync("chat-message", message, user.SpotifyId), Clients.Group($"{roomId}#listeners").SendAsync("chat-message", message, user.SpotifyId) }); } } }
public void MessageValidatorFormatsMessageIdBeforeCaching() { var messageValidator = new MessageValidator(); var messageId = Guid.NewGuid().ToString(); messageValidator.AddMessageIdToCache(messageId); Assert.IsTrue(!messageValidator.Cache.First().Contains("-")); }
public void ValidateText_Tweet_BodyTextLenghtBiggerThan140_ShouldThrowError() { List <string> fields = new List <string>() { "@david", "\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\"" }; Assert.ThrowsException <System.Exception>(() => MessageValidator.ValidateText(fields, 1, 140)); }
/// <summary> /// Creates a message sender. /// </summary> /// <param name="serverAddress">The address of server that messages will be send to.</param> public MessageSender(IPEndPoint serverAddress) { _servers = new List<ServerInfo>(); _tcpClient = new TcpClient(serverAddress); var validator = new MessageValidator(); var serializer = new MessageSerializer(); _marshaller = new Marshaller(serializer, validator); }
public void ValidateText_Email_SIR_BodyTextLenghtBiggerThan1028_ShouldThrowError() { List <string> fields = new List <string>() { "*****@*****.**", "SIR 02/07/1995", "99-99-99", "Theft", "\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequatLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\"" }; Assert.ThrowsException <System.Exception>(() => MessageValidator.ValidateText(fields, 4, 1028)); }
public void ValidateText_Email_SIR_BodyTextLenghtSmallerEqualThan1028_ShouldPass() { List <string> fields = new List <string>() { "*****@*****.**", "SIR 02/07/1995", "99-99-99", "Theft", "\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.\"" }; Assert.AreEqual(fields[4], MessageValidator.ValidateText(fields, 4, 1028)); }
public void ValidateText_Tweet_BodyTextLenghtSmallerEqualThan140_ShouldPass() { List <string> fields = new List <string>() { "@david", "hello" }; Assert.AreEqual(fields[1], MessageValidator.ValidateText(fields, 1, 140)); }
public void WBDSD_HierarchicalCodeList() { // load the DSD string dsdPath = Utility.GetPath("lib\\DSD_WB.xml"); var dsd = StructureMessage.Load(dsdPath); // create hierarchical code list and add it to the DSD var hlist = new HierarchicalCodeList("MDG_Regions", "MDG"); hlist.Name["en"] = "MDG Regions"; dsd.HierarchicalCodeLists.Add(hlist); // get REF_AREA code list from the DSD and add it to the hierarchical code list var refAreaCodeList = dsd.CodeLists.Where(codeList => codeList.Id == "CL_REF_AREA_MDG").Single(); hlist.AddCodeList(refAreaCodeList, "REF_AREA_MDG"); // get parent country code var MDG_DEVELOPED = refAreaCodeList.Where(code => code.Id == "MDG_DEVELOPED").Single(); // child country codes string[] ids = new[] { "ALB", "AND", "AUS", "AUT", "BEL", "BIH", "BMU", "BGR", "HRV", "CAN", "CZE", "DNK", "EST", "FRO", "FIN", "FRA", "DEU", "GRC", "HUN", "ISL", "IRL", "ITA", "JPN", "LVA", "LIE", "LTU", "LUX", "MKD", "MLT", "MCO", "MNE", "NLD", "NZL", "NOR", "POL", "PRT", "ROU", "SVK", "SMR", "SVN", "SRB", "ESP", "SWE", "CHE", "GBR", "USA" }; var countryCodes = (from c in refAreaCodeList join cid in ids on c.Id.ToString() equals cid select c).ToList(); // create hirarchy with parent code and child code and add it to // the hierarchical code list var hierarchy = new Hierarchy("Developed_Countries", new CodeRef(MDG_DEVELOPED, countryCodes)); hierarchy.Name["en"] = "Developed Countries"; hlist.Add(hierarchy); // create another hierarchy and add it to the hierarchical code list var MDG_NAFR = refAreaCodeList.Where(code => code.Id == "MDG_NAFR").Single(); ids = new[] { "DZA", "EGY", "LBY", "MAR", "TUN" }; countryCodes = (from c in refAreaCodeList join cid in ids on c.Id.ToString() equals cid select c).ToList(); hierarchy = new Hierarchy("MDG_NAFR", new CodeRef(MDG_NAFR, () => countryCodes)); hierarchy.Name["en"] = "MDG Northern Africa Countries"; hlist.Add(hierarchy); // save the DSD dsd.Save(Utility.GetPath("lib\\DSD_WB2.xml")); string messageText = dsd.ToString(); var doc = XDocument.Parse(messageText); using (var reader = doc.CreateReader()) Assert.IsTrue(MessageValidator.ValidateXml(reader)); }
public QueueFunction( IPipe pipe, MessageDeserializer messageDeserializer, MessageValidator messageValidator) { _pipe = pipe; _messageDeserializer = messageDeserializer; _messageValidator = messageValidator; }
public void ValidateSender_Tweet_BodySenderCorrect_ShouldPass() { List <string> fields = new List <string>() { "@david" }; string senderRegex = @"^\@[a-zA-Z0-9_]{1,15}$"; Assert.AreEqual(fields[0], MessageValidator.ValidateSender(fields, senderRegex)); }
public void ValidateSender_Tweet_BodySenderLengthMax15_ShouldThrowError() { List <string> fields = new List <string>() { "@1234567890123456" }; string senderRegex = @"^\@[a-zA-Z0-9_]{1,15}$"; Assert.ThrowsException <System.Exception>(() => MessageValidator.ValidateSender(fields, senderRegex)); }
public void Part1(string filename, int rule, int end, long expected) { var parser = new Parser(filename); var lines = parser.Parse(new MessageFactory()) .Where(c => c != null); var sut = new MessageValidator(lines.FirstOrDefault()); var actual = sut.Validate(rule, end); Assert.Equal(expected, actual); }
public void ValidateSender_Tweet_BodySenderNotInTweetIdForm_ShouldThrowError() { List <string> fields = new List <string>() { "david" }; string senderRegex = @"^\@[a-zA-Z0-9_]{1,15}$"; Assert.ThrowsException <System.Exception>(() => MessageValidator.ValidateSender(fields, senderRegex)); }
public void ValidateSender_Email_BodySenderCorrect_ShouldPass() { List <string> fields = new List <string>() { "*****@*****.**" }; string senderRegex = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z"; Assert.AreEqual(fields[0], MessageValidator.ValidateSender(fields, senderRegex)); }
/// <summary> /// Creates a message sender. /// </summary> /// <param name="serverAddress">The address of server that messages will be send to.</param> public MessageSender(IPEndPoint serverAddress) { _servers = new List <ServerInfo>(); _tcpClient = new TcpClient(serverAddress); var validator = new MessageValidator(); var serializer = new MessageSerializer(); _marshaller = new Marshaller(serializer, validator); }
public void ValidateSender_Email_BodySenderNotEmailFormat_ShouldThrowError() { List <string> fields = new List <string>() { "david@" }; string senderRegex = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z"; Assert.ThrowsException <System.Exception>(() => MessageValidator.ValidateSender(fields, senderRegex)); }
public void SkipValidationWhenMessagesNotReceivedYet() { // arrange var validator = new MessageValidator(); // act & assert var message = new Message(2000, "test-message"); // some large message ID Assert.IsType <SuccessValidationResult>(validator.Validate(message)); }
public void DuplicitMessageReceived() { // arrange var validator = new MessageValidator(); var message1 = new Message(1, "test-message"); // act & assert Assert.IsType <SuccessValidationResult>(validator.Validate(message1)); Assert.IsType <AlreadyProcessedValidationResult>(validator.Validate(message1)); }
public static void WaitForRecharging(StreamMessage streamMessage, ClientRobot robot) { robot.TcpClient.ReceiveTimeout = Constants.TIMEOUT_RECHARGING; streamMessage.ReadMessage("Accepted Full charged", MaxLenths.FullPower); if (!MessageValidator.ValidFullPower(streamMessage)) { MessageService.SendLogicError(streamMessage, robot); } robot.TcpClient.ReceiveTimeout = Constants.TIMEOUT; }
public MessageProcessorTests() { var serializer = new MessageSerializer(); var validator = new MessageValidator(); _marshaller = new Marshaller(serializer, validator); _overseer = new ComponentOverseer(5, 1); _workManager = new WorkManager(_overseer); _processor = new MessageProcessor(_overseer, _workManager); }
public AddMessageViewModel(INavigation navigation) { System.Diagnostics.Debug.WriteLine("=================================="); System.Diagnostics.Debug.Flush(); DateTime date = DateTime.Now; var test = date.ToString("yyyy-MM-dd H:mm:ss.fffffffzzz"); System.Diagnostics.Debug.WriteLine("AddMessageViewModel() constructor -1- start - timestamp: " + test); System.Diagnostics.Debug.Flush(); _navigation = navigation; _message = new MessageInfo(); GetDBConnection dbConnection = new GetDBConnection(); if (dbConnection == null || dbConnection.Connection == null) { string errMsg = dbConnection.ConnException.Message; App.DatabaseError("AddMessageViewModel() constructor", errMsg); return; } else { string textPointer = "pointer is null"; if (dbConnection.Connection != null) { if (dbConnection.Connection.Handle == null) { textPointer = "handle is null"; } else { textPointer = dbConnection.Connection.Handle.ptr.ToString(); } } System.Diagnostics.Debug.WriteLine("AddMessageViewModel() constructor -2- sqlite connection: " + textPointer); } _repository = new Repository(dbConnection.Connection); ContactList = _repository.GetAllContactsData(); IList <int> foreignKeys = _repository.GetAllContactKeys(); _messageValidator = new MessageValidator(foreignKeys); AddMessageCommand = new Command(async() => await AddMessage()); test = date.ToString("yyyy-MM-dd H:mm:ss.fffffffzzz"); System.Diagnostics.Debug.WriteLine("AddMessageViewModel() constructor -3- end - timestamp: " + test); System.Diagnostics.Debug.WriteLine("=================================="); System.Diagnostics.Debug.Flush(); }
public AcceptanceTests() { _messages = new InMemoryMessageReader(); _output = new InMemoryValidationOutput(); _validators = new InMemoryValidationSource(); var converter = new DirectMessageConverter(); var validator = new MessageValidator(_validators); _queueMonitor = new QueueMonitor(_messages, converter, validator, _output); _queueMonitor.Start(); }
/// <summary> /// Creates MessageProcessor instance. /// </summary> /// <param name="componentOverseer">Component overseer module.</param> /// <param name="workManager">Work manager to get work from.</param> public MessageProcessor(IComponentOverseer componentOverseer, IWorkManager workManager) { if (componentOverseer == null) throw new ArgumentNullException("IComponentOverseer dependancy is null."); if (workManager == null) throw new ArgumentNullException("IWorkManager dependancy is null."); _inputDataQueue = new RawDataQueue(); var serializer = new MessageSerializer(); var validator = new MessageValidator(); _marshaller = new Marshaller(serializer, validator); _componentOverseer = componentOverseer; _workManager = workManager; _processingLock = new AutoResetEvent(false); }