Ejemplo n.º 1
0
        public override Task <ReadResponse> ReadCpu(ReadRequest request, ServerCallContext context)
        {
            var result = new ReadResponse();

            try
            {
                if (request.Length > 1)
                {
                    Console.Write($"Reading 0x{request.Address:X4}-0x{request.Address + request.Length - 1:X4} @ CPU... ");
                }
                else
                {
                    Console.Write($"Reading 0x{request.Address:X4} @ CPU... ");
                }
                byte[] data;
                if (request.HasLength)
                {
                    data = dumper.ReadCpu((ushort)request.Address, (ushort)request.Length);
                }
                else
                {
                    data = new byte[] { dumper.ReadCpu((ushort)request.Address) }
                };
                if (data.Length <= 32)
                {
                    foreach (var b in data)
                    {
                        Console.Write($"{b:X2} ");
                    }
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("OK");
                }
                result.Data = ByteString.CopyFrom(data);
            }
            catch (Exception ex)
            {
                PrintError(ex);
                result.ErrorInfo = new ErrorInfo()
                {
                    ExceptionName    = ex.GetType().ToString(),
                    ExceptionMessage = ex.Message
                };
            }
            return(Task.FromResult(result));
        }
        /// <summary>
        /// Reads tag unit.
        /// </summary>
        async Task ReadUnit(ReferenceDescription[] rds, UaTcpSessionChannel channel, Tag tag)
        {
            ReadValueId[] unit = new ReadValueId[1];
            unit[0] = new ReadValueId {
                NodeId = NodeId.Parse(rds.Last().NodeId.ToString()), AttributeId = AttributeIds.Value
            };
            ReadRequest unitRequest = new ReadRequest {
                NodesToRead = unit
            };
            ReadResponse unitResponse = await channel.ReadAsync(unitRequest);

            ExtensionObject EO = (ExtensionObject)unitResponse.Results[0].Value;
            EUInformation   EU = (EUInformation)EO.Body;

            tag.Unit = EU.DisplayName; //zapis jednostki
        }
Ejemplo n.º 3
0
 private void Connect_Click(object sender, EventArgs e)
 {
     if (!clientSocket.Connected) // man kan inte ansluta
     {
         try
         {
             clientSocket.Connect(ipInput.Text, port); // ansluter till serverns socket
             isConnected = true;
             ReadResponse.RunWorkerAsync();            // kör i bakgrunden och läser av från servern
         }
         catch (SocketException ex)
         {
             MessageBox.Show(ex.ToString()); // något gjick fel
         }
     }
 }
Ejemplo n.º 4
0
        public void ReadFile(out byte[] data, NtHandle handle, long offset, int maxCount)
        {
            ReadRequest request = new ReadRequest
            {
                Header     = { CreditCharge = (ushort)Math.Ceiling((double)maxCount / BytesPerCredit) },
                FileId     = (FileID)handle,
                Offset     = (ulong)offset,
                ReadLength = (uint)maxCount
            };

            SendCommand(request);
            ReadResponse readResponse = (ReadResponse)WaitForCommand(request.MessageID);

            readResponse.IsSuccessElseThrow();
            data = readResponse.Data;
        }
Ejemplo n.º 5
0
        public void Read_Return_Success()
        {
            //Setup
            FinanceDbContext        _dbContext          = GetDbContext(GetCurrentMethod());
            Mock <IServiceProvider> serviceProviderMock = GetServiceProvider();

            var vBRealizationWithPOService = new VBRealizationWithPOService(_dbContext, serviceProviderMock.Object);
            var vBRealizationDocumenData   = _dataUtil(vBRealizationWithPOService).GetTestData_TanpaNomorVB();

            //Act
            ReadResponse <VBRealizationDocumentModel> result = vBRealizationWithPOService.Read(1, 1, "{}", new List <string>(), "", "{}");

            //Assert
            Assert.NotNull(result);
            Assert.True(0 < result.Count);
        }
Ejemplo n.º 6
0
        /// <inheritdoc/>
        protected override Task <ILogConsistencyProtocolMessage> OnMessageReceived(ILogConsistencyProtocolMessage payload)
        {
            var request = (ReadRequest)payload;

            var response = new ReadResponse <TLogView>()
            {
                Version = version
            };

            // optimization: include value only if version is newer
            if (version > request.KnownVersion)
            {
                response.Value = cached;
            }

            return(Task.FromResult <ILogConsistencyProtocolMessage>(response));
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> WriteAsync([FromRoute] string mount)
        {
            var(backend, path) = _server.ResolveAuthMount(mount);
            if (backend == null)
            {
                throw new VaultServerException(
                          HttpStatusCode.NotFound,
                          $"no handler for route '{mount}'");
            }

            // Decode the bytes as UTF8 string
            string json;

            using (var b = new StreamReader(this.Request.Body, Encoding.UTF8))
            {
                json = b.ReadToEnd();
            }

            try
            {
                RememberMe();
                var ret = await backend.WriteAsync(path, json);

                // if (ret is NoContentResponse)
                if (ret == null)
                {
                    return(base.NoContent());
                }

                var resp = new ReadResponse <object>();
                if (ret is AuthInfo auth)
                {
                    resp.Auth = auth;
                }
                else
                {
                    resp.Data = ret;
                }

                return(base.Ok(resp));
            }
            catch (Exception ex)
            {
                return(await DecodeException(ex));
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Reads the values for a node collection. Returns diagnostic errors.
        /// </summary>
        /// <param name="nodeIds">The node Id.</param>
        /// <param name="ct">The cancellation token for the request.</param>
        public async Task <(DataValueCollection, IList <ServiceResult>)> ReadValuesAsync(
            IList <NodeId> nodeIds,
            CancellationToken ct = default)
        {
            if (nodeIds.Count == 0)
            {
                return(new DataValueCollection(), new List <ServiceResult>());
            }

            // read all values from server.
            var itemsToRead = new ReadValueIdCollection(
                nodeIds.Select(nodeId =>
                               new ReadValueId {
                NodeId      = nodeId,
                AttributeId = Attributes.Value
            }));

            // read from server.
            var errors = new List <ServiceResult>(itemsToRead.Count);

            ReadResponse readResponse = await ReadAsync(
                null,
                0,
                TimestampsToReturn.Both,
                itemsToRead, ct).ConfigureAwait(false);

            DataValueCollection      values          = readResponse.Results;
            DiagnosticInfoCollection diagnosticInfos = readResponse.DiagnosticInfos;

            ClientBase.ValidateResponse(values, itemsToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, itemsToRead);

            foreach (var value in values)
            {
                ServiceResult result = ServiceResult.Good;
                if (StatusCode.IsBad(value.StatusCode))
                {
                    result = ClientBase.GetResult(values[0].StatusCode, 0, diagnosticInfos, readResponse.ResponseHeader);
                }
                errors.Add(result);
            }

            return(values, errors);
        }
Ejemplo n.º 9
0
        public async Task <MembershipTableData> ReadAll()
        {
            try
            {
                ReadResponse spResponse = await ReadRecords();

                ClusterVersionEntity versionEntity = spResponse.ClusterVersion;
                List <SiloEntity>    entryEntities = spResponse.Silos;

                TableVersion version = null;
                if (versionEntity != null)
                {
                    version = new TableVersion(versionEntity.ClusterVersion, versionEntity.ETag);
                }
                else
                {
                    this._logger.LogError("Initial ClusterVersionEntity entity doesn't exist.");
                }

                var memEntries = new List <Tuple <MembershipEntry, string> >();
                foreach (var entity in entryEntities)
                {
                    try
                    {
                        MembershipEntry membershipEntry = ParseEntity(entity);
                        memEntries.Add(new Tuple <MembershipEntry, string>(membershipEntry, entity.ETag));
                    }
                    catch (Exception exc)
                    {
                        this._logger.LogError(exc, "Failure reading all membership records.");
                        throw;
                    }
                }

                var data = new MembershipTableData(memEntries, version);
                return(data);
            }
            catch (Exception exc)
            {
                this._logger.LogWarning($"Failure reading all silo entries for cluster id {this._clusterOptions.ClusterId}: {exc}");
                throw;
            }
        }
Ejemplo n.º 10
0
        public ReadResponse Read(string storeName, int start, int pageSize, string search, int sortByColumn, string sortDirection)
        {
            var response = new ReadResponse {
                Success = false
            };

            logger.Debug("Read started");
            int totalCount;

            var store         = DynamicDataStoreFactory.Instance.GetStore(storeName);
            var storeMetadata = store.Metadata();

            // TODO: we cannot order here due to fact that this is PropertyBag, if we could it would be great performance boost
            // var orderBy = sortByColumn == 0 ? "Id" : StoreMetadata.Columns.ToList()[sortByColumn - 1].PropertyName;
            var query = store.ItemsAsPropertyBag(); // .OrderBy(orderBy);

            var data = sortByColumn == 0 && string.IsNullOrEmpty(search)
                               ? (sortDirection == "asc"
                                          ? query.OrderBy(r => r.Id).Skip(start).Take(pageSize).ToList()
                                          : query.OrderByDescending(r => r.Id).Skip(start).Take(pageSize).ToList())
                               : query.ToList();

            List <List <string> > stringData;

            if (sortByColumn == 0 && string.IsNullOrEmpty(search))
            {
                // no sorting and no filtering, use fast code then
                stringData = FormatData(storeMetadata, data);
                totalCount = query.Count();
            }
            else
            {
                stringData = FilterAndFormatData(storeMetadata, data, search);
                totalCount = stringData.Count;
                stringData = GetSortedPagedData(stringData, start, pageSize, sortByColumn, sortDirection == "asc");
            }

            response.TotalCount = totalCount;
            response.Data       = stringData;
            response.Success    = true;
            logger.Debug("Read finished");
            return(response);
        }
Ejemplo n.º 11
0
        public static SMB2Body CreateSMB2Body(byte[] vs, int offset, ESMB2Command eSMB2Command, SMB2HeaderFlags smb2HeaderFlags, NTStateType ntState)
        {
            SMB2Body sMB2Body = null;

            if (smb2HeaderFlags.HasFlag(SMB2HeaderFlags.ServerToRedir))
            {
                if (ntState == NTStateType.Success || ntState == NTStateType.MoreProcessingRequired || ntState == NTStateType.LogonFailure)
                {
                    switch (eSMB2Command)
                    {
                    case ESMB2Command.NEGOTIATE: sMB2Body = NegotiateResponse.Parser(vs, offset); break;

                    case ESMB2Command.SESSION_SETUP: sMB2Body = SessionSetupResponse.Parser(vs, offset); break;

                    case ESMB2Command.TREE_CONNECT: sMB2Body = TreeConnectResponse.Parser(vs, offset); break;

                    case ESMB2Command.LOGOFF:
                    case ESMB2Command.TREE_DISCONNECT: sMB2Body = LogoffAndTreeDisconnect.Parser(vs, offset); break;

                    case ESMB2Command.CREATE: sMB2Body = CreateResponse.Parser(vs, offset); break;

                    case ESMB2Command.CLOSE: sMB2Body = CloseResponse.Parser(vs, offset); break;

                    case ESMB2Command.WRITE: sMB2Body = WriteResponse.Parser(vs, offset); break;

                    case ESMB2Command.READ: sMB2Body = ReadResponse.Parser(vs, offset); break;

                    case ESMB2Command.IOCTL: sMB2Body = IOCTLResponse.Parser(vs, offset); break;

                    default: throw new Exception("UnKnow SMB2 Command");
                    }
                }
                else
                {
                    sMB2Body = ErrorResponse.Parser(vs, offset);
                }
            }
            else
            {
                throw new NotImplementedException();
            }
            return(sMB2Body);
        }
Ejemplo n.º 12
0
 public virtual IActionResult Get(int page = 1, int size = 25, string order = "{}", [Bind(Prefix = "Select[]")] List <string> select = null, string keyword = null, string filter = "{}")
 {
     try
     {
         ValidateUser();
         ReadResponse <ClearaceVBViewModel> read   = Service.Read(page, size, order, select, keyword, filter);
         Dictionary <string, object>        Result =
             new ResultFormatter(ApiVersion, General.OK_STATUS_CODE, General.OK_MESSAGE)
             .Ok(Mapper, read.Data, page, size, read.Count, read.Data.Count, read.Order, read.Selected);
         return(Ok(Result));
     }
     catch (Exception e)
     {
         Dictionary <string, object> Result =
             new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
             .Fail();
         return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
     }
 }
        public virtual IActionResult Get(int Page = 1, int Size = 25, string Order = "{}", [Bind(Prefix = "Select[]")] List <string> Select = null, string Keyword = null, string Filter = "{}")
        {
            try
            {
                ReadResponse <TModel> read = Service.Read(Page, Size, Order, Select, Keyword, Filter);

                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.OK_STATUS_CODE, General.OK_MESSAGE)
                    .Ok(read.Data, Service.MapToViewModel, Page, Size, read.Count, read.Data.Count, read.Order, read.Selected);
                return(Ok(Result));
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Ejemplo n.º 14
0
        public override IActionResult Get(int page = 1, int size = 25, string order = "{}", [Bind(Prefix = "Select[]")] List <string> select = null, string keyword = null, string filter = "{}")
        {
            try
            {
                ValidateUser();

                ReadResponse <FinishingPrintingSalesContractModel> read = Facade.Read(page, size, order, select, keyword, filter);

                //Tuple<List<TModel>, int, Dictionary<string, string>, List<string>> Data = Facade.Read(page, size, order, select, keyword, filter);
                List <ShinFinishingPrintingSalesContractViewModel> DataVM = Mapper.Map <List <ShinFinishingPrintingSalesContractViewModel> >(read.Data);

                foreach (var data in DataVM)
                {
                    var preSalesContractModel = fpPreSalesContractFacade.ReadByIdAsync((int)data.PreSalesContract.Id).Result;
                    if (preSalesContractModel != null)
                    {
                        data.PreSalesContract = Mapper.Map <FinishingPrintingPreSalesContractViewModel>(preSalesContractModel);
                    }
                    //var fpCCModel = finishingPrintingCostCalculationService.ReadParent(data.CostCalculation.Id).Result;
                    //if(fpCCModel != null)
                    //{

                    //    var fpCCVM = Mapper.Map<FinishingPrintingCostCalculationViewModel>(fpCCModel);
                    //    var preSalesContractModel = fpPreSalesContractFacade.ReadByIdAsync((int)fpCCVM.PreSalesContract.Id).Result;
                    //    fpCCVM.PreSalesContract = Mapper.Map<FinishingPrintingPreSalesContractViewModel>(preSalesContractModel);
                    //    data.CostCalculation = fpCCVM;
                    //}
                }

                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, Common.OK_STATUS_CODE, Common.OK_MESSAGE)
                    .Ok <ShinFinishingPrintingSalesContractViewModel>(Mapper, DataVM, page, size, read.Count, DataVM.Count, read.Order, read.Selected);
                return(Ok(Result));
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, Common.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(Common.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Ejemplo n.º 15
0
        public override async Task <VTQ[]> ReadDataItems(string group, IList <ReadRequest> items, Duration?timeout)
        {
            int N = items.Count;

            VTQ[] res = new VTQ[N];

            bool connected = await TryConnect();

            if (!connected)
            {
                for (int i = 0; i < N; ++i)
                {
                    VTQ vtq = items[i].LastValue;
                    vtq.Q  = Quality.Bad;
                    res[i] = vtq;
                }
                return(res);
            }

            ReadValueId[] dataItemsToRead = new ReadValueId[N];
            for (int i = 0; i < N; ++i)
            {
                ReadRequest request = items[i];
                NodeId      node    = mapId2Info[request.ID].Node ?? NodeId.Null;
                dataItemsToRead[i] = new ReadValueId {
                    AttributeId = AttributeIds.Value, NodeId = node
                };
            }

            var readRequest = new Workstation.ServiceModel.Ua.ReadRequest {
                NodesToRead        = dataItemsToRead,
                TimestampsToReturn = TimestampsToReturn.Source,
            };

            ReadResponse readResponse = await connection.ReadAsync(readRequest);

            for (int i = 0; i < N; ++i)
            {
                res[i] = MakeVTQ(readResponse.Results[i], items[i].LastValue, items[i].ID);
            }
            return(res);
        }
Ejemplo n.º 16
0
        public CausalConsistency.ImmutableVectorClock Read(
            string partitionId,
            string objectId,
            out string value,
            CausalConsistency.ImmutableVectorClock timestamp)
        {
            ReadRequest request = new ReadRequest {
                PartitionId = partitionId,
                ObjectId    = objectId,
                Timestamp   = BuildGrpcClock(timestamp)
            };

            ReadResponse response = client.Read(
                request,
                deadline: DateTime.UtcNow.AddSeconds(60));

            value = !response.Missing ? response.ObjectValue : null;

            return(BuildVectorClock(response.Timestamp));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Reads multiple items in one single request.
        /// Currently only reading based on the path of an item or property is supported.
        /// </summary>
        /// <param name="items">List of Identity instances to read.</param>
        private static async Task ReadMultipleItemsAtOnce(List <Identity> items)
        {
            LogResult();

            ReadResponse readResponse = await _client.ReadAsync(items);

            if (readResponse.Error != null)
            {
                Console.WriteLine(string.Format("An error has occurred : {0}", readResponse.Error?.First().Message));
            }
            else
            {
                foreach (ItemValue itemValue in readResponse.Data)
                {
                    Console.WriteLine("ItemValue: {0}", itemValue);
                }
            }

            Console.WriteLine();
        }
Ejemplo n.º 18
0
        public async void Should_Success_Get_Data()
        {
            var numberGeneratorMock = new Mock <IBankDocumentNumberGenerator>();

            numberGeneratorMock.Setup(p => p.GenerateDocumentNumber(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync("TEST");

            BankExpenditureNoteFacade facadeBEN = new BankExpenditureNoteFacade(_dbContext(GetCurrentMethod()), numberGeneratorMock.Object);

            await _dataUtilBEN(facadeBEN, GetCurrentMethod()).GetTestData();

            PPHBankExpenditureNoteFacade facadeBENPPH = new PPHBankExpenditureNoteFacade(_dbContext(GetCurrentMethod()), numberGeneratorMock.Object);

            await _dataUtilBENPPH(facadeBENPPH, GetCurrentMethod()).GetTestData();

            UnitPaymentOrderPaidStatusReportFacade facade = new UnitPaymentOrderPaidStatusReportFacade(_dbContext(GetCurrentMethod()));
            ReadResponse response = facade.GetReport(25, 1, "{}", null, null, null, null, null, null, 0);

            Assert.NotEqual(null, response);
        }
Ejemplo n.º 19
0
 private ReadResponse Read(ReadRequest request)
 {
     Console.WriteLine("Received Read Request: " + request.ToString());
     try {
         var partitionId = request.PartitionId;
         var objectId    = request.ObjectId;
         var partition   = _storage.GetPartitionOrThrowException(partitionId);
         var objectValue = _storage.Read(partitionId, objectId);
         var response    = new ReadResponse {
             ObjectValue = objectValue
         };
         return(response);
     }
     catch (Exception) {
         /*Partition not founded */
         return(new ReadResponse {
             ObjectValue = "N/A"
         });
     }
 }
Ejemplo n.º 20
0
        public ActionResult Get(int page = 1, int size = 25, string order = "{}", string keyword = null, string filter = "{}")
        {
            ReadResponse <object> Response = this.facade.Read(page, size, order, keyword, filter);

            return(Ok(new
            {
                apiVersion = "1.0.0",
                data = Response.Data,
                info = new Dictionary <string, object>
                {
                    { "count", Response.Data.Count },
                    { "total", Response.TotalData },
                    { "order", Response.Order },
                    { "page", page },
                    { "size", size }
                },
                message = General.OK_MESSAGE,
                statusCode = General.OK_STATUS_CODE
            }));
        }
Ejemplo n.º 21
0
        public void Basic_READ_Statement_Works()
        {
            string code = @"
INT nextNumber = 999;
EXECUTE \\Connections\DummyConnection\Tables\LAG\Manufacturers
    GET (NextManufacturerNumber AS nextNumber)
END";

            _SyneryClient.Run(code);

            // resolve the synery variable "nextNumber"
            int testNextNumber = (int)_SyneryMemory.CurrentScope.ResolveVariable("nextNumber").Value;

            // load the provider plugin connection
            string[]            connectionPath = new string[] { "Connections", "DummyConnection" };
            IProviderConnection connection     = _ProviderPluginManager.Connections[connectionPath];

            string[]      endpointPath     = new string[] { "Tables", "LAG" };
            IReadEndpoint articlesEndpoint = (from e in connection.Endpoints
                                              where e is IReadEndpoint &&
                                              ArrayEqualityComparer.Equals(e.Path, endpointPath) &&
                                              e.Name == "Articles"
                                              select(IReadEndpoint) e).FirstOrDefault();

            ReadResource resource = articlesEndpoint.GetReadResource();

            // create a mocked read request

            Mock <IReadRequest> mock = new Mock <IReadRequest>();

            mock.Setup(r => r.Resource).Returns(resource);
            mock.Setup(r => r.RequestedFields).Returns(resource.Schema.Fields);

            // request all articles with all fields
            ReadResponse response = articlesEndpoint.RunReadRequest(mock.Object);

            // calculate the expected number from adding 1 to the highest manufacturer number
            int expectedNextNumber = response.RecordSet.Max(r => (int)r["ManufacturerNumber"]) + 1;

            Assert.AreEqual(expectedNextNumber, testNextNumber);
        }
Ejemplo n.º 22
0
        public IActionResult GetReport(int bankId, int month, int year)
        {
            try
            {
                int clientTimeZoneOffset = int.Parse(Request.Headers["x-timezone-offset"].First());
                ReadResponse <DailyBankTransactionModel> Result = Service.GetReport(bankId, month, year, clientTimeZoneOffset);

                return(Ok(new
                {
                    apiVersion = "1.0.0",
                    data = Result.Data,
                    message = Utilities.General.OK_MESSAGE,
                    statusCode = Utilities.General.OK_STATUS_CODE
                }));
            }
            catch (Exception e)
            {
                var result = new ResultFormatter(ApiVersion, Utilities.General.INTERNAL_ERROR_STATUS_CODE, e.Message + "\n" + e.StackTrace);
                return(StatusCode(Utilities.General.INTERNAL_ERROR_STATUS_CODE, result));
            }
        }
Ejemplo n.º 23
0
        public IActionResult GetReportAll(string referenceNo, int accountBankId, string division, DateTimeOffset?startDate, DateTimeOffset?endDate, int page = 0, int size = 25, string order = "{}", [Bind(Prefix = "Select[]")] List <string> select = null, string keyword = null, string filter = "{}")
        {
            try
            {
                int clientTimeZoneOffset = int.Parse(Request.Headers["x-timezone-offset"].First());
                ReadResponse <DailyBankTransactionModel> Result = Service.GetReportAll(referenceNo, accountBankId, division, startDate, endDate, page, size, order, select, keyword, filter);

                return(Ok(new
                {
                    apiVersion = "1.0.0",
                    data = Result.Data,
                    message = Utilities.General.OK_MESSAGE,
                    statusCode = Utilities.General.OK_STATUS_CODE
                }));
            }
            catch (Exception e)
            {
                var result = new ResultFormatter(ApiVersion, Utilities.General.INTERNAL_ERROR_STATUS_CODE, e.Message + "\n" + e.StackTrace);
                return(StatusCode(Utilities.General.INTERNAL_ERROR_STATUS_CODE, result));
            }
        }
        public IActionResult GetLoader(string keyword = null, string filter = "{}")
        {
            try
            {
                int clientTimeZoneOffset = int.Parse(Request.Headers["x-timezone-offset"].First());
                ReadResponse <GarmentInvoicePurchasingDispositionNoVM> Result = Service.GetLoader(keyword, filter);

                return(Ok(new
                {
                    apiVersion = "1.0.0",
                    data = Result.Data,
                    message = Utilities.General.OK_MESSAGE,
                    statusCode = Utilities.General.OK_STATUS_CODE
                }));
            }
            catch (Exception e)
            {
                var result = new ResultFormatter(ApiVersion, Utilities.General.INTERNAL_ERROR_STATUS_CODE, e.Message + "\n" + e.StackTrace);
                return(StatusCode(Utilities.General.INTERNAL_ERROR_STATUS_CODE, result));
            }
        }
Ejemplo n.º 25
0
        public IActionResult GetMaterials(int page = 1, int size = 25, string order = "{}", string select = null, string keyword = null, string filter = "{}", string search = "[]")
        {
            try
            {
                ValidateUser();

                ReadResponse <dynamic> read = Facade.ReadMaterials(page, size, order, select, keyword, filter, search);

                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, Common.OK_STATUS_CODE, Common.OK_MESSAGE)
                    .Ok(Mapper, read.Data, page, size, read.Count, read.Data.Count, read.Order, read.Selected);
                return(Ok(Result));
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, Common.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(Common.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Ejemplo n.º 26
0
        public IActionResult Get(int page = 1, int size = 25, string order = "{}", [Bind(Prefix = "Select[]")] List <string> select = null, string keyword = null, string filter = "{}")
        {
            try
            {
                ReadResponse <GarmentFinanceMemorialModel> read = Service.Read(page, size, order, select, keyword, filter);

                List <GarmentFinanceMemorialViewModel> dataVM = Mapper.Map <List <GarmentFinanceMemorialViewModel> >(read.Data);

                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.OK_STATUS_CODE, General.OK_MESSAGE)
                    .Ok(Mapper, dataVM, page, size, read.Count, dataVM.Count, read.Order, read.Selected);
                return(Ok(Result));
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Ejemplo n.º 27
0
        public ActionResult GetReport(string DocumentNo, string UnitPaymentOrderNo, string InvoiceNo, string SupplierCode, string DivisionCode, string PaymentMethod, DateTimeOffset?DateFrom, DateTimeOffset?DateTo, int Size = 25, int Page = 1)
        {
            int clientTimeZoneOffset       = int.Parse(Request.Headers["x-timezone-offset"].First());
            ReadResponse <object> response = this.facade.GetReport(Size, Page, DocumentNo, UnitPaymentOrderNo, InvoiceNo, SupplierCode, DivisionCode, PaymentMethod, DateFrom, DateTo, clientTimeZoneOffset);

            return(Ok(new
            {
                apiVersion = ApiVersion,
                data = response.Data,
                info = new Dictionary <string, object>
                {
                    { "count", response.Data.Count },
                    { "total", response.TotalData },
                    { "order", response.Order },
                    { "page", Page },
                    { "size", Size }
                },
                message = General.OK_MESSAGE,
                statusCode = General.OK_STATUS_CODE
            }));
        }
Ejemplo n.º 28
0
        public IActionResult Get(int page = 1, int size = 25, [Bind(Prefix = "Select[]")] List <string> select = null, string order = "{}", string keyword = null, string filter = "{}")
        {
            try
            {
                ReadResponse <GarmentBookingOrder> read = Facade.ReadExpired(page, size, order, select, keyword, filter);

                List <GarmentBookingOrderViewModel> DataVM = Mapper.Map <List <GarmentBookingOrderViewModel> >(read.Data);

                Dictionary <string, object> Result =
                    new Utilities.ResultFormatter(ApiVersion, Common.OK_STATUS_CODE, Common.OK_MESSAGE)
                    .Ok <GarmentBookingOrderViewModel>(Mapper, DataVM, page, size, read.Count, DataVM.Count, read.Order, read.Selected);
                return(Ok(Result));
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new Utilities.ResultFormatter(ApiVersion, Common.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(Common.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Ejemplo n.º 29
0
        public async Task <ActionResult> Get(int Size, int Page, string Order, string UnitPaymentOrderNo, string SupplierCode, DateTimeOffset?DateFrom, DateTimeOffset?DateTo)
        {
            int clientTimeZoneOffset = int.Parse(Request.Headers["x-timezone-offset"].First());

            ReadResponse response = await this.unitPaymentOrderUnpaidReportFacade.GetReport(Size, Page, Order, UnitPaymentOrderNo, SupplierCode, DateFrom, DateTo, clientTimeZoneOffset);

            return(Ok(new
            {
                apiVersion = ApiVersion,
                data = response.Data,
                info = new Dictionary <string, object>
                {
                    { "count", response.Data.Count },
                    { "total", response.TotalData },
                    { "order", response.Order },
                    { "page", Page },
                    { "size", Size }
                },
                message = General.OK_MESSAGE,
                statusCode = General.OK_STATUS_CODE
            }));
        }
Ejemplo n.º 30
0
        /// <inheritdoc/>
        protected override Task <ILogConsistencyProtocolMessage> OnMessageReceived(ILogConsistencyProtocolMessage payload)
        {
            var request = (ReadRequest)payload;

            if (!MayAccessStorage())
            {
                throw new ProtocolTransportException("message destined for primary cluster ended up elsewhere (inconsistent configurations?)");
            }

            var response = new ReadResponse <TLogView>()
            {
                Version = version
            };

            // optimization: include value only if version is newer
            if (version > request.KnownVersion)
            {
                response.Value = cached;
            }

            return(Task.FromResult <ILogConsistencyProtocolMessage>(response));
        }
Ejemplo n.º 31
0
        /// <summary cref="IServiceMessage.CreateResponse" />
        public object CreateResponse(IServiceResponse response)
        {
            ReadResponse body = response as ReadResponse;

            if (body == null)
            {
                body = new ReadResponse();
                body.ResponseHeader = ((ServiceFault)response).ResponseHeader;
            }

            return new ReadResponseMessage(body);
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Initializes the message with the body.
 /// </summary>
 public ReadResponseMessage(ReadResponse ReadResponse)
 {
     this.ReadResponse = ReadResponse;
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Initializes the message with a service fault.
        /// </summary>
        public ReadResponseMessage(ServiceFault ServiceFault)
        {
            this.ReadResponse = new ReadResponse();

            if (ServiceFault != null)
            {
                this.ReadResponse.ResponseHeader = ServiceFault.ResponseHeader;
            }
        }
        private async Task<IServiceResponse> ReceiveResponseAsync(CancellationToken token = default(CancellationToken))
        {
            await this.receivingSemaphore.WaitAsync(token).ConfigureAwait(false);
            try
            {
                token.ThrowIfCancellationRequested();
                this.ThrowIfClosedOrNotOpening();
                uint sequenceNumber;
                uint requestId;
                int paddingHeaderSize;
                int plainHeaderSize;
                int bodySize;
                int paddingSize;

                var bodyStream = SerializableBytes.CreateWritableStream();
                var bodyDecoder = new BinaryDecoder(bodyStream, this);
                try
                {
                    // read chunks
                    int chunkCount = 0;
                    bool isFinal = false;
                    do
                    {
                        chunkCount++;
                        if (this.LocalMaxChunkCount > 0 && chunkCount > this.LocalMaxChunkCount)
                        {
                            throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
                        }

                        var count = await this.ReceiveAsync(this.receiveBuffer, 0, (int)this.LocalReceiveBufferSize, token).ConfigureAwait(false);
                        if (count == 0)
                        {
                            return null;
                        }

                        var stream = new MemoryStream(this.receiveBuffer, 0, count, true, true);
                        var decoder = new BinaryDecoder(stream, this);
                        try
                        {
                            uint channelId;
                            uint messageType = decoder.ReadUInt32(null);
                            int messageLength = (int)decoder.ReadUInt32(null);
                            Debug.Assert(count == messageLength, "Bytes received not equal to encoded Message length");
                            switch (messageType)
                            {
                                case UaTcpMessageTypes.MSGF:
                                case UaTcpMessageTypes.MSGC:
                                    // header
                                    channelId = decoder.ReadUInt32(null);
                                    if (channelId != this.ChannelId)
                                    {
                                        throw new ServiceResultException(StatusCodes.BadTcpSecureChannelUnknown);
                                    }

                                    // symmetric security header
                                    var tokenId = decoder.ReadUInt32(null);

                                    // detect new token
                                    if (tokenId != this.currentServerTokenId)
                                    {
                                        this.currentServerTokenId = tokenId;

                                        // update with new keys
                                        if (this.symIsSigned)
                                        {
                                            this.symVerifier.Key = this.serverSigningKey;
                                            if (this.symIsEncrypted)
                                            {
                                                this.currentServerEncryptingKey = this.serverEncryptingKey;
                                                this.currentServerInitializationVector = this.serverInitializationVector;
                                                this.symDecryptor = this.symEncryptionAlgorithm.CreateDecryptor(this.currentServerEncryptingKey, this.currentServerInitializationVector);
                                            }
                                        }
                                    }

                                    plainHeaderSize = decoder.Position;

                                    // decrypt
                                    if (this.symIsEncrypted)
                                    {
                                        using (var symDecryptor = this.symEncryptionAlgorithm.CreateDecryptor(this.currentServerEncryptingKey, this.currentServerInitializationVector))
                                        {
                                            int inputCount = messageLength - plainHeaderSize;
                                            Debug.Assert(inputCount % symDecryptor.InputBlockSize == 0, "Input data is not an even number of encryption blocks.");
                                            symDecryptor.TransformBlock(this.receiveBuffer, plainHeaderSize, inputCount, this.receiveBuffer, plainHeaderSize);
                                            symDecryptor.TransformFinalBlock(this.receiveBuffer, messageLength, 0);
                                        }
                                    }

                                    // verify
                                    if (this.symIsSigned)
                                    {
                                        var datalen = messageLength - this.symSignatureSize;
                                        byte[] signature = this.symVerifier.ComputeHash(this.receiveBuffer, 0, datalen);
                                        if (!signature.SequenceEqual(this.receiveBuffer.AsArraySegment(datalen, this.symSignatureSize)))
                                        {
                                            throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed);
                                        }
                                    }

                                    // read sequence header
                                    sequenceNumber = decoder.ReadUInt32(null);
                                    requestId = decoder.ReadUInt32(null);

                                    // body
                                    if (this.symIsEncrypted)
                                    {
                                        if (this.symEncryptionBlockSize > 256)
                                        {
                                            paddingHeaderSize = 2;
                                            paddingSize = BitConverter.ToInt16(this.receiveBuffer, messageLength - this.symSignatureSize - paddingHeaderSize);
                                        }
                                        else
                                        {
                                            paddingHeaderSize = 1;
                                            paddingSize = this.receiveBuffer[messageLength - this.symSignatureSize - paddingHeaderSize];
                                        }

                                        bodySize = messageLength - plainHeaderSize - SequenceHeaderSize - paddingSize - paddingHeaderSize - this.symSignatureSize;
                                    }
                                    else
                                    {
                                        bodySize = messageLength - plainHeaderSize - SequenceHeaderSize - this.symSignatureSize;
                                    }

                                    bodyStream.Write(this.receiveBuffer, plainHeaderSize + SequenceHeaderSize, bodySize);
                                    isFinal = messageType == UaTcpMessageTypes.MSGF;
                                    break;

                                case UaTcpMessageTypes.OPNF:
                                case UaTcpMessageTypes.OPNC:
                                    // header
                                    channelId = decoder.ReadUInt32(null);

                                    // asymmetric header
                                    var securityPolicyUri = decoder.ReadString(null);
                                    var serverCertificateByteString = decoder.ReadByteString(null);
                                    var clientThumbprint = decoder.ReadByteString(null);
                                    plainHeaderSize = decoder.Position;

                                    // decrypt
                                    if (this.asymIsEncrypted)
                                    {
                                        byte[] cipherTextBlock = new byte[this.asymLocalCipherTextBlockSize];
                                        int jj = plainHeaderSize;
                                        for (int ii = plainHeaderSize; ii < messageLength; ii += this.asymLocalCipherTextBlockSize)
                                        {
                                            Buffer.BlockCopy(this.receiveBuffer, ii, cipherTextBlock, 0, this.asymLocalCipherTextBlockSize);

                                            // decrypt with local private key.
                                            byte[] plainTextBlock = this.LocalPrivateKey.Decrypt(cipherTextBlock, this.asymEncryptionPadding);
                                            Debug.Assert(plainTextBlock.Length == this.asymLocalPlainTextBlockSize, "Decrypted block length was not as expected.");
                                            Buffer.BlockCopy(plainTextBlock, 0, this.receiveBuffer, jj, this.asymLocalPlainTextBlockSize);
                                            jj += this.asymLocalPlainTextBlockSize;
                                        }

                                        messageLength = jj;
                                        decoder.Position = plainHeaderSize;
                                    }

                                    // verify
                                    if (this.asymIsSigned)
                                    {
                                        // verify with remote public key.
                                        var datalen = messageLength - this.asymRemoteSignatureSize;
                                        if (!this.RemotePublicKey.VerifyData(this.receiveBuffer, 0, datalen, this.receiveBuffer.AsArraySegment(datalen, this.asymRemoteSignatureSize).ToArray(), this.asymSignatureHashAlgorithmName, RSASignaturePadding.Pkcs1))
                                        {
                                            throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed);
                                        }
                                    }

                                    // sequence header
                                    sequenceNumber = decoder.ReadUInt32(null);
                                    requestId = decoder.ReadUInt32(null);

                                    // body
                                    if (this.asymIsEncrypted)
                                    {
                                        if (this.asymLocalCipherTextBlockSize > 256)
                                        {
                                            paddingHeaderSize = 2;
                                            paddingSize = BitConverter.ToInt16(this.receiveBuffer, messageLength - this.asymRemoteSignatureSize - paddingHeaderSize);
                                        }
                                        else
                                        {
                                            paddingHeaderSize = 1;
                                            paddingSize = this.receiveBuffer[messageLength - this.asymRemoteSignatureSize - paddingHeaderSize];
                                        }

                                        bodySize = messageLength - plainHeaderSize - SequenceHeaderSize - paddingSize - paddingHeaderSize - this.asymRemoteSignatureSize;
                                    }
                                    else
                                    {
                                        bodySize = messageLength - plainHeaderSize - SequenceHeaderSize - this.asymRemoteSignatureSize;
                                    }

                                    bodyStream.Write(this.receiveBuffer, plainHeaderSize + SequenceHeaderSize, bodySize);
                                    isFinal = messageType == UaTcpMessageTypes.OPNF;
                                    break;

                                case UaTcpMessageTypes.ERRF:
                                case UaTcpMessageTypes.MSGA:
                                case UaTcpMessageTypes.OPNA:
                                case UaTcpMessageTypes.CLOA:
                                    var code = (StatusCode)decoder.ReadUInt32(null);
                                    var message = decoder.ReadString(null);
                                    throw new ServiceResultException(code, message);

                                default:
                                    throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                            }

                            if (this.LocalMaxMessageSize > 0 && bodyStream.Position > this.LocalMaxMessageSize)
                            {
                                throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
                            }
                        }
                        finally
                        {
                            decoder.Dispose();
                        }
                    }
                    while (!isFinal);
                    bodyStream.Seek(0L, SeekOrigin.Begin);
                    var nodeId = bodyDecoder.ReadNodeId(null);
                    IServiceResponse response;

                    // fast path
                    if (nodeId == PublishResponseNodeId)
                    {
                        response = new PublishResponse();
                    }
                    else if (nodeId == ReadResponseNodeId)
                    {
                        response = new ReadResponse();
                    }
                    else
                    {
                        // find node in dictionary
                        Type type2;
                        if (!BinaryEncodingIdToTypeDictionary.TryGetValue(NodeId.ToExpandedNodeId(nodeId, this.NamespaceUris), out type2))
                        {
                            throw new ServiceResultException(StatusCodes.BadEncodingError, "NodeId not registered in dictionary.");
                        }

                        // create response
                        response = (IServiceResponse)Activator.CreateInstance(type2);
                    }

                    // set properties from message stream
                    response.Decode(bodyDecoder);
                    return response;
                }
                finally
                {
                    bodyDecoder.Dispose();
                }
            }
            finally
            {
                this.receivingSemaphore.Release();
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Invokes the Read service.
        /// </summary>
        public IServiceResponse Read(IServiceRequest incoming)
        {
            ReadResponse response = null;

            ReadRequest request = (ReadRequest)incoming;

            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            response = new ReadResponse();

            response.ResponseHeader = ServerInstance.Read(
               request.RequestHeader,
               request.MaxAge,
               request.TimestampsToReturn,
               request.NodesToRead,
               out results,
               out diagnosticInfos);

            response.Results         = results;
            response.DiagnosticInfos = diagnosticInfos;

            return response;
        }