new public static void Handle(string data, Connection connection)
        {
            List <Message> messages = MessageService.GetMessagesAdressedTo(connection.ConnectedUser.Name);

            try
            {
                foreach (Message messageToSend in messages)
                {
                    Package.Write(
                        connection.TcpClient.GetStream(),
                        RequestConverter.ComposeMessage(messageToSend));
                }
                //Thread.Sleep(10);
                //Package.Write(
                //    connection.TcpClient.GetStream(),
                //    RequestConverter.ComposeGetAllMessagesResponse());
            }
            catch (Exception ex)
            {
                if (ex is NullReferenceException || ex is InvalidOperationException)
                {
                    Console.WriteLine(ex);
                }
                else
                {
                    throw;
                }
            }
        }
        new public static void Handle(string data, Connection connection)
        {
            Message message = MessageService.GetMessageById(RequestConverter.DecomposeMessageReceived(data));

            message.State |= MessageState.ReceiverReceived;

            MessageService.CheckAndHandleMessageState(message);
        }
Exemple #3
0
 public RequestController(IRequestAppService requestAppService
                          , RequestConverter requestConverter
                          , ILogger <RequestController> logger)
 {
     _requestAppService = requestAppService;
     _requestConverter  = requestConverter;
     _logger            = logger;
 }
        new public static void Handle(string data, Connection connection)
        {
            User user = RequestConverter.DecomposeLogin(data);

            User userFromDb = UserService.FindUser(user?.Name);

            connection.ConnectedUser = userFromDb;

            Package.Write(connection.TcpClient.GetStream(),
                          RequestConverter.ComposeLoginResponse(user.Equals(userFromDb)));
        }
Exemple #5
0
        public ActionResult List()
        {
            try
            {
                w2uiGridJsonPostModel postModel = null;
                try
                {
                    postModel = RequestConverter.FromJsonRequest <w2uiGridJsonPostModel>(Request.Body);
                }
                catch (Exception ex)
                {
                    return(Json(w2uiBaseModel.Error(ex)));
                }

                var search      = postModel.search != null ? postModel.search[0].value : "";
                var searchField = postModel.search != null ? postModel.search[0].field : "Title";
                var searchType  = postModel.search != null ? postModel.search[0].type : "text";

                var sortdir   = postModel.sort != null ? postModel.sort[0].direction : "asc";
                var sortfield = postModel.sort != null ? postModel.sort[0].field : "Title";

                SearchOptions options =
                    new SearchOptions(sortfield, searchField, searchType)
                    .Limit(postModel.offset, postModel.limit)
                    .Sort(sortdir)
                    .Search(search);

                w2uiGridModel <GroupAPI> model = new w2uiGridModel <GroupAPI>();


                var allGroups = _db
                                .Groups
                                .ApplyFilterByType(options);

                model.records = allGroups
                                .ApplyPaging(options)
                                .Select(el => new GroupAPI
                {
                    Id        = el.Id,
                    Title     = el.Title,
                    UserCount = _db.UserInGroups.Where(g => g.GroupId == el.Id).Count()
                })
                                .ToList();

                model.total = allGroups.Count();

                return(Json(model));
            }
            catch (Exception ex)
            {
                return(Json(w2uiBaseModel.Error(ex)));
            }
        }
Exemple #6
0
        public void Should_return_request_with_correct_merged_url_with_path_segments_deduplication(string replicaUrl, string requestUrl, string expectedUrl)
        {
            converter = new RequestConverter(new ConsoleLog(), true);

            var convertedRequest = converter.TryConvertToAbsolute(Request.Get(requestUrl), new Uri(replicaUrl));

            convertedRequest.Should().NotBeNull();

            convertedRequest.Url.IsAbsoluteUri.Should().BeTrue();

            convertedRequest.Url.OriginalString.Should().Be(expectedUrl);
        }
        public static IList <IRequestModule> BuildChain(IClusterClientConfiguration config, IReplicaStorageProvider storageProvider)
        {
            var responseClassifier   = new ResponseClassifier();
            var requestConverter     = new RequestConverter(config.Log);
            var requestSender        = new RequestSender(config, storageProvider, responseClassifier, requestConverter, config.Transport);
            var resultStatusSelector = new ClusterResultStatusSelector();

            var modules = new List <IRequestModule>(15 + config.Modules?.Count ?? 0)
            {
                new ErrorCatchingModule(),
                new RequestTransformationModule(config.RequestTransforms),
                new OperationNameFallbackModule(),
                new RequestPriorityApplicationModule()
            };

            if (config.Modules != null)
            {
                modules.AddRange(config.Modules);
            }

            if (config.EnableTracing)
            {
                modules.Add(new TracingModule(config.ServiceName));
            }

            modules.Add(new LoggingModule(config.LogRequestDetails, config.LogResultDetails));
            modules.Add(new ResponseTransformationModule(config.ResponseTransforms));
            modules.Add(new ErrorCatchingModule());
            modules.Add(new RequestValidationModule());
            modules.Add(new TimeoutValidationModule());
            modules.Add(new RequestRetryModule(config.RetryPolicy, config.RetryStrategy));

            if (config.AdaptiveThrottling != null)
            {
                modules.Add(new AdaptiveThrottlingModule(config.AdaptiveThrottling));
            }

            if (config.ReplicaBudgeting != null)
            {
                modules.Add(new ReplicaBudgetingModule(config.ReplicaBudgeting));
            }

            modules.Add(new AbsoluteUrlSenderModule(config.Transport, responseClassifier, config.ResponseCriteria, resultStatusSelector));
            modules.Add(new RequestExecutionModule(config.ClusterProvider, config.ReplicaOrdering, config.ResponseSelector,
                                                   storageProvider, requestSender, resultStatusSelector));

            return(modules);
        }
        public void StartSession()
        {
            string receivedPackage;

            NetworkStream networkStream = null;

            try
            {
                Console.WriteLine("new client");

                networkStream = TcpClient.GetStream();

                while (true)
                {
                    receivedPackage = Package.Read(networkStream);
                    RequestType type;
                    type = RequestConverter.GetRequestType(receivedPackage);
                    Console.WriteLine(type);
                    Type selectedController = GetControllerByRequestType(type);

                    selectedController.GetMethod(nameof(BaseController.Handle))
                    .Invoke(null, new object[] { RequestConverter.GetData(receivedPackage), this });
                }
            }
            catch (IOException ioEx)
            {
                Console.WriteLine(ioEx.Message);
            }
            catch (FormatException foEx)
            {
                Console.WriteLine(foEx.Message);
            }
            catch (ControllerNotFoundExeption contrNotFound)
            {
                Console.WriteLine(contrNotFound.Message);
            }
            finally
            {
                networkStream?.Close();
                TcpClient?.Close();

                Connection connection = this;
                ConnectionController.Connections.TryTake(out connection);
            }
        }
        public IActionResult PutDeliveryFile(
            [RequestBodyType(typeof(DeliveryFileUpdateRequestDto), "配信ファイル更新リクエスト")]
            [HttpTrigger(AuthorizationLevel.Function, "put", Route = "deliveryfiles/{deliveryFileId}")]
            DeliveryFileUpdateRequestDto request,
            long deliveryFileId,
            ILogger log)
        {
            log.EnterJson($"{nameof(deliveryFileId)}: {deliveryFileId}, {typeof(DeliveryFileUpdateRequestDto)}: {{0}}", request);
            ActionResult response = null;

            try
            {
                DeliveryFileUpdateRequestDto requestByType = RequestConverter.Convert(request);    // リクエストオブジェクトがnullの場合にはnullが返る
                // リクエストパラメータチェック
                if (RequestValidator.IsBadRequestParameter(request, out string message))
                {
                    log.Error(nameof(Resources.CO_API_DFU_002), new object[] { message });
                    return(new BadRequestObjectResult(string.Empty));
                }

                var utilParam   = requestByType.ConvertDtoToUtility(deliveryFileId);
                var resultParam = _service.Update(utilParam);

                // Resultから返却ステータスを作成
                response = SqlResultConverter.ConvertToActionResult(
                    resultParam.ResultCode,
                    resultParam.Message,
                    resultParam.Entity.ConvertUtilityToResponseDto());
            }
            catch (Exception e)
            {
                log.Error(e, nameof(Resources.CO_API_DFU_001));
                response = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }
            finally
            {
                log.LeaveJson("Response: {0}", response);
            }

            return(response);
        }
        public void SyncMessage(MessageSyncInfo messageSyncInfo)
        {
            LocalMessage message = LocalMessageRepository
                                   .GetMessageByLocalIdAndSenderName(messageSyncInfo.LocalId, messageSyncInfo.SenderName);

            if (message is null)
            {
                return;
            }

            message.Id         = messageSyncInfo.Id;
            message.SendedTime = messageSyncInfo.NewDateTime;
            SaveAndShowMessage(message);

            RequestToHideMessage(
                LocalMessageRepository.GetMessageByLocalIdAndSenderName(message.LocalId, message.Sender));
            LocalMessageRepository.RemoveMessageByLocalIdIfWithoutId(message.LocalId);

            ServerConnectionHandler.RequestsToSend.Add(
                RequestConverter.ComposeMessageSynchronised(message.Id));
        }
        new public static void Handle(string data, Connection connection)
        {
            Message message = RequestConverter.DecomposeMessage(data);

            message.SendedTime = DateTime.UtcNow;

            try
            {
                MessageService.SaveMessageIfLocalIdUnique(message);
                message = MessageService.GetMessageById(message.Id);

                Package.Write(
                    connection.TcpClient.GetStream(),
                    RequestConverter.ComposeMessageSyncInfo(message.Id, message.SenderLocalId, message.SendedTime));

                Connection receiverConnection = ConnectionController.Connections
                                                .FirstOrDefault(c => c.ConnectedUser.Name == message.Receiver);

                if (!(receiverConnection is null))
                {
                    Package.Write(
                        receiverConnection.TcpClient.GetStream(),
                        RequestConverter.ComposeMessage(message));
                }
            }
            catch (Exception ex)
            {
                if (ex is NullReferenceException || ex is InvalidOperationException)
                {
                    //MessageService.SaveMessage(message);

                    // here i got exception; i must correct it;
                    //else
                    //throw;

                    Console.WriteLine(ex.Message);
                }
            }
        }
        new public static void Handle(string data, Connection connection)
        {
            string userToFind = RequestConverter.DecomposeUserExist(data);
            User   user       = UserService.FindUser(userToFind);

            try
            {
                Package.Write(connection.TcpClient.GetStream(),
                              RequestConverter.ComposeUserExistResponse(!(user is null)));
            }
            catch (Exception ex)
            {
                if (ex is NullReferenceException || ex is InvalidOperationException)
                {
                    Console.WriteLine(ex);
                }
                else
                {
                    throw;
                }
            }
        }
 public void SendGetAllMessages()
 {
     ServerConnectionHandler.RequestsToSend.Add(RequestConverter.ComposeGetAllMessages());
 }
 public void SendMessage(LocalMessage message)
 {
     ServerConnectionHandler.RequestsToSend.Add(RequestConverter.ComposeMessage(message.GetMessage()));
 }
        public async void Start()
        {
            await Task.Run(() =>
            {
                try
                {
                    TcpClient        = new TcpClient(Constants.IP, Constants.PORT);
                    NetworkStream ns = TcpClient.GetStream();
                    string buff;

                    while (true)
                    {
                        while (ns.DataAvailable)
                        {
                            string receivedPackage = Package.Read(ns);

                            RequestType type = RequestConverter.GetRequestType(receivedPackage);
                            string data      = RequestConverter.GetData(receivedPackage);
                            switch (type)
                            {
                            case RequestType.LoginResponse:
                                userHandler.Found = RequestConverter.DecomposeLoginResponse(data);
                                break;

                            case RequestType.RegistrationResponse:
                                userHandler.Found = RequestConverter.DecomposeLoginResponse(data);
                                break;

                            case RequestType.SendMessage:
                                Message message = RequestConverter.DecomposeMessage(data);
                                messageHandler.SaveAndShowMessage(new LocalMessage(message));
                                Package.Write(ns, RequestConverter.ComposeMessageReceived(message.Id));
                                break;

                            case RequestType.CheckUserExistResponse:
                                userHandler.ReceiverFound = RequestConverter.DecomposeUserExistResponse(data);
                                break;

                            case RequestType.MessageSyncInfo:
                                messageHandler.SyncMessage(RequestConverter.DecomposeMessageSyncInfo(data));
                                break;

                            default:
                                break;
                            }
                        }

                        while (!RequestsToSend.IsEmpty)
                        {
                            RequestsToSend.TryTake(out buff);
                            Package.Write(ns, buff);
                        }

                        Thread.Sleep(5);
                    }
                }
                catch (IOException ioEx)
                {
                    Console.WriteLine(ioEx.Message);
                }
                finally
                {
                    TcpClient?.GetStream().Close();
                    TcpClient?.Close();
                }
            });
        }
Exemple #16
0
        public static IList <IRequestModule> BuildChain(IClusterClientConfiguration config, IReplicaStorageProvider storageProvider)
        {
            var responseClassifier   = new ResponseClassifier();
            var requestConverter     = new RequestConverter(config.Log, config.DeduplicateRequestUrl);
            var requestSender        = new RequestSender(config, storageProvider, responseClassifier, requestConverter);
            var resultStatusSelector = new ClusterResultStatusSelector();

            // ReSharper disable once UseObjectOrCollectionInitializer
            var modules = new List <IRequestModule>(12 + config.Modules?.Sum(x => x.Value.Count) ?? 0);

            var addedModules = new HashSet <Type>();

            AddModule(new LeakPreventionModule());
            AddModule(new GlobalErrorCatchingModule());
            AddModule(new RequestTransformationModule(config.RequestTransforms));
            AddModule(new AuxiliaryHeadersModule());

            // -->> user-defined modules by default inserted here <<-- //

            AddModule(new LoggingModule(config.Logging.LogRequestDetails, config.Logging.LogResultDetails, config.TargetServiceName));
            AddModule(new ResponseTransformationModule(config.ResponseTransforms));
            AddModule(new ErrorCatchingModule());
            AddModule(new RequestValidationModule());

            AddModule(new TimeoutValidationModule());
            AddModule(new RequestRetryModule(config.RetryPolicy, config.RetryStrategyEx));

            // -->> adaptive throttling module <<-- //

            AddModule(new AbsoluteUrlSenderModule(responseClassifier, config.ResponseCriteria, resultStatusSelector));

            // -->> replica budgeting module <<-- //

            // -->> service-mesh module is injected before RequestExecutionModule <<-- //

            AddModule(
                new RequestExecutionModule(
                    config.ResponseSelector,
                    storageProvider,
                    requestSender,
                    resultStatusSelector));

            return(modules);

            void AddModules(IEnumerable <IRequestModule> modulesRange)
            {
                if (modulesRange == null)
                {
                    return;
                }

                foreach (var module in modulesRange)
                {
                    AddModule(module);
                }
            }

            void AddModule(IRequestModule module)
            {
                if (config.ModulesToRemove.Contains(module.GetType()))
                {
                    return;
                }

                var moduleType = module.GetType();

                var isNewModule = addedModules.Add(moduleType);

                if (!isNewModule || config.Modules == null)
                {
                    modules.Add(module);
                    return;
                }

                var relatedModules = config.Modules.TryGetValue(moduleType, out var v) ? v : null;

                AddModules(relatedModules?.Before);
                modules.Add(module);
                AddModules(relatedModules?.After);
            }
        }
 public void SetUp()
 {
     converter = new RequestConverter(new ConsoleLog());
 }
        public ActionResult List()
        {
            try
            {
                w2uiGridJsonPostModel postModel = null;
                try
                {
                    postModel = RequestConverter.FromJsonRequest <w2uiGridJsonPostModel>(Request.Body);
                }
                catch (Exception ex)
                {
                    return(Json(w2uiBaseModel.Error(ex)));
                }

                var search      = "";
                var searchField = "Id";
                var searchType  = "int";
                var sortdir     = "asc";
                var sortfield   = "LastName";

                var specialFilters = new List <string>()
                {
                    "gender", "group"
                };
                var genderFilter = false;
                var groupFilter  = false;
                var specVal      = "";

                if (postModel.search != null)
                {
                    var s = postModel.search[0];

                    if (!specialFilters.Contains(s.field))
                    {
                        search      = s.value;
                        searchField = s.field;
                        searchType  = s.type;
                    }
                    else
                    {
                        specVal      = s.value;
                        genderFilter = s.field == "gender";
                        groupFilter  = s.field == "group";
                    }
                }

                if (postModel.sort != null)
                {
                    sortdir   = postModel.sort[0].direction;
                    sortfield = postModel.sort[0].field;
                }

                SearchOptions options = null;

                if (searchField != "groups")
                {
                    options =
                        new SearchOptions(sortfield, searchField, searchType)
                        .Limit(postModel.offset, postModel.limit)
                        .Sort(sortdir)
                        .Search(search);
                }
                else
                {
                    options =
                        new SearchOptions(sortfield, searchField, searchType)
                        .Limit(postModel.offset, postModel.limit)
                        .Sort(sortdir);
                }

                w2uiGridModel <StudentAPI> model = new w2uiGridModel <StudentAPI>();


                var allStudents = _db.Students
                                  .Where(el => genderFilter == false || el.Gender.Title == specVal)
                                  .Where(el => groupFilter == false || el.UserInGroups.Select(gr => gr.Group).Where(gr => gr.Title == specVal).Any())
                                  .ApplyFilterByType(options);

                model.records = allStudents
                                .ApplyPaging(options)
                                .Select(el => new StudentAPI
                {
                    CallSign  = el.CallSign,
                    FirstName = el.FirstName,
                    Gender    = el.Gender,
                    GenderId  = el.GenderId,
                    Groups    = _db.UserInGroups
                                .Where(g => g.UserId == el.Id)
                                .Select(g => new IdText {
                        id = g.Id, text = g.Group.Title
                    })
                                .ToList(),
                    Id           = el.Id,
                    LastName     = el.LastName,
                    SecondName   = el.SecondName,
                    UserInGroups = el.UserInGroups
                })
                                .ToList();

                model.total = allStudents.Count();

                return(Json(model));
            }
            catch (Exception ex)
            {
                return(Json(w2uiBaseModel.Error(ex)));
            }
        }
Exemple #19
0
 public void TestSetup()
 {
     converter = new RequestConverter(new ConsoleLog(), false);
 }