Exemple #1
0
        /// <summary>
        /// Создавет ответ на ошибку.
        /// </summary>
        /// <param name="serializer">Текущие сериалайзер.</param>
        /// <param name="message">Сообщение об ошибке.</param>
        /// <returns>Ответ.</returns>
        private string CreateErrorResponse(ProtocolSerializer serializer, string message)
        {
            var error = new ErrorResponse();

            error.Description = message;
            return(serializer.Serialize(error));
        }
Exemple #2
0
        /// <summary>
        /// Осуществляет отправку данных на сервер и получение ответа.
        /// </summary>
        /// <typeparam name="TResponse">Ответ.</typeparam>
        /// <param name="serializeFunct">Вызов функции сериализации..</param>
        /// <param name="deserializeFunct">Вызов функции десериализации.</param>
        /// <returns>Полученный ответ.</returns>
        private TResponse SendData <TResponse>(Func <ProtocolSerializer, string> serializeFunct, Func <string, ProtocolSerializer, TResponse> deserializeFunct)
            where TResponse : MessageBase
        {
            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);

            var rawRequest = serializeFunct(serializer);

            var rawResponse = SendRawXml(rawRequest);

            var info = serializer.GetMessageInfoOrNull(rawResponse);

            if (info == null)
            {
                throw new Exception("Нет ответа от сервера");
            } //if

            if (info.Kind == MessageKind.ErrorResponse)
            {
                var err = serializer.DeserializeErrorResponse(rawResponse);
                throw new ResponseErrorException(err.Description);
            } //if

            if (info.Kind == MessageKind.AuthErrorResponse)
            {
                var err = serializer.DeserializeAuthErrorResponse(rawResponse);
                throw new ResponseErrorException(err.Message);
            } //if

            return(deserializeFunct(rawResponse, serializer));
        }
Exemple #3
0
        /// <summary>
        /// Обработчик запроса на получение пользовательских отчетов.
        /// </summary>
        /// <param name="serializer">Сериализатор протокола.</param>
        /// <param name="postData">Данные запроса.</param>
        /// <param name="hostAddress">Адрес клиента.</param>
        /// <returns>Результат.</returns>
        private string ProcessGetCustomReportItemRequest(ProtocolSerializer serializer, string postData, string hostAddress)
        {
            var request = serializer.DeserializeGetCustomReportItemRequest(postData);

            _logger.InfoFormat(
                "Получен запрос на получение информации по пользовательским отчетам от пользователя {0} с клиента {1}",
                request.UserID, hostAddress);

            var userDomainID = CheckSignedMessage(request);

            var items    = RemontinkaServer.Instance.DataStore.GetCustomReportItems(userDomainID);
            var response = new GetCustomReportItemResponse();

            foreach (var reportItem in items)
            {
                response.CustomReportItems.Add(new CustomReportItemDTO
                {
                    CustomReportID = reportItem.CustomReportID,
                    HtmlContent    = reportItem.HtmlContent,
                    Title          = reportItem.Title,
                    DocumentKindID = reportItem.DocumentKindID
                });
            } //foreach

            return(serializer.Serialize(response));
        }
Exemple #4
0
 private LocalObserver(
     ProtocolSerializer serializer,
     [Parameter(typeof(MessageObserver))] IInjectionFuture <object> fMessageObserver)
 {
     _serializer       = serializer;
     _fMessageObserver = fMessageObserver;
 }
Exemple #5
0
        public void GetRepairOrdersRequestTest()
        {
            var message = new GetRepairOrdersRequest();

            Assert.AreEqual(message.Kind, MessageKind.GetRepairOrdersRequest);

            message.UserID = Guid.NewGuid();
            message.RepairOrderIds.Add(Guid.NewGuid());
            message.RepairOrderIds.Add(Guid.NewGuid());
            message.RepairOrderIds.Add(Guid.NewGuid());

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetRepairOrdersRequest);

            var savedMessage = serializer.DeserializeGetRepairOrdersRequest(data);

            Assert.IsNotNull(savedMessage);

            Assert.AreEqual(message.Kind, savedMessage.Kind);
            Assert.AreEqual(message.UserID, savedMessage.UserID);
            Assert.AreEqual(message.RepairOrderIds.Count, savedMessage.RepairOrderIds.Count);
            Assert.AreEqual(message.RepairOrderIds[0], savedMessage.RepairOrderIds[0]);
            Assert.AreEqual(message.RepairOrderIds[1], savedMessage.RepairOrderIds[1]);
            Assert.AreEqual(message.RepairOrderIds[2], savedMessage.RepairOrderIds[2]);
        }
Exemple #6
0
        /// <summary>
        /// Обработчик запроса на получение остатков на складах.
        /// </summary>
        /// <param name="serializer">Сериализатор протокола.</param>
        /// <param name="postData">Данные запроса.</param>
        /// <param name="hostAddress">Адрес клиента.</param>
        /// <returns>Результат.</returns>
        private string ProcessGetWarehouseItemsRequest(ProtocolSerializer serializer, string postData, string hostAddress)
        {
            var request = serializer.DeserializeGetWarehouseItemsRequest(postData);

            _logger.InfoFormat(
                "Получен запрос на получение информации остаткам на складах от пользователя {0} с клиента {1}",
                request.UserID, hostAddress);

            var userDomainID = CheckSignedMessage(request);

            var warehouseItems = RemontinkaServer.Instance.DataStore.GetWarehouseItems(userDomainID);
            var response       = new GetWarehouseItemsResponse();

            foreach (var warehouse in warehouseItems)
            {
                response.WarehouseItems.Add(new Protocol.SynchronizationMessages.WarehouseItemDTO
                {
                    WarehouseID     = warehouse.WarehouseID,
                    GoodsItemID     = warehouse.WarehouseID,
                    RepairPrice     = warehouse.RepairPrice,
                    SalePrice       = warehouse.SalePrice,
                    StartPrice      = warehouse.StartPrice,
                    Total           = warehouse.StartPrice,
                    WarehouseItemID = warehouse.WarehouseItemID
                });
            } //foreach

            return(serializer.Serialize(response));
        }
Exemple #7
0
        public void ProbeKeyActivationResponseTest()
        {
            var message = new ProbeKeyActivationResponse();

            Assert.AreEqual(message.Kind, MessageKind.ProbeKeyActivationResponse);

            message.IsExists      = true;
            message.IsExpired     = true;
            message.IsNotAccepted = true;
            message.IsRevoked     = true;

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.ProbeKeyActivationResponse);

            var savedMessage = serializer.DeserializeProbeKeyActivationResponse(data);

            Assert.IsNotNull(savedMessage);

            Assert.AreEqual(message.Kind, savedMessage.Kind);
            Assert.AreEqual(message.IsExists, savedMessage.IsExists);
            Assert.AreEqual(message.IsExpired, savedMessage.IsExpired);
            Assert.AreEqual(message.IsNotAccepted, savedMessage.IsNotAccepted);
            Assert.AreEqual(message.IsRevoked, savedMessage.IsRevoked);
        }
Exemple #8
0
    public static byte[] PackPb()
    {
        var person = new Person();

        person.id   = 1;
        person.name = "My Playground!!!";
        person.tags.AddRange(tags);

        foreach (var log in logs)
        {
            person.logs.Add(new Log
            {
                id      = log.Id,
                content = log.Content,
                status  = log.Status,
                times   = log.Times
            }
                            );
        }

        using (var ms = new MemoryStream())
        {
            var ser = new ProtocolSerializer();
            ser.Serialize(ms, person);
            return(ms.ToArray());
        }
    }
Exemple #9
0
        private NetworkTransport(
            ILocalAddressProvider localAddressProvider,
            ProtocolSerializer serializer,
            LocalObserver localObserver,
            IRemoteManagerFactory remoteManagerFactory,
            REEFFileNames fileNames)
        {
            _serializer = serializer;
            _fileNames  = fileNames;

            // Instantiate the remote manager.
            _remoteManager = remoteManagerFactory.GetInstance(localAddressProvider.LocalAddress, new ByteCodec());

            // Listen to the java bridge on the local end point.
            _remoteManager.RegisterObserver(localObserver);
            Logger.Log(Level.Info, "Local observer listening to java bridge on: [{0}]", _remoteManager.LocalEndpoint);

            // Instantiate a remote observer to send messages to the java bridge.
            IPEndPoint javaIpEndPoint = GetJavaBridgeEndpoint();

            Logger.Log(Level.Info, "Connecting to java bridge on: [{0}]", javaIpEndPoint);
            _remoteObserver = _remoteManager.GetRemoteObserver(javaIpEndPoint);

            // Negotiate the protocol.
            Send(0, new BridgeProtocol(100));
        }
Exemple #10
0
        /// <summary>
        /// Обработчик запроса на получение данных по пользователям домена.
        /// </summary>
        /// <param name="serializer">Сериализатор протокола.</param>
        /// <param name="postData">Данные запроса.</param>
        /// <param name="hostAddress">Адрес клиента.</param>
        /// <returns>Результат.</returns>
        private string ProcessGetDomainUsersRequest(ProtocolSerializer serializer, string postData, string hostAddress)
        {
            var request = serializer.DeserializeGetDomainUsersRequest(postData);

            _logger.InfoFormat(
                "Получен запрос на получение информации по пользователям от пользователя {0} с клиента {1}",
                request.UserID, hostAddress);

            var userDomainID = CheckSignedMessage(request);

            var users    = RemontinkaServer.Instance.DataStore.GetUsers(userDomainID);
            var response = new GetDomainUsersResponse();

            foreach (var user in users)
            {
                response.Users.Add(new DomainUserDTO
                {
                    Email         = user.Email,
                    FirstName     = user.FirstName,
                    LastName      = user.LastName,
                    MiddleName    = user.MiddleName,
                    Phone         = user.Phone,
                    ProjectRoleID = user.ProjectRoleID,
                    UserID        = user.UserID,
                    LoginName     = user.LoginName
                });
            }  //foreach

            return(serializer.Serialize(response));
        }
Exemple #11
0
        public void GetServerRepairOrderHashesResponseTest()
        {
            var message = new GetServerRepairOrderHashesResponse();

            Assert.AreEqual(message.Kind, MessageKind.GetServerRepairOrderHashesResponse);


            message.TotalCount = 55;

            var order = new RepairOrderServerHashDTO();

            order.DataHash            = "HashData111";
            order.OrderTimelinesCount = 112;
            order.RepairOrderID       = Guid.NewGuid();

            var workItem = new WorkItemServerHashDTO();

            workItem.WorkItemID = Guid.NewGuid();
            workItem.DataHash   = "Titl1231231e";

            var deviceItem = new DeviceItemServerHashDTO();

            deviceItem.DeviceItemID = Guid.NewGuid();
            deviceItem.DataHash     = "Tiqsdqw1233123tle";


            order.WorkItems.Add(workItem);
            order.DeviceItems.Add(deviceItem);
            message.RepairOrderServerHashes.Add(order);

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);

            var savedMessage = serializer.DeserializeGetServerRepairOrderHashesResponse(data);

            Assert.IsNotNull(savedMessage);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetServerRepairOrderHashesResponse);
            Assert.AreEqual(savedMessage.RepairOrderServerHashes.Count, 1);
            Assert.AreEqual(savedMessage.RepairOrderServerHashes[0].DeviceItems.Count, 1);
            Assert.AreEqual(savedMessage.RepairOrderServerHashes[0].WorkItems.Count, 1);
            Assert.AreEqual(savedMessage.TotalCount, message.TotalCount);

            var savedDeviceItem = savedMessage.RepairOrderServerHashes[0].DeviceItems[0];
            var savedWorkItem   = savedMessage.RepairOrderServerHashes[0].WorkItems[0];
            var savedOrder      = savedMessage.RepairOrderServerHashes[0];

            Assert.AreEqual(savedOrder.DataHash, order.DataHash);
            Assert.AreEqual(savedOrder.RepairOrderID, order.RepairOrderID);
            Assert.AreEqual(savedOrder.OrderTimelinesCount, order.OrderTimelinesCount);


            Assert.AreEqual(deviceItem.DeviceItemID, savedDeviceItem.DeviceItemID);
            Assert.AreEqual(deviceItem.DataHash, savedDeviceItem.DataHash);

            Assert.AreEqual(savedWorkItem.DataHash, workItem.DataHash);
            Assert.AreEqual(savedWorkItem.WorkItemID, workItem.WorkItemID);
        }
        public static void OnDataReceived(IClientConnection connection, byte[] data)
        {
            try
            {
                ProtocolEncoder encoder = new ProtocolEncoder();

                MediumDeserializedObject requestObject = null;
                try
                {
                    requestObject = ProtocolSerializer.Deserialize(data);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

                string controlCommand = encoder.Decode(requestObject.ControlCommand);

                IList <ArraySegment <byte> > serializedResponse = null;
                Type requestType = _availableRequests.GetRequestType(controlCommand);
                if (requestType != null)
                {
                    try
                    {
                        Type protocolRequestInterface = requestType.GetInterfaces().FirstOrDefault(x => typeof(IProtocolRequest <IProtocolResponse>).IsAssignableFrom(x));
                        Type responseType             = protocolRequestInterface.GenericTypeArguments[0];
                        serializedResponse = (IList <ArraySegment <byte> >)_executeMethod.MakeGenericMethod(requestType, responseType).Invoke(null, new object[] { requestObject.Body });
                    }
                    catch
                    {
                        serializedResponse = SerializeResponse(new ErrorResponse
                        {
                            Code    = 500,
                            Message = "Internal server error."
                        });
                    }
                }
                else
                {
                    serializedResponse = SerializeResponse(new ErrorResponse
                    {
                        Code    = 400,
                        Message = "Unsupported request."
                    });
                }

                connection.Send(serializedResponse);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    public static void UnPackPb()
    {
        var data   = GetData("data.pb");
        var stream = new MemoryStream(data);

        var ser    = new ProtocolSerializer();
        var person = ser.Deserialize(stream, null, typeof(Person)) as Person;

        stream.Close();

        // Console.WriteLine("{0}, {1}, {2}, {3}", person.id, person.name, person.tags.Count, person.logs.Count);
    }
Exemple #14
0
        /// <summary>
        /// Обработчик запроса на получение хэшей заказов.
        /// </summary>
        /// <param name="serializer">Сериализатор протокола.</param>
        /// <param name="postData">Данные запроса.</param>
        /// <param name="hostAddress">Адрес клиента.</param>
        /// <returns>Результат.</returns>
        private string ProcessGetServerRepairOrderHashesRequest(ProtocolSerializer serializer, string postData, string hostAddress)
        {
            var request = serializer.DeserializeGetServerRepairOrderHashesRequest(postData);

            _logger.InfoFormat(
                "Получен запрос на получение информации по хэшам заказов от пользователя {0} с клиента {1}",
                request.UserID, hostAddress);

            var userDomainID = CheckSignedMessage(request);

            var response = new GetServerRepairOrderHashesResponse();

            int total;

            var hashes = RemontinkaServer.Instance.DataStore.GetRepairOrderHashes(userDomainID,
                                                                                  request.LastRepairOrderID, out total).ToList();

            response.TotalCount = total;

            foreach (var repairOrderHash in hashes)
            {
                var item = new RepairOrderServerHashDTO
                {
                    DataHash            = repairOrderHash.DataHash,
                    OrderTimelinesCount = repairOrderHash.OrderTimelinesCount,
                    RepairOrderID       = repairOrderHash.RepairOrderID
                };

                response.RepairOrderServerHashes.Add(item);

                foreach (var deviceItemHash in repairOrderHash.DeviceItemHashes)
                {
                    item.DeviceItems.Add(new DeviceItemServerHashDTO
                    {
                        DeviceItemID = deviceItemHash.DeviceItemID,
                        DataHash     = deviceItemHash.DataHash
                    });
                } //foreach

                foreach (var workItemHash in repairOrderHash.WorkItemHashes)
                {
                    item.WorkItems.Add(new WorkItemServerHashDTO
                    {
                        WorkItemID = workItemHash.WorkItemID,

                        DataHash = workItemHash.DataHash
                    });
                } //foreach
            }     //foreach


            return(serializer.Serialize(response));
        }
Exemple #15
0
        public void GetGoodsItemResponseTest()
        {
            var message = new GetGoodsItemResponse();

            Assert.AreEqual(message.Kind, MessageKind.GetGoodsItemResponse);

            var item = new ItemCategoryDTO();

            item.ItemCategoryID = Guid.NewGuid();
            item.Title          = "Title";

            var goodsItem = new GoodsItemDTO();

            goodsItem.GoodsItemID     = Guid.NewGuid();
            goodsItem.Title           = "Title";
            goodsItem.ItemCategoryID  = item.ItemCategoryID;
            goodsItem.BarCode         = "BarCode";
            goodsItem.Description     = "Description";
            goodsItem.DimensionKindID = 1;
            goodsItem.Particular      = "Particular";
            goodsItem.UserCode        = "UserCode";

            message.GoodsItems.Add(goodsItem);
            message.ItemCategories.Add(item);

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);

            var savedMessage = serializer.DeserializeGetGoodsItemResponse(data);

            Assert.IsNotNull(savedMessage);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetGoodsItemResponse);
            Assert.AreEqual(savedMessage.GoodsItems.Count, 1);
            Assert.AreEqual(savedMessage.ItemCategories.Count, 1);

            var savedGoodsItems = savedMessage.GoodsItems[0];
            var savedItem       = savedMessage.ItemCategories[0];

            Assert.AreEqual(goodsItem.BarCode, savedGoodsItems.BarCode);
            Assert.AreEqual(goodsItem.Title, savedGoodsItems.Title);
            Assert.AreEqual(goodsItem.Description, savedGoodsItems.Description);
            Assert.AreEqual(goodsItem.DimensionKindID, savedGoodsItems.DimensionKindID);
            Assert.AreEqual(goodsItem.GoodsItemID, savedGoodsItems.GoodsItemID);
            Assert.AreEqual(goodsItem.ItemCategoryID, savedGoodsItems.ItemCategoryID);
            Assert.AreEqual(goodsItem.Particular, savedGoodsItems.Particular);
            Assert.AreEqual(goodsItem.UserCode, savedGoodsItems.UserCode);


            Assert.AreEqual(savedItem.ItemCategoryID, item.ItemCategoryID);
            Assert.AreEqual(savedItem.Title, item.Title);
        }
Exemple #16
0
        /// <summary>
        /// Обрабатывает запрос пришедший с арма и передает соответствующим службам.
        /// </summary>
        /// <param name="postData">Данные для обработки.</param>
        /// <param name="hostAddress">Адрес хоста клиента. </param>
        /// <returns>Сформированный ответ.</returns>
        public string ProcessRequest(string postData, string hostAddress)
        {
            var result     = UnknownMethod;
            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);

            var kindInfo = serializer.GetMessageInfoOrNull(postData);

            if (kindInfo == null)
            {
                _logger.ErrorFormat("Получен неизвестный метод с клиента \"{0}\" сообщение = \"{1}\"",
                                    hostAddress, postData);
                return(result);
            } //if

            if (!_methods.ContainsKey(kindInfo.Kind))
            {
                _logger.ErrorFormat("Нет обработчика для метода {0} с клиента \"{1}\" сообщение = \"{2}\"", kindInfo.Kind,
                                    hostAddress, postData);
                return(result);
            } //if

            try
            {
                var method = _methods[kindInfo.Kind];
                result = method(serializer, postData, hostAddress);
            }
            catch (AuthException ex)
            {
                _logger.ErrorFormat(
                    "Во время обработки подписанного запроса с клинета {0}:{1} была получена ошибка [{2} {3} {4}] сообщение \"{5}\"", kindInfo.Kind,
                    hostAddress, ex.Message, ex.GetType(), ex.StackTrace, postData);
                result = serializer.Serialize(new AuthErrorResponse {
                    Message = ex.Message
                });
            }
            catch (Exception ex)
            {
                var inner = string.Empty;
                if (ex.InnerException != null)
                {
                    inner = ex.InnerException.Message;
                }
                _logger.ErrorFormat(
                    "Во время обработки запроса с клинета {0}:{1} была получена ошибка [{2} {3} {4} {5}] сообщение \"{6}\"", kindInfo.Kind,
                    hostAddress, ex.Message, ex.GetType(), ex.StackTrace, inner, postData);
                result = serializer.Serialize(new ErrorResponse {
                    Description = ex.Message
                });
            } //try

            return(result);
        }
        private static IList <ArraySegment <byte> > SerializeResponse <TResponse>(TResponse protocolResponse)
            where TResponse : IProtocolResponse, new()
        {
            ProtocolEncoder encoder = new ProtocolEncoder();

            MessageHeadersDictionary responseHeaders = new MessageHeadersDictionary();

            byte[] identifier     = encoder.Encode(protocolResponse.GetIdentifier());
            byte[] headers        = ProtocolMessageHeaderSerializer.Serialize(responseHeaders);
            byte[] serializedBody = ProtocolBodySerializer.Serialize(protocolResponse);

            return(ProtocolSerializer.Serialize(identifier, headers, serializedBody));
        }
Exemple #18
0
        public void GetUserBranchesResponseTest()
        {
            var message = new GetUserBranchesResponse();

            Assert.AreEqual(message.Kind, MessageKind.GetUserBranchesResponse);
            var branch = new BranchDTO();

            branch.Address   = "Address";
            branch.BranchID  = Guid.NewGuid();
            branch.LegalName = "LegalName";
            branch.Title     = "Title";

            var item = new UserBranchMapItemDTO();

            item.BranchID        = branch.BranchID;
            item.EventDate       = new DateTime(2015, 06, 07);
            item.UserBranchMapID = Guid.Empty;
            item.UserID          = Guid.NewGuid();

            message.Branches.Add(branch);
            message.UserBranchMapItems.Add(item);

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);

            var savedMessage = serializer.DeserializeGetUserBranchesResponse(data);

            Assert.IsNotNull(savedMessage);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetUserBranchesResponse);
            Assert.AreEqual(savedMessage.Branches.Count, 1);
            Assert.AreEqual(savedMessage.UserBranchMapItems.Count, 1);

            var savedBranch = savedMessage.Branches[0];
            var savedItem   = savedMessage.UserBranchMapItems[0];

            Assert.AreEqual(savedBranch.Address, savedBranch.Address);
            Assert.AreEqual(savedBranch.BranchID, savedBranch.BranchID);
            Assert.AreEqual(savedBranch.LegalName, savedBranch.LegalName);
            Assert.AreEqual(savedBranch.Title, savedBranch.Title);


            Assert.AreEqual(savedItem.BranchID, item.BranchID);
            Assert.AreEqual(savedItem.EventDate, item.EventDate);
            Assert.AreEqual(savedItem.UserBranchMapID, item.UserBranchMapID);
            Assert.AreEqual(savedItem.UserID, item.UserID);
        }
Exemple #19
0
        /// <summary>
        /// Обработчик запроса на регистрацию ключей.
        /// </summary>
        /// <param name="serializer">Сериализатор протокола.</param>
        /// <param name="postData">Данные запроса.</param>
        /// <param name="hostAddress">Адрес клиента.</param>
        /// <returns>Результат.</returns>
        private string ProcessRegisterPublicKeyRequest(ProtocolSerializer serializer, string postData, string hostAddress)
        {
            var request = serializer.DeserializeRegisterPublicKeyRequest(postData);

            _logger.InfoFormat("Получен запрос на регистрацию нового ключа для пользователя {0} с клиента {1}",
                               request.UserLogin, hostAddress);
            var entity = new UserPublicKeyRequest();

            var user = RemontinkaServer.Instance.DataStore.GetUser(request.UserLogin);

            if (user == null)
            {
                _logger.ErrorFormat("Нет пользователя для запроса по публичному ключю {0} с клиента {1}", request.UserLogin, hostAddress);

                return(CreateErrorResponse(serializer, "Нет такого пользователя"));
            } //if

            entity.ClientIdentifier = hostAddress;
            entity.KeyNotes         = request.KeyNotes;
            entity.PublicKeyData    = request.PublicKeyData;
            entity.UserID           = user.UserID;
            entity.EventDate        = request.EventDate;

            if (request.ClientUserDomainID != null)
            {
                if (request.ClientUserDomainID != user.UserDomainID)
                {
                    _logger.ErrorFormat("В запросе на регистрацию нового ключа не совпадают домены {0} {1}",
                                        request.ClientUserDomainID, user.UserDomainID);
                    return(CreateErrorResponse(serializer, "Домены не совпадают"));
                } //if
            }     //if

            var number =
                RemontinkaServer.Instance.DataStore.GetNewOrderNumber(user.UserDomainID).ToString(
                    CultureInfo.InvariantCulture);

            entity.Number = string.Format(NewPublicKeyNumberFormat, number);

            RemontinkaServer.Instance.DataStore.SaveUserPublicKeyRequest(entity);

            var response = new RegisterPublicKeyResponse();

            response.Number       = entity.Number;
            response.UserDomainID = user.UserDomainID;

            return(serializer.Serialize(response));
        }
Exemple #20
0
        public void GetCustomReportItemResponseTest()
        {
            var message = new GetCustomReportItemResponse();

            Assert.AreEqual(message.Kind, MessageKind.GetCustomReportItemResponse);
            var item1 = new CustomReportItemDTO();

            item1.CustomReportID = Guid.NewGuid();
            item1.DocumentKindID = 1;
            item1.Title          = "Title";
            item1.HtmlContent    = "HtmlContent";

            var item2 = new CustomReportItemDTO();

            item2.CustomReportID = Guid.NewGuid();
            item2.DocumentKindID = 1;
            item2.Title          = "Title2";
            item2.HtmlContent    = "HtmlConte323nt";

            message.CustomReportItems.Add(item1);
            message.CustomReportItems.Add(item2);


            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);

            var savedMessage = serializer.DeserializeGetCustomReportItemResponse(data);

            Assert.IsNotNull(savedMessage);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetCustomReportItemResponse);
            Assert.AreEqual(savedMessage.CustomReportItems.Count, 2);

            var savedItem1 = savedMessage.CustomReportItems[0];
            var savedItem2 = savedMessage.CustomReportItems[1];

            Assert.AreEqual(savedItem1.CustomReportID, item1.CustomReportID);
            Assert.AreEqual(savedItem1.DocumentKindID, item1.DocumentKindID);
            Assert.AreEqual(savedItem1.HtmlContent, item1.HtmlContent);
            Assert.AreEqual(savedItem1.Title, item1.Title);

            Assert.AreEqual(savedItem2.CustomReportID, item2.CustomReportID);
            Assert.AreEqual(savedItem2.DocumentKindID, item2.DocumentKindID);
            Assert.AreEqual(savedItem2.HtmlContent, item2.HtmlContent);
            Assert.AreEqual(savedItem2.Title, item2.Title);
        }
Exemple #21
0
        public void FinancialGroupBranchesResponseTest()
        {
            var message = new GetFinancialGroupBranchesResponse();

            Assert.AreEqual(message.Kind, MessageKind.GetFinancialGroupBranchesResponse);
            var financialGroupItem = new FinancialGroupItemDTO();

            financialGroupItem.Trademark        = "Trademark";
            financialGroupItem.FinancialGroupID = Guid.NewGuid();
            financialGroupItem.LegalName        = "LegalName";
            financialGroupItem.Title            = "Title";

            var item = new FinancialGroupBranchMapItemDTO();

            item.FinancialGroupID          = financialGroupItem.FinancialGroupID;
            item.BranchID                  = Guid.NewGuid();
            item.FinancialGroupBranchMapID = Guid.Empty;

            message.FinancialGroupItems.Add(financialGroupItem);
            message.FinancialGroupBranchMapItems.Add(item);

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);

            var savedMessage = serializer.DeserializeGetFinancialGroupBranchesResponse(data);

            Assert.IsNotNull(savedMessage);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetFinancialGroupBranchesResponse);
            Assert.AreEqual(savedMessage.FinancialGroupItems.Count, 1);
            Assert.AreEqual(savedMessage.FinancialGroupBranchMapItems.Count, 1);

            var savedfinancialGroupItem = savedMessage.FinancialGroupItems[0];
            var savedItem = savedMessage.FinancialGroupBranchMapItems[0];

            Assert.AreEqual(savedfinancialGroupItem.Trademark, savedfinancialGroupItem.Trademark);
            Assert.AreEqual(savedfinancialGroupItem.FinancialGroupID, savedfinancialGroupItem.FinancialGroupID);
            Assert.AreEqual(savedfinancialGroupItem.LegalName, savedfinancialGroupItem.LegalName);
            Assert.AreEqual(savedfinancialGroupItem.Title, savedfinancialGroupItem.Title);


            Assert.AreEqual(savedItem.BranchID, item.BranchID);
            Assert.AreEqual(savedItem.FinancialGroupID, item.FinancialGroupID);
            Assert.AreEqual(savedItem.FinancialGroupBranchMapID, item.FinancialGroupBranchMapID);
        }
Exemple #22
0
        /// <summary>
        /// Обработчик запроса на получению информации по регистрации публичных ключей.
        /// </summary>
        /// <param name="serializer">Сериализатор протокола.</param>
        /// <param name="postData">Данные запроса.</param>
        /// <param name="hostAddress">Адрес клиента.</param>
        /// <returns>Результат.</returns>
        private string ProcessProbeKeyActivationRequest(ProtocolSerializer serializer, string postData, string hostAddress)
        {
            var request = serializer.DeserializeProbeKeyActivationRequest(postData);

            _logger.InfoFormat("Получен запрос на проверки регистрации ключа {0} для домена {1} с клиента {2}",
                               request.KeyNumber,
                               request.UserDomainID, hostAddress);

            var response = new ProbeKeyActivationResponse();

            response.IsExists = true;
            var currentKey = RemontinkaServer.Instance.DataStore.GetPublicKey(request.UserDomainID, request.KeyNumber);

            if (currentKey != null)
            {
                currentKey.IsRevoked = currentKey.IsRevoked;
                response.UserID      = currentKey.UserID;

                currentKey = RemontinkaServer.Instance.DataStore.GetCurrentPublicKey(currentKey.UserID);

                if (currentKey != null)
                {
                    currentKey.IsRevoked = currentKey.IsRevoked;
                }  //if
                else
                {
                    response.IsExpired = true;
                } //else
            }     //
            else
            {
                var keyRequest = RemontinkaServer.Instance.DataStore.GetUserPublicKeyRequest(request.UserDomainID, request.KeyNumber);
                if (keyRequest != null)
                {
                    response.IsNotAccepted = true;
                }  //if
                else
                {
                    response.IsExists = false;
                } //else
            }     //if

            return(serializer.Serialize(response));
        }
Exemple #23
0
        public void GetOrderStatusesResponseTest()
        {
            var message = new GetOrderStatusesResponse();

            Assert.AreEqual(message.Kind, MessageKind.GetOrderStatusesResponse);

            var item = new OrderKindDTO();

            item.OrderKindID = Guid.NewGuid();
            item.Title       = "Title";

            var orderStatus = new OrderStatusDTO();

            orderStatus.OrderStatusID = Guid.NewGuid();
            orderStatus.Title         = "Title";
            orderStatus.StatusKindID  = 1;

            message.OrderKinds.Add(item);
            message.OrderStatuses.Add(orderStatus);

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);

            var savedMessage = serializer.DeserializeGetOrderStatusesResponse(data);

            Assert.IsNotNull(savedMessage);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetOrderStatusesResponse);
            Assert.AreEqual(savedMessage.OrderKinds.Count, 1);
            Assert.AreEqual(savedMessage.OrderStatuses.Count, 1);

            var savedOrderStatus = savedMessage.OrderStatuses[0];
            var savedOrderKind   = savedMessage.OrderKinds[0];

            Assert.AreEqual(orderStatus.StatusKindID, savedOrderStatus.StatusKindID);
            Assert.AreEqual(orderStatus.Title, savedOrderStatus.Title);
            Assert.AreEqual(orderStatus.OrderStatusID, savedOrderStatus.OrderStatusID);



            Assert.AreEqual(savedOrderKind.OrderKindID, item.OrderKindID);
            Assert.AreEqual(savedOrderKind.Title, item.Title);
        }
Exemple #24
0
        public void GetWarehousesResponseTest()
        {
            var message = new GetWarehousesResponse();

            Assert.AreEqual(message.Kind, MessageKind.GetWarehousesResponse);
            var warehouse = new WarehouseDTO();

            warehouse.WarehouseID = Guid.NewGuid();
            warehouse.Title       = "Title";

            var item = new FinancialGroupWarehouseMapItemDTO();

            item.FinancialGroupID             = warehouse.WarehouseID;
            item.FinancialGroupWarehouseMapID = Guid.NewGuid();
            item.FinancialGroupID             = Guid.Empty;

            message.Warehouses.Add(warehouse);
            message.MapItems.Add(item);

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);

            var savedMessage = serializer.DeserializeGetWarehousesResponse(data);

            Assert.IsNotNull(savedMessage);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetWarehousesResponse);
            Assert.AreEqual(savedMessage.Warehouses.Count, 1);
            Assert.AreEqual(savedMessage.MapItems.Count, 1);

            var savedWarehouse = savedMessage.Warehouses[0];
            var savedItem      = savedMessage.MapItems[0];

            Assert.AreEqual(savedWarehouse.WarehouseID, savedWarehouse.WarehouseID);
            Assert.AreEqual(savedWarehouse.Title, savedWarehouse.Title);


            Assert.AreEqual(savedItem.WarehouseID, item.WarehouseID);
            Assert.AreEqual(savedItem.FinancialGroupID, item.FinancialGroupID);
            Assert.AreEqual(savedItem.FinancialGroupWarehouseMapID, item.FinancialGroupWarehouseMapID);
        }
Exemple #25
0
        /// <summary>
        /// Обработчик запроса на получение категорий и номенклатур товаров.
        /// </summary>
        /// <param name="serializer">Сериализатор протокола.</param>
        /// <param name="postData">Данные запроса.</param>
        /// <param name="hostAddress">Адрес клиента.</param>
        /// <returns>Результат.</returns>
        private string ProcessGetGoodsItemRequest(ProtocolSerializer serializer, string postData, string hostAddress)
        {
            var request = serializer.DeserializeGetGoodsItemRequest(postData);

            _logger.InfoFormat(
                "Получен запрос на получение информации по категориям и номенклатур от пользователя {0} с клиента {1}",
                request.UserID, hostAddress);

            var userDomainID = CheckSignedMessage(request);

            var goodsItems = RemontinkaServer.Instance.DataStore.GetGoodsItems(userDomainID);
            var response   = new GetGoodsItemResponse();

            foreach (var item in goodsItems)
            {
                response.GoodsItems.Add(new Protocol.SynchronizationMessages.GoodsItemDTO
                {
                    BarCode         = item.BarCode,
                    Description     = item.Description,
                    DimensionKindID = item.DimensionKindID,
                    GoodsItemID     = item.GoodsItemID,
                    ItemCategoryID  = item.ItemCategoryID,
                    Particular      = item.Particular,
                    Title           = item.Title,
                    UserCode        = item.UserCode
                });
            } //foreach

            var items = RemontinkaServer.Instance.DataStore.GetItemCategories(userDomainID);

            foreach (var item in items)
            {
                response.ItemCategories.Add(new ItemCategoryDTO
                {
                    ItemCategoryID = item.ItemCategoryID,
                    Title          = item.Title
                });
            } //foreach

            return(serializer.Serialize(response));
        }
Exemple #26
0
        public void SaveRepairOrderResponseTest()
        {
            var message = new SaveRepairOrderResponse();

            Assert.AreEqual(message.Kind, MessageKind.SaveRepairOrderResponse);

            message.Success = true;

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.SaveRepairOrderResponse);

            var savedMessage = serializer.DeserializeSaveRepairOrderResponse(data);

            Assert.IsNotNull(savedMessage);

            Assert.AreEqual(message.Kind, savedMessage.Kind);
            Assert.AreEqual(message.Success, savedMessage.Success);
        }
Exemple #27
0
        public void GetOrderStatusesRequestTest()
        {
            var message = new GetOrderStatusesRequest();

            Assert.AreEqual(message.Kind, MessageKind.GetOrderStatusesRequest);

            message.UserID = Guid.NewGuid();

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetOrderStatusesRequest);

            var savedMessage = serializer.DeserializeGetOrderStatusesRequest(data);

            Assert.IsNotNull(savedMessage);

            Assert.AreEqual(message.Kind, savedMessage.Kind);
            Assert.AreEqual(message.UserID, savedMessage.UserID);
        }
Exemple #28
0
        public void GetWarehouseItemsResponseTest()
        {
            var message = new GetWarehouseItemsResponse();

            Assert.AreEqual(message.Kind, MessageKind.GetWarehouseItemsResponse);

            var item = new WarehouseItemDTO();

            item.WarehouseItemID = Guid.NewGuid();
            item.GoodsItemID     = Guid.NewGuid();
            item.WarehouseID     = Guid.Empty;
            item.RepairPrice     = 11.22M;
            item.SalePrice       = 22.65M;
            item.StartPrice      = 55.64M;
            item.Total           = 10.23M;

            message.WarehouseItems.Add(item);

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);

            var savedMessage = serializer.DeserializeGetWarehouseItemsResponse(data);

            Assert.IsNotNull(savedMessage);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.GetWarehouseItemsResponse);
            Assert.AreEqual(savedMessage.WarehouseItems.Count, 1);

            var savedItem = savedMessage.WarehouseItems[0];

            Assert.AreEqual(savedItem.WarehouseID, item.WarehouseID);
            Assert.AreEqual(savedItem.WarehouseItemID, item.WarehouseItemID);
            Assert.AreEqual(savedItem.GoodsItemID, item.GoodsItemID);
            Assert.AreEqual(savedItem.RepairPrice, item.RepairPrice);
            Assert.AreEqual(savedItem.SalePrice, item.SalePrice);
            Assert.AreEqual(savedItem.StartPrice, item.StartPrice);
            Assert.AreEqual(savedItem.Total, item.Total);
        }
Exemple #29
0
    /// Метод для работы с клиентом в другом потоке
    private void ClientProcessing(object sender, DoWorkEventArgs e)
    {
        // чтение аргументов
        List <object>      args       = (List <object>)e.Argument;
        ProtocolSerializer serializer = new ProtocolSerializer();

        try
        {
            while (socket.Connected)
            {
                // получение или отправка данных
            }
        }
        catch (SocketException)
        {
            // обработка исключений
        }
        catch (Exception)
        {
            // обработка исключений
        }
    }
Exemple #30
0
        public void AuthErrorResponseTest()
        {
            var message = new AuthErrorResponse();

            Assert.AreEqual(message.Kind, MessageKind.AuthErrorResponse);

            message.Message = "AuthErrorResponse";

            var serializer = new ProtocolSerializer(ProtocolVersion.Version10);
            var data       = serializer.Serialize(message);

            Assert.IsNotNull(data);
            Assert.AreEqual(serializer.GetMessageInfoOrNull(data).Kind, MessageKind.AuthErrorResponse);

            var savedMessage = serializer.DeserializeAuthErrorResponse(data);

            Assert.IsNotNull(savedMessage);

            Assert.AreEqual(message.Kind, savedMessage.Kind);
            Assert.AreEqual(message.Version, savedMessage.Version);
            Assert.AreEqual(message.Message, savedMessage.Message);
        }