示例#1
0
        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                if (IsGrpcGatewayRequest(httpContext))
                {
                    if (!IsAllowedMethod(httpContext))
                    {
                        httpContext.Response.Clear();
                        httpContext.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                        return;
                    }

                    string body;
                    using (var sr = new StreamReader(httpContext.Request.Body, Encoding.UTF8))
                        body = sr.ReadToEnd();

                    if (string.IsNullOrWhiteSpace(body))
                    {
                        body = "[]";
                    }

                    var lastIndexOf = httpContext.Request.Path.Value.LastIndexOf('/') + 1;
                    var key         = new StringSegment(httpContext.Request.Path.Value, lastIndexOf, httpContext.Request.Path.Value.Length - lastIndexOf);

                    var metadata = new Metadata();
                    foreach (var header in httpContext.Request.Headers)
                    {
                        metadata.Add(header.Key, header.Value);
                    }

                    var client = new CacheServiceClient(_channel);

                    object response;
                    if (HttpMethods.IsGet(httpContext.Request.Method))
                    {
                        response = await client.GetAsync(new GetRequest { Key = key.ToString() }, new CallOptions().WithHeaders(metadata));
                    }
                    else
                    {
                        response = await client.SetAsync(JsonConvert.DeserializeObject <SetRequest>(body), new CallOptions().WithHeaders(metadata));
                    }

                    var responseBody = JsonConvert.SerializeObject(response, new[] { new Newtonsoft.Json.Converters.StringEnumConverter() });
                    httpContext.Response.ContentType = "application/json";
                    await httpContext.Response.WriteAsync(responseBody);

                    return;
                }
                else
                {
                    await _next(httpContext);
                }
            }
            catch (Exception ex)
            {
                httpContext.Response.StatusCode = 500;
                await httpContext.Response.WriteAsync(ex.ToString());
            }
        }
示例#2
0
文件: Cache.cs 项目: nittikkin/hoc
        private CacheServiceClient GetCacheServiceClient(string key)
        {
            Node node = _nodeResolver.GetObjectLocation(key);
            CacheServiceClient serviceClient;

            if (!(dictionaryList.TryGetValue(node.EndPoint.ToString(), out serviceClient)))
            {
                string endPoint = string.Format("net.tcp://{0}:{1}/HoCCacheService", node.EndPoint.ToString(), node.ServicePort);
                serviceClient = new CacheServiceClient(new NetTcpBinding(SecurityMode.None), new EndpointAddress(endPoint));
                //serviceClient = new CacheServiceClient(new NetTcpBinding(), new EndpointAddress(endPoint));
                serviceClient.Open();
                dictionaryList.Add(node.EndPoint.ToString(), serviceClient);
            }

            return(serviceClient);
        }
示例#3
0
        private static async Task GeneratedClientExample(CallInvoker invoker)
        {
            var client = new CacheServiceClient(invoker);

            try
            {
                await client.SetAsync(new SetRequest
                {
                    Key   = "ClientDemo",
                    Value = ByteString.CopyFrom("ClientDemo", Encoding.UTF8)
                }, options : new CallOptions().WithDeadline(DateTime.UtcNow.AddSeconds(2)));

                var response = await client.GetAsync(new GetRequest
                {
                    Key = "ClientDemo",
                }, options : new CallOptions().WithDeadline(DateTime.UtcNow.AddSeconds(2)));

                Logger.Info("Get by key pattern 'Client'");

                using (var stream = client.GetByKeyPattern(new GetByKeyPatternRequest
                {
                    Pattern = "Client",
                }, options: new CallOptions().WithDeadline(DateTime.UtcNow.AddSeconds(5))))
                {
                    while (await stream.ResponseStream.MoveNext())
                    {
                        var current = stream.ResponseStream.Current;
                        Logger.Info($"Got key '{current.Key}' with value '{current.Value.ToStringUtf8()}'");
                    }
                };
            }
            catch (RpcException ex)
            {
                Logger.Error(ex, "Error setting key: 'ClientDemo'");
            }
        }
        public CacheController(NMSWrapper nmsWrapper, WebSocketServerWrapper wssWrapper, UserManager userManager)
        {
            _tiplocs = _tiplocRepository.GetTiplocs().ToList();

            _userManager = userManager;
            nmsWrapper.FeedDataRecieved += (s, f) =>
            {
                Task.Run(() =>
                     {
                         switch (f.Source)
                         {
                             case Common.Feed.TrainMovement:
                                 ICollection<ITrainData> data = new List<ITrainData>(32);
                                 foreach (var message in f.Data)
                                 {
                                     switch (byte.Parse((string)message.header.msg_type))
                                     {
                                         // activation
                                         case 1:
                                             data.Add(CacheActivation(message.body));
                                             break;

                                         // cancellation
                                         case 2:
                                             data.Add(CacheTrainCancellation((string)message.body.train_id, message.body));
                                             break;

                                         // train movement
                                         case 3:
                                             data.Add(CacheTrainMovement((string)message.body.train_id, message.body));
                                             break;

                                         // unidentified train
                                         case 4:
                                             break;

                                         // train reinstatement
                                         case 5:
                                             data.Add(CacheTrainReinstatement((string)message.body.train_id, message.body));
                                             break;

                                         // train change of origin
                                         case 6:
                                             data.Add(CacheChangeOfOrigin((string)message.body.train_id, message.body));
                                             break;

                                         // train change of identity
                                         case 7:
                                             break;

                                         // train change of location
                                         case 8:
                                             break;
                                     }
                                 }
                                 data = data.Where(d => d != null)
                                     .ToList();
                                 if (data.Any())
                                 {
                                     lock (_cacheLock)
                                     {
                                         CacheServiceClient cacheService = null;
                                         try
                                         {
                                             cacheService = new CacheServiceClient();
                                             cacheService.Open();
                                             cacheService.CacheTrainData(data);
                                         }
                                         finally
                                         {
                                             try
                                             {
                                                 if (cacheService != null)
                                                     cacheService.Close();
                                             }
                                             catch (CommunicationObjectFaultedException e)
                                             {
                                                 Trace.TraceError("Error Closing Cache Connection: {0}", e);
                                             }
                                         }
                                     }
                                 }
                                 break;
                             case Common.Feed.TrainDescriber:
                                 ICollection<TrainDescriber> tdData = new List<TrainDescriber>(32);
                                 foreach (var message in f.Data)
                                 {
                                     tdData.Add(TrainDescriberMapper.MapFromBody(message));
                                 }
                                 tdData = tdData.Where(d => d != null)
                                     .ToList();

                                 if (tdData.Any())
                                 {
                                     TDCacheServiceClient cacheService = null;
                                     try
                                     {
                                         cacheService = new TDCacheServiceClient();
                                         cacheService.Open();
                                         cacheService.CacheTrainDescriberData(tdData);
                                     }
                                     catch (Exception e)
                                     {
                                         Trace.TraceError("Error In Cache Connection: {0}", e);
                                     }
                                     finally
                                     {
                                         try
                                         {
                                             if (cacheService != null)
                                                 cacheService.Close();
                                         }
                                         catch (CommunicationObjectFaultedException e)
                                         {
                                             Trace.TraceError("Error Closing Cache Connection: {0}", e);
                                         }
                                     }
                                 }
                                 break;

                             case Common.Feed.VSTP:

                                 ScheduleTrain train = null;
                                 try
                                 {
                                     train = VSTPMapper.ParseJsonVSTP(f.Data, _tiplocs);
                                 }
                                 catch (TiplocNotFoundException tnfe)
                                 {
                                     Trace.TraceError("Could not add VSTP: {0}", tnfe);
                                 }
                                 catch (Exception e)
                                 {
                                     Trace.TraceError("Could not add VSTP: {0}", e);
                                 }

                                 if (train != null)
                                 {
                                     CacheServiceClient cacheService = null;
                                     try
                                     {
                                         cacheService = new CacheServiceClient();
                                         cacheService.Open();
                                         cacheService.CacheVSTPSchedule(train);
                                     }
                                     catch (Exception e)
                                     {
                                         Trace.TraceError("Error In Cache Connection: {0}", e);
                                     }
                                     finally
                                     {
                                         try
                                         {
                                             if (cacheService != null)
                                                 cacheService.Close();
                                         }
                                         catch (CommunicationObjectFaultedException e)
                                         {
                                             Trace.TraceError("Error Closing Cache Connection: {0}", e);
                                         }
                                     }
                                 }

                                 break;

                             case Common.Feed.RtPPM:
                                 RtppmData ppmData = null;
                                 try
                                 {
                                     ppmData = PPMJsonMapper.ParsePPMData(f.Data.RTPPMDataMsgV1.RTPPMData);
                                 }
                                 catch (Exception e)
                                 {
                                     Trace.TraceError("Could not add PPM Data: {0}", e);
                                 }
                                 if (ppmData != null)
                                 {
                                     CacheServiceClient cacheService = null;
                                     try
                                     {
                                         cacheService = new CacheServiceClient();
                                         cacheService.Open();
                                         cacheService.CachePPMData(ppmData);
                                     }
                                     catch (Exception e)
                                     {
                                         Trace.TraceError("Error In Cache Connection: {0}", e);
                                     }
                                     finally
                                     {
                                         try
                                         {
                                             if (cacheService != null)
                                                 cacheService.Close();
                                         }
                                         catch (CommunicationObjectFaultedException e)
                                         {
                                             Trace.TraceError("Error Closing Cache Connection: {0}", e);
                                         }
                                     }
                                 }
                                 break;
                         }
                     });
            };

            wssWrapper.OnReceive += (s, context) =>
            {
                string command = context.UserContext.DataFrame.ToString();
                int idx = command.IndexOf(':');
                if (idx != -1)
                {
                    string cmdText = new string(command.Take(idx).ToArray());
                    string args = new string(command.Skip(idx + 1).ToArray());
                    switch (cmdText)
                    {
                        case "substanox":
                            HandleSubStanoxCommand(context, args, true);
                            break;
                        case "unsubstanox":
                            HandleSubStanoxCommand(context, args, false);
                            break;
                    }
                }
            };
        }
示例#5
0
文件: Cache.cs 项目: nittikkin/hoc
        private CacheServiceClient GetCacheServiceClient(string key)
        {
            Node node = _nodeResolver.GetObjectLocation(key);
            CacheServiceClient serviceClient;

            if (!(dictionaryList.TryGetValue(node.EndPoint.ToString(), out serviceClient)))
            {
                string endPoint = string.Format("net.tcp://{0}:{1}/HoCCacheService", node.EndPoint.ToString(), node.ServicePort);
                serviceClient = new CacheServiceClient(new NetTcpBinding(SecurityMode.None), new EndpointAddress(endPoint));
                //serviceClient = new CacheServiceClient(new NetTcpBinding(), new EndpointAddress(endPoint));
                serviceClient.Open();
                dictionaryList.Add(node.EndPoint.ToString(), serviceClient);
            }

            return serviceClient;
        }