Esempio n. 1
0
        private ServiceResult OnGenerateAASCall(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments)
        {
            try
            {
                string packagePath = Path.Combine(Directory.GetCurrentDirectory(), "Station.aasx");
                using (Package package = Package.Open(packagePath, FileMode.Create))
                {
                    // add package origin part
                    PackagePart origin = package.CreatePart(new Uri("/aasx/aasx-origin", UriKind.Relative), MediaTypeNames.Text.Plain, CompressionOption.Maximum);

                    using (Stream fileStream = origin.GetStream(FileMode.Create))
                    {
                        var bytes = Encoding.ASCII.GetBytes("Intentionally empty.");
                        fileStream.Write(bytes, 0, bytes.Length);
                    }

                    package.CreateRelationship(origin.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aasx-origin");

                    // add package spec part
                    PackagePart spec = package.CreatePart(new Uri("/aasx/aasenv-with-no-id/aasenv-with-no-id.aas.xml", UriKind.Relative), MediaTypeNames.Text.Xml);

                    string packageSpecPath = Path.Combine(Directory.GetCurrentDirectory(), "aasenv-with-no-id.aas.xml");
                    using (FileStream fileStream = new FileStream(packageSpecPath, FileMode.Open, FileAccess.Read))
                    {
                        CopyStream(fileStream, spec.GetStream());
                    }

                    origin.CreateRelationship(spec.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-spec");

                    // add the nodeset2.xml as a supplemental document part
                    PackagePart supplementalDoc = package.CreatePart(new Uri("/aasx/Station.NodeSet2.xml", UriKind.Relative), MediaTypeNames.Text.Xml);

                    string documentPath = Path.Combine(Directory.GetCurrentDirectory(), "Station.NodeSet2.xml");
                    using (FileStream fileStream = new FileStream(documentPath, FileMode.Open, FileAccess.Read))
                    {
                        CopyStream(fileStream, supplementalDoc.GetStream());
                    }

                    package.CreateRelationship(supplementalDoc.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-suppl");
                }

                return(ServiceResult.Good);
            }
            catch (Exception ex)
            {
                return(ServiceResult.Create(ex, StatusCodes.BadUnexpectedError, "Failed to create Asset Admin Shell!"));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Sends a fault response secured with the asymmetric keys.
        /// </summary>
        private void SendServiceFault(uint requestId, ServiceResult fault)
        {
            Utils.Trace("Channel {0} Request {1}: SendServiceFault()", ChannelId, requestId);

            BufferCollection chunksToSend = null;

            try
            {
                // construct fault.
                ServiceFault response = new ServiceFault();

                response.ResponseHeader.ServiceResult = fault.Code;

                StringTable stringTable = new StringTable();

                response.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo(
                    fault,
                    DiagnosticsMasks.NoInnerStatus,
                    true,
                    stringTable);

                response.ResponseHeader.StringTable = stringTable.ToArray();

                // serialize fault.
                byte[] buffer = BinaryEncoder.EncodeMessage(response, Quotas.MessageContext);

                // secure message.
                chunksToSend = WriteAsymmetricMessage(
                    TcpMessageType.Open,
                    requestId,
                    ServerCertificate,
                    ClientCertificate,
                    new ArraySegment <byte>(buffer, 0, buffer.Length));

                // write the message to the server.
                BeginWriteMessage(chunksToSend, null);
                chunksToSend = null;
            }
            catch (Exception e)
            {
                if (chunksToSend != null)
                {
                    chunksToSend.Release(BufferManager, "SendServiceFault");
                }

                ForceChannelFault(ServiceResult.Create(e, StatusCodes.BadTcpInternalError, "Unexpected error sending a service fault."));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Returns the data dictionary from cache or disk (updates the data type version as well).
        /// </summary>
        protected virtual byte[] ReadDictionary(double maxAge)
        {
            byte[] dictionary = Value;

            // return cached value.
            if (dictionary != null)
            {
                if (Timestamp.AddMilliseconds(MinimumSamplingInterval) > DateTime.UtcNow)
                {
                    return(dictionary);
                }

                if (Timestamp.AddMilliseconds(maxAge) > DateTime.UtcNow)
                {
                    return(dictionary);
                }

                if (m_assembly != null)
                {
                    return(dictionary);
                }
            }

            // read from source.
            try
            {
                if (m_assembly != null)
                {
                    dictionary = ReadDictionaryFromResource(m_filePath);
                }
                else if (m_filePath.StartsWith(Uri.UriSchemeHttp))
                {
                    dictionary = ReadDictionaryFromHttpFile(m_filePath);
                }
                else
                {
                    dictionary = ReadDictionaryFromDiskFile(m_filePath);
                }

                return(dictionary);
            }
            catch (Exception e)
            {
                ServiceResult error = ServiceResult.Create(e, StatusCodes.BadOutOfService, "Could not access data dictionary file: {0}.", m_filePath);
                UpdateStatus(error);
                return(null);
            }
        }
        private ServiceResult OnWriteEnabled(ISystemContext context, NodeState node, ref object value)
        {
            try
            {
                simulationEnabled_ = (bool)value;

                simulationTimer_.Change(100, simulationEnabled_ ? simulationInterval_ : 0);

                return(ServiceResult.Good);
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Error writing Enabled variable.");
                return(ServiceResult.Create(e, StatusCodes.Bad, "Error writing Enabled variable."));
            }
        }
        /// <summary>
        /// Handle method call to get configured endpoints
        /// </summary>
        private ServiceResult OnGetConfiguredEndpointsCall(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments)
        {
            string logPrefix = "GetConfiguredEndpointsCall:";

            try
            {
                var methodResult = HubCommunication.HandleGetConfiguredEndpointsMethodAsync(new Microsoft.Azure.Devices.Client.MethodRequest("GetConfiguredEndpointsMethod", Encoding.UTF8.GetBytes(inputArguments[0] as string)), null).Result;
                outputArguments[0] = methodResult.ResultAsJson;
            }
            catch (Exception ex)
            {
                Logger.Error($"{logPrefix} The request is invalid!");
                return(ServiceResult.Create(ex, null, StatusCodes.Bad));
            }
            return(ServiceResult.Good);
        }
Esempio n. 6
0
        public async Task <IActionResult> GetCommandDescriptor(string serviceId, string address)
        {
            IEnumerable <ServiceCommandDescriptor> list = null;

            if (!string.IsNullOrEmpty(serviceId))
            {
                list = await ServiceLocator.GetService <IFaultTolerantProvider>().GetCommandDescriptor(serviceId);
            }
            else if (!string.IsNullOrEmpty(address))
            {
                list = await ServiceLocator.GetService <IFaultTolerantProvider>().GetCommandDescriptorByAddress(address);
            }
            var result = ServiceResult <IEnumerable <ServiceCommandDescriptor> > .Create(true, list);

            return(Json(result));
        }
Esempio n. 7
0
        /// <summary>
        /// Sends a fault response secured with the symmetric keys.
        /// </summary>
        private void SendServiceFault(TcpChannelToken token, uint requestId, ServiceResult fault)
        {
            // Utils.Trace("Channel {0} Request {1}: SendServiceFault()", ChannelId, requestId);

            BufferCollection buffers = null;

            try {
                // construct fault.
                ServiceFault response = new ServiceFault();

                response.ResponseHeader.ServiceResult = fault.Code;

                StringTable stringTable = new StringTable();

                response.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo(
                    fault,
                    DiagnosticsMasks.NoInnerStatus,
                    true,
                    stringTable);

                response.ResponseHeader.StringTable = stringTable.ToArray();

                // the limits should never be exceeded when sending a fault.
                bool limitsExceeded = false;

                // secure message.
                buffers = WriteSymmetricMessage(
                    TcpMessageType.Message,
                    requestId,
                    token,
                    response,
                    false,
                    out limitsExceeded);

                // send message.
                BeginWriteMessage(buffers, Int32.MaxValue, null);
                buffers = null;
            } catch (Exception e) {
                if (buffers != null)
                {
                    buffers.Release(BufferManager, "SendServiceFault");
                }

                ForceChannelFault(ServiceResult.Create(e, StatusCodes.BadTcpInternalError,
                                                       "Unexpected error sending a service fault."));
            }
        }
Esempio n. 8
0
        public ServiceResult OnWriteValue(ISystemContext context, NodeState node, ref object value)
        {
            if (context.UserIdentity == null || context.UserIdentity.TokenType == UserTokenType.Anonymous)
            {
                TranslationInfo info = new TranslationInfo(
                    "BadUserAccessDenied",
                    "en-US",
                    "User cannot change value.");

                return(new ServiceResult(StatusCodes.BadUserAccessDenied, new LocalizedText(info)));
            }

            // attempt to update file system.
            try
            {
                string filePath = value as string;
                PropertyState <string> variable = node as PropertyState <string>;

                if (!String.IsNullOrEmpty(variable.Value))
                {
                    FileInfo file = new FileInfo(variable.Value);

                    if (file.Exists)
                    {
                        file.Delete();
                    }
                }

                if (!String.IsNullOrEmpty(filePath))
                {
                    FileInfo file = new FileInfo(filePath);

                    using (StreamWriter writer = file.CreateText())
                    {
                        writer.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
                    }
                }

                value = filePath;
            }
            catch (Exception e)
            {
                return(ServiceResult.Create(e, StatusCodes.BadUserAccessDenied, "Could not update file system."));
            }

            return(ServiceResult.Good);
        }
 //writing value on specific intervals
 private ServiceResult OnWriteInterval(ISystemContext context, NodeState node, ref object value)
 {
     try
     {
         m_simulationInterval = (UInt16)value;
         if (m_simulationEnabled)
         {
             m_simulationTimer.Change(100, (int)m_simulationInterval);
         }
         return(ServiceResult.Good);
     }
     catch (Exception e)
     {
         Utils.Trace(e, "Error writing Interval variable.");
         return(ServiceResult.Create(e, StatusCodes.Bad, "Error writing Interval variable."));
     }
 }
Esempio n. 10
0
        /// <summary>
        /// Data node in the server which registers ourselves with IoT Hub when this node is written to
        /// </summary>
        public ServiceResult ConnectionStringWrite(ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp)
        {
            var connectionString = value as string;

            if (string.IsNullOrEmpty(connectionString))
            {
                Program.Trace("ConnectionStringWrite: Invalid Argument!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments as strings!"));
            }

            statusCode = StatusCodes.Bad;
            timestamp  = DateTime.Now;

            // read current connection string and compare to the one passed in
            string currentConnectionString = SecureIoTHubToken.Read(Program.m_configuration.ApplicationName);

            if (string.Equals(connectionString, currentConnectionString, StringComparison.OrdinalIgnoreCase))
            {
                Program.Trace("ConnectionStringWrite: Connection string up to date!");
                return(ServiceResult.Create(StatusCodes.Bad, "Connection string already up-to-date!"));
            }

            Program.Trace("Attemping to configure publisher with connection string: " + connectionString);

            // configure publisher and write connection string
            try
            {
                DeviceClient newClient = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
                newClient.RetryPolicy = RetryPolicyType.Exponential_Backoff_With_Jitter;
                newClient.OpenAsync().Wait();
                SecureIoTHubToken.Write(Program.m_configuration.ApplicationName, connectionString);
                Program.m_deviceClient = newClient;
            }
            catch (Exception ex)
            {
                statusCode = StatusCodes.Bad;
                Program.Trace("ConnectionStringWrite: Exception: " + ex.ToString());
                return(ServiceResult.Create(StatusCodes.Bad, "Publisher registration failed: " + ex.Message));
            }

            statusCode = StatusCodes.Good;
            Program.Trace("ConnectionStringWrite: Success!");

            return(statusCode);
        }
Esempio n. 11
0
        private (bool, ServiceResult <object>) OnAuthorization(ServiceRoute route, Dictionary <string, object> model)
        {
            bool isSuccess     = true;
            var  serviceResult = ServiceResult <object> .Create(false, null);

            if (route.ServiceDescriptor.EnableAuthorization())
            {
                if (route.ServiceDescriptor.AuthType() == AuthorizationType.JWT.ToString())
                {
                    isSuccess = ValidateJwtAuthentication(route, model, ref serviceResult);
                }
                else
                {
                    isSuccess = ValidateAppSecretAuthentication(route, model, ref serviceResult);
                }
            }
            return(new ValueTuple <bool, ServiceResult <object> >(isSuccess, serviceResult));
        }
Esempio n. 12
0
        public async Task <ServiceResult <object> > Post(string path, string serviceKey, Dictionary <string, object> model)
        {
            model = model ?? new Dictionary <string, object>();
            ServiceResult <object> result = ServiceResult <object> .Create(false, null);

            path = string.IsNullOrEmpty(path) ?
                   GateWayAppConfig.AuthorizationRoutePath : path.ToLower();
            if (OnAuthorization(path, model, ref result))
            {
                if (path == GateWayAppConfig.AuthorizationRoutePath)
                {
                    var token = await _authorizationServerProvider.GenerateTokenCredential(model);

                    if (token != null)
                    {
                        result = ServiceResult <object> .Create(true, token);

                        result.StatusCode = (int)ServiceStatusCode.Success;
                    }
                    else
                    {
                        result = new ServiceResult <object> {
                            IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                        };
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(serviceKey))
                    {
                        result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path, serviceKey));

                        result.StatusCode = (int)ServiceStatusCode.Success;
                    }
                    else
                    {
                        result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path));

                        result.StatusCode = (int)ServiceStatusCode.Success;
                    }
                }
            }
            return(result);
        }
Esempio n. 13
0
        public ServiceResult <Manager> GetManagerById(string id)
        {
            try
            {
                ServiceResult <Manager> result = null;
                var manageId = 0;
                int.TryParse(id, out manageId);
                result = ServiceResult <Manager> .Create(true, _managerService.GetManagerById(manageId));

                return(result);
            }
            catch (ServiceException e)
            {
                var result = ServiceResult <Manager> .Create(false, e.Message, null);

                result.ErrorCode = e.Code;
                return(result);
            }
        }
        private ServiceResult OnWriteInterval(ISystemContext context, NodeState node, ref object value)
        {
            try
            {
                simulationInterval_ = (ushort)value;

                if (simulationEnabled_)
                {
                    simulationTimer_.Change(100, simulationInterval_);
                }

                return(ServiceResult.Good);
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Error writing Interval variable.");
                return(ServiceResult.Create(e, StatusCodes.Bad, "Error writing Interval variable."));
            }
        }
Esempio n. 15
0
        public async Task <(bool, ServiceResult <object>)> ValidateJwtAuthentication(ServiceRoute route, Dictionary <string, object> model)
        {
            var result = ServiceResult <object> .Create(false, null);

            bool isSuccess = true;
            var  author    = HttpContext.Request.Headers["Authorization"];

            if (author.Count > 0)
            {
                isSuccess = await _authorizationServerProvider.ValidateClientAuthentication(author);

                if (!isSuccess)
                {
                    result = new ServiceResult <object> {
                        IsSucceed = false, StatusCode = Surging.Core.CPlatform.Exceptions.StatusCode.UnAuthentication, Message = "Invalid authentication credentials"
                    };
                }
                else
                {
                    var payload = _authorizationServerProvider.GetPayloadString(author);
                    RpcContext.GetContext().SetAttachment("payload", payload);
                    if (model.Count > 0)
                    {
                        var keyValue = model.FirstOrDefault();
                        if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType()))
                        {
                            dynamic instance = keyValue.Value;
                            instance.Payload = payload;
                            model.Remove(keyValue.Key);
                            model.Add(keyValue.Key, instance);
                        }
                    }
                }
            }
            else
            {
                result = new ServiceResult <object> {
                    IsSucceed = false, StatusCode = Surging.Core.CPlatform.Exceptions.StatusCode.RequestError, Message = "Request error"
                };
                isSuccess = false;
            }
            return(isSuccess, result);
        }
        /// <summary>
        /// Called when the alarm is acknowledged.
        /// </summary>
        private ServiceResult OnAcknowledge(
            ISystemContext context,
            MethodState method,
            NodeId objectId,
            byte[] eventId,
            LocalizedText comment)
        {
            ComAeClientManager system = (ComAeClientManager)this.SystemContext.SystemHandle;
            ComAeClient        client = (ComAeClient)system.SelectClient((ServerSystemContext)context, false);

            try
            {
                return(client.Acknowledge((ServerSystemContext)context, eventId, comment));
            }
            catch (Exception e)
            {
                return(ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Could not acknowledge event."));
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Handles a read complete event.
        /// </summary>
        private void OnReadComplete(object sender, SocketAsyncEventArgs e)
        {
            lock (m_readLock)
            {
                ServiceResult error = null;

                try
                {
                    bool innerCall = m_readState == ReadState.ReadComplete;
                    error = DoReadComplete(e);
                    // to avoid recursion, inner calls of OnReadComplete return
                    // after processing the ReadComplete and let the outer call handle it
                    if (!innerCall && !ServiceResult.IsBad(error))
                    {
                        while (ReadNext())
                        {
                            ;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.Trace(ex, "Unexpected error during OnReadComplete,");
                    error = ServiceResult.Create(ex, StatusCodes.BadTcpInternalError, ex.Message);
                }
                finally
                {
                    e?.Dispose();
                }

                if (ServiceResult.IsBad(error))
                {
                    if (m_receiveBuffer != null)
                    {
                        m_bufferManager.ReturnBuffer(m_receiveBuffer, "OnReadComplete");
                        m_receiveBuffer = null;
                    }

                    m_sink?.OnReceiveError(this, error);
                }
            }
        }
Esempio n. 18
0
        private async Task <(bool, ServiceResult <object>)> OnAuthorization(string path, Dictionary <string, object> model)
        {
            bool isSuccess = true;
            var  route     = await _serviceRouteProvider.GetRouteByPath(path);

            var serviceResult = ServiceResult <object> .Create(false, null);

            if (route.ServiceDescriptor.EnableAuthorization())
            {
                if (route.ServiceDescriptor.AuthType() == AuthorizationType.JWT.ToString())
                {
                    isSuccess = ValidateJwtAuthentication(route, model, ref serviceResult);
                }
                else
                {
                    isSuccess = ValidateAppSecretAuthentication(route, path, model, ref serviceResult);
                }
            }
            return(new ValueTuple <bool, ServiceResult <object> >(isSuccess, serviceResult));
        }
Esempio n. 19
0
        /// <summary>
        /// Data node in the server which registers ourselves with IoT Hub when this node is written.
        /// </summary>
        public ServiceResult OnConnectionStringWrite(ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp)
        {
            var connectionString = value as string;

            if (string.IsNullOrEmpty(connectionString))
            {
                Trace("ConnectionStringWrite: Invalid Argument!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments as strings!"));
            }

            statusCode = StatusCodes.Bad;
            timestamp  = DateTime.Now;

            // read current connection string and compare to the one passed in
            string currentConnectionString = SecureIoTHubToken.Read(OpcConfiguration.ApplicationName, IotDeviceCertStoreType, IotDeviceCertStorePath);

            if (string.Equals(connectionString, currentConnectionString, StringComparison.OrdinalIgnoreCase))
            {
                Trace("ConnectionStringWrite: Connection string up to date!");
                return(ServiceResult.Create(StatusCodes.Bad, "Connection string already up-to-date!"));
            }

            Trace($"ConnectionStringWrite: Attempting to configure publisher with connection string: {connectionString}");

            // configure publisher and write connection string
            try
            {
                IotHubCommunication.ConnectionStringWrite(connectionString);
            }
            catch (Exception e)
            {
                statusCode = StatusCodes.Bad;
                Trace(e, $"ConnectionStringWrite: Exception while trying to create IoTHub client and store device connection string in cert store");
                return(ServiceResult.Create(StatusCodes.Bad, "Publisher registration failed: " + e.Message));
            }

            statusCode = StatusCodes.Good;
            Trace("ConnectionStringWrite: Success!");

            return(statusCode);
        }
        /// <summary>
        /// Handle method call to call direct IoTHub methods
        /// </summary>
        private ServiceResult OnIoTHubDirectMethodCall(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments)
        {
            string logPrefix = "OnIoTHubDirectMethodCall:";

            try
            {
                if (string.IsNullOrEmpty(inputArguments[0] as string))
                {
                    string errorMessage = "There is no direct method name specified.";
                    Logger.Error($"{logPrefix} {errorMessage}");
                    return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, errorMessage));
                }

                string methodRequest = string.Empty;
                if ((inputArguments[1] as string) != null)
                {
                    methodRequest = inputArguments[1] as string;
                }

                string methodName = inputArguments[0] as string;
                if (IotHubDirectMethods.ContainsKey(inputArguments[0] as string))
                {
                    var methodCallback = IotHubDirectMethods.GetValueOrDefault(methodName);
                    var methodResponse = methodCallback(new MethodRequest(methodName, Encoding.UTF8.GetBytes(methodRequest)), null).Result;
                    outputArguments[0] = methodResponse.ResultAsJson;
                }
                else
                {
                    var methodCallback = IotHubDirectMethods.GetValueOrDefault(methodName);
                    var methodResponse = DefaultMethodHandlerAsync(new MethodRequest(methodName, Encoding.UTF8.GetBytes(methodRequest)), null).Result;
                    outputArguments[0] = methodResponse.ResultAsJson;
                    return(ServiceResult.Create(StatusCodes.BadNotImplemented, "The IoTHub direct method is not implemented"));
                }
            }
            catch (Exception ex)
            {
                Logger.Error($"{logPrefix} The request is invalid!");
                return(ServiceResult.Create(ex, null, StatusCodes.Bad));
            }
            return(ServiceResult.Good);
        }
Esempio n. 21
0
        private async Task <(bool, ServiceResult <object>)> OnAuthorization(ServiceRoute route, Dictionary <string, object> model)
        {
            var isSuccess     = true;
            var serviceResult = ServiceResult <object> .Create(false, null);

            var result = (isSuccess, serviceResult);

            if (route.ServiceDescriptor.EnableAuthorization())
            {
                if (route.ServiceDescriptor.AuthType() == AuthorizationType.JWT.ToString())
                {
                    result = await ValidateJwtAuthentication(route, model);
                }
                else
                {
                    isSuccess = ValidateAppSecretAuthentication(route, model, ref serviceResult);
                    result    = (isSuccess, serviceResult);
                }
            }
            return(result);
        }
Esempio n. 22
0
        /// <summary cref="IReplyChannel.EndTryReceiveRequest" />
        public bool EndTryReceiveRequest(IAsyncResult result, out System.ServiceModel.Channels.RequestContext context)
        {
            context = null;
            TcpAsyncOperation <RequestContext> operation = (TcpAsyncOperation <RequestContext>)result;

            try
            {
                context = operation.End(Int32.MaxValue);
                return(true);
            }
            catch (TimeoutException)
            {
                return(false);
            }
            catch (Exception e)
            {
                m_fault = ServiceResult.Create(e, StatusCodes.BadInternalError, "Could not receive request from a UA TCP channel.");
                Utils.Trace(m_fault.ToLongString());
                return(false);
            }
        }
Esempio n. 23
0
        public async Task <ServiceResult <object> > Path(string path, [FromQuery] string serviceKey, [FromBody] Dictionary <string, object> model)
        {
            ServiceResult <object> result = ServiceResult <object> .Create(false, null);

            if (OnAuthorization(path, model, ref result))
            {
                if (!string.IsNullOrEmpty(serviceKey))
                {
                    result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path, serviceKey));

                    result.StatusCode = (int)ServiceStatusCode.Success;
                }
                else
                {
                    result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path));

                    result.StatusCode = (int)ServiceStatusCode.Success;
                }
            }
            return(result);
        }
Esempio n. 24
0
        /// <summary>
        /// Write a single message.
        /// </summary>
        private void WriteMessage(WriteOperation operation)
        {
            // get the buffers to write.
            BufferCollection buffers = operation.ChunksToSend;

            // get the socket.
            Socket socket = null;

            lock (m_socketLock)
            {
                socket = m_socket;
            }

            // check if the socket has been closed.
            if (socket == null)
            {
                operation.Fault(ServiceResult.Create(StatusCodes.BadConnectionClosed, "Socket is no longer available."));
                return;
            }

            // begin the write operation (blocks until data is copied into the transport buffer).
            try
            {
                int bytesSent = socket.Send(buffers, SocketFlags.None);

                // check that all the data was sent.
                if (bytesSent < buffers.TotalSize)
                {
                    operation.Fault(ServiceResult.Create(StatusCodes.BadConnectionClosed, "Write operation could not complete."));
                    return;
                }

                // everything ok - yeah!.
                operation.Complete(bytesSent);
            }
            catch (Exception e)
            {
                operation.Fault(ServiceResult.Create(e, StatusCodes.BadConnectionClosed, "Write to socket failed."));
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Handles a write complete event.
        /// </summary>
        protected virtual void OnWriteComplete(object sender, SocketAsyncEventArgs e)
        {
            lock (DataLock)
            {
                ServiceResult error = ServiceResult.Good;

                try
                {
                    if (e.BytesTransferred == 0)
                    {
                        error = ServiceResult.Create(StatusCodes.BadConnectionClosed, "The socket was closed by the remote application.");
                    }

                    HandleWriteComplete(e.UserToken, e.BytesTransferred, error);
                }
                catch (Exception ex)
                {
                    error = ServiceResult.Create(ex, StatusCodes.BadTcpInternalError, "Unexpected error during write operation.");
                    HandleWriteComplete(e.UserToken, e.BytesTransferred, error);
                }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Get an external order
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="supplier"></param>
        /// <returns></returns>
        public async Task <IServiceResult <ExternalOrderResponse> > GetExternalOrderAsync(string orderId, string supplier)
        {
            switch (supplier.ToLower())
            {
            case "digikey":
                if (!_digikeyApi.IsConfigured)
                {
                    throw new InvalidOperationException($"DigiKey Api is not configured!");
                }
                return(await GetExternalDigikeyOrderAsync(orderId));

            case "mouser":
                if (!_mouserApi.IsConfigured)
                {
                    throw new InvalidOperationException($"Mouser Api is not configured!");
                }

                return(ServiceResult <ExternalOrderResponse> .Create(new ExternalOrderResponse()));

            default:
                throw new InvalidOperationException($"Unknown supplier {supplier}");
            }
        }
Esempio n. 27
0
        public ServiceResult Update(BookInfo book)
        {
            var query = _db.Books.FirstOrDefaultAsync(q => q.Id == book.Id);

            if (query.IsCompleted && query.Result == null)
            {
                return(ServiceResult.Error("数据不存在"));
            }
            else
            {
                query.Result.AminId     = book.AminId;
                query.Result.Author     = book.Author;
                query.Result.CoverImage = book.CoverImage;
                query.Result.CreateDT   = book.CreateDT;
                query.Result.Name       = book.Name;
                query.Result.Price      = book.Price;
                query.Result.Publish    = book.Publish;
                query.Result.RealPrice  = book.RealPrice;
                query.Result.SubName    = book.SubName;
                _db.SaveChanges();
                return(ServiceResult.Create(true, "操作成功"));
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Reads an error from a stream.
        /// </summary>
        protected static ServiceResult ReadErrorMessageBody(BinaryDecoder decoder)
        {
            // read the status code.
            uint statusCode = decoder.ReadUInt32(null);

            string reason = null;

            // ensure the reason does not exceed the limits in the protocol.
            int reasonLength = decoder.ReadInt32(null);

            if (reasonLength > 0 && reasonLength < TcpMessageLimits.MaxErrorReasonLength)
            {
                byte[] reasonBytes = new byte[reasonLength];

                for (int ii = 0; ii < reasonLength; ii++)
                {
                    reasonBytes[ii] = decoder.ReadByte(null);
                }

                reason = new UTF8Encoding().GetString(reasonBytes, 0, reasonLength);
            }

            return(ServiceResult.Create(statusCode, "Error received from remote host: {0}", reason));
        }
Esempio n. 29
0
 /// <summary>
 /// Called when an asynchronous operation completes.
 /// </summary>
 public bool Fault(bool doNotBlock, Exception e, uint defaultCode, string format, params object[] args)
 {
     return(InternalComplete(doNotBlock, ServiceResult.Create(e, defaultCode, format, args)));
 }
Esempio n. 30
0
 /// <summary>
 /// Called when an asynchronous operation completes.
 /// </summary>
 public bool Fault(bool doNotBlock, uint code, string format, params object[] args)
 {
     return(InternalComplete(doNotBlock, ServiceResult.Create(code, format, args)));
 }