Beispiel #1
0
 public FileSystemHubTest(IEnvironment environment, ITracer tracer, HubCallerContext context,
                          IGroupManager group, IHubCallerConnectionContext clients) : base(environment, tracer)
 {
     Context = context;
     Groups  = group;
     Clients = clients;
 }
Beispiel #2
0
 internal SignalXRequest(
     string correlationId,
     SignalX signalX,
     string replyTo,
     object sender,
     string messageId,
     string message,
     string user,
     string handler,
     IPrincipal principalUser,
     List <string> groups,
     IRequest request,
     HubCallerContext context,
     IHubCallerConnectionContext <dynamic> clients,
     IGroupManager groupsManager,
     object messageObject)
 {
     this.CorrelationId = correlationId;
     this.Context       = context;
     this.Clients       = clients;
     this.GroupsManager = groupsManager;
     this.SignalX       = signalX ?? throw new ArgumentNullException(nameof(signalX));
     this.ReplyTo       = replyTo;
     this.Sender        = sender;
     this.MessageId     = messageId;
     this.MessageAsJson = message;
     //UserId = principalUser?.Identity?.Name;
     this.User          = user;
     this.Handler       = handler;
     this.PrincipalUser = principalUser;
     this.Groups        = groups ?? new List <string>();
     this.Request       = request;
     this.MessageObject = messageObject;
 }
 public ProcessReportRequestModel(IHubCallerConnectionContext<dynamic> clients, string id, string name, BackgroundWorkerQueue worker)
     : base(clients)
 {
     Id = id;
     Name = name;
     WorkerQueue = worker;
 }
Beispiel #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stopCalled"></param>
        /// <returns></returns>
        public override Task OnDisconnected(bool stopCalled)
        {
            ClientList    = Clients;
            ServerContext = Context;
            if (ConnectionIds.Count > 0)
            {
                KeyValuePair <string, string> tmpconnect = ConnectionIds.FirstOrDefault(a => a.Value == Context.ConnectionId);
                if (tmpconnect.Key != null)
                {
                    int    employeeid = Convert.ToInt32(tmpconnect.Key.Split('@').Last());
                    string companyID  = tmpconnect.Key.Split('@').First();

                    //离线调用数据库更新用户登录状态TODO:
                    //

                    ConnectionIds.Remove(tmpconnect.Key);//删除连接 list 中 当前退出的客户端


                    Dictionary <string, string> resultlist = ConnectionIds.Where(a => chkcompanyID(a.Key, companyID)).ToDictionary(b => b.Key, c => c.Value);
                    if (resultlist.Count > 0)
                    {
                        foreach (var item in resultlist)
                        {
                            ClientList.Client(item.Value).customerloginstatemessage(new { companyID = companyID, employeeid = employeeid, isonline = false });
                        }
                    }
                }
            }
            return(base.OnDisconnected(true));
        }
Beispiel #5
0
        public static async Task RespondToScriptRequest(
            this SignalX signalX,
            string correlationId,
            HubCallerContext context,
            IHubCallerConnectionContext <dynamic> clients,
            IGroupManager groups)
        {
            signalX.Advanced.Trace(correlationId, "Preparing script for client ...");
            signalX.Settings.ConnectionEventsHandler.ForEach(h => h?.Invoke(ConnectionEvents.SignalXRequestForMethods.ToString(), context?.User?.Identity?.Name));
            if (!await signalX.CanProcess(correlationId, context, "", null, true).ConfigureAwait(false))
            {
                signalX.Settings.WarningHandler.ForEach(h => h?.Invoke("RequireAuthentication", "User attempting to connect has not been authenticated when authentication is required"));
                return;
            }

            string logRequestOnClient      = signalX.Settings.LogAgentMessagesOnClient ? signalX.Settings.ClientLogScriptFunction + "(message);" : "";
            string logResponseOnClient     = signalX.Settings.LogAgentMessagesOnClient ? signalX.Settings.ClientLogScriptFunction + "(response);" : "";
            string receiveErrorsFromClient = (signalX.Settings.ReceiveErrorMessagesFromClient
                ? signalX.ClientErrorSnippet
                : "") + (signalX.Settings.ReceiveDebugMessagesFromClient
                ? signalX.ClientDebugSnippet
                : "");
            string clientAgent = @"
                 " + receiveErrorsFromClient + @"
                 signalx.client." + SignalX.SIGNALXCLIENTAGENT + @" = function (message) {
                   " + logRequestOnClient + @"
                   var response ={};
                   try{ response={ Error : '', MessageAsJsonString : JSON.stringify(eval('(function(){ '+message+' })()')) }; }catch(err){  response = {Error : err, MessageAsJsonString :'' }; signalx.error.f({error:err,description:'error occured while evaluating server agent command',context:'server agent error context'});  }
                   " + logResponseOnClient + @"
                    signalx.server." + SignalX.SIGNALXCLIENTAGENT + @"(response,function(messageResponse){  });
                 };";

            string clientReady = signalX.OnClientReady.Count == 0
                ? ""
                : @"
                    signalx.beforeOthersReady=function(f){
                        signalx.debug.f('Checking with server before executing ready functions...')
                        signalx.server." + SignalX.SIGNALXCLIENTREADY + @"('',function(){
                             signalx.debug.f('Server indicates readiness. Now running client ready functions ... ');
                             typeof f ==='function' && f();
                          });
                 }";

            string methods = "; window.signalxidgen=window.signalxidgen||function(){return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);    return v.toString(16);})};" +
                             signalX.SignalXServers.Aggregate(clientReady + clientAgent + "var $sx= {", (current, signalXServer) => current + signalXServer.Key + @":function(m,repTo,sen,msgId){ var deferred = $.Deferred();  window.signalxid=window.signalxid||window.signalxidgen();   sen=sen||window.signalxid;repTo=repTo||''; var messageId=signalx.MESSAGE_ID || window.signalxidgen(); var rt=repTo; if(typeof repTo==='function'){ signalx.waitingList(messageId,repTo);rt=messageId;  }  if(!repTo){ signalx.waitingList(messageId,deferred);rt=messageId;  }  var messageToSend={handler:'" + signalXServer.Key + "',message:m, replyTo:rt,sender:sen, groupList:signalx.groupList};  chat.server.send('" + signalXServer.Key + "',(m && JSON.stringify(m)) ||'',rt,sen,messageId,signalx.groupList||[]); if(repTo){return messageId}else{ return deferred.promise();}   },").Trim()
                             + "}; $sx; ";

            if (signalX.Settings.StartCountingInComingMessages)
            {
                Interlocked.Increment(ref signalX.Settings.InComingCounter);
            }

            signalX.Advanced.Trace(correlationId, "Sending script to client ...");
            signalX.Receiver.ReceiveScripts(correlationId, context?.ConnectionId, methods, context, groups, clients);

            signalX.Settings.ConnectionEventsHandler.ForEach(h => h?.Invoke(ConnectionEvents.SignalXRequestForMethodsCompleted.ToString(), methods));
        }
 public ClientsDatabaseIsolator(string database, IHubCallerConnectionContext <dynamic> clients)
 {
     if (database == null)
     {
         throw new ArgumentNullException(nameof(database));
     }
     this._database = database;
     this._clients  = clients;
 }
        public TradingAgent(string connId, double initialAmount, IHubCallerConnectionContext <IStockTickerHubClient> caller)
        {
            var initialState = new State
            {
                Cash       = initialAmount,
                Portfolio  = new Dictionary <string, TradingDetails>(),
                BuyOrders  = new Dictionary <string, List <TradingDetails> >(),
                SellOrders = new Dictionary <string, List <TradingDetails> >()
            };

            agent = Agent.Start <State, Trading>(initialState,
                                                 (state, message) =>
            {
                if (message is Trading.Kill)
                {
                    throw new NotImplementedException("Kill messages should not be send to Dataflow based Agents");
                }
                else if (message is Trading.Error msgError)
                {
                    throw msgError.Item;
                }
                else if (message is Trading.Buy msgBuy)
                {
                    var items = HelperFunctions.setOrder(state.BuyOrders, msgBuy.symbol, msgBuy.Item2);
                    var order = HelperFunctions.createOrder(msgBuy.symbol, msgBuy.Item2, TradingType.Buy);
                    caller.Client(connId).UpdateOrderBuy(order);
                    state.BuyOrders = items;
                }
                else if (message is Trading.Sell msgSell)
                {
                    var items = HelperFunctions.setOrder(state.SellOrders, msgSell.symbol, msgSell.Item2);
                    var order = HelperFunctions.createOrder(msgSell.symbol, msgSell.Item2, TradingType.Sell);
                    caller.Client(connId).UpdateOrderSell(order);
                    state.SellOrders = items;
                }
                else if (message is Trading.UpdateStock msgStock)
                {
                    caller.Client(connId).UpdateStockPrice(msgStock.Item);

                    var x            = HelperFunctions.updatePortfolio(state.Cash, msgStock.Item, state.Portfolio, state.SellOrders, TradingType.Sell);
                    state.Cash       = x.Item1;
                    state.Portfolio  = x.Item2;
                    state.SellOrders = x.Item3;

                    var y           = HelperFunctions.updatePortfolio(state.Cash, msgStock.Item, state.Portfolio, state.BuyOrders, TradingType.Buy);
                    state.Cash      = y.Item1;
                    state.Portfolio = y.Item2;
                    state.BuyOrders = y.Item3;

                    var asset = HelperFunctions.getUpdatedAsset(state.Portfolio, state.SellOrders, state.BuyOrders, state.Cash);
                    caller.Client(connId).UpdateAsset(asset);
                }
                return(state);
            });
        }
Beispiel #8
0
        public void DisconnectFromTimetable(int doctorId, DateTime date)
        {
            var observerInfo = new ObserverInfo(Context.ConnectionId, date);

            if (TimetableObservers.ContainsKey(doctorId))
            {
                TimetableObservers[doctorId].Remove(observerInfo);
            }

            ConnectionContext = this.Clients;
        }
Beispiel #9
0
 void InitializeFromSignalRIfNecessary()
 {
     if (!isSignalRestInitialized)
     {
         var hubType = GetType();
         var hubName = hubType.GetCustomAttribute <HubNameAttribute>()?.HubName ?? hubType.Name;
         signalRestClients       = new HubConnectionContext(hubName, base.Context.ConnectionId);
         signalRestGroups        = new GroupManager(hubName);
         isSignalRestInitialized = true;
     }
 }
Beispiel #10
0
 public void SendNotification(string name, string message, int userId)
 {
     try
     {
         if (GroupClients == null)
             GroupClients = Clients;
         GroupClients.Group(Convert.ToString(userId)).broadcastMessage(name, message);
     }
     catch (Exception ex)
     {
     }
 }
Beispiel #11
0
        public void MsgProcess(ClientMsgPackEntity value, IHubCallerConnectionContext <dynamic> clients = null, string connectionId = "")
        {
            if (value != null)
            {
                GloableMsgPack gloableMsgPack = JsonUtil <GloableMsgPack> .Deserialize(value.mp_cotent.ToString());

                if (gloableMsgPack != null)
                {
                    clients.All.Push(gloableMsgPack.resdata);
                }
            }
        }
Beispiel #12
0
 internal static void LeaveGroup(
     this SignalX signalX,
     string correlationId,
     HubCallerContext context,
     IHubCallerConnectionContext <dynamic> clients,
     IGroupManager groups,
     string groupName)
 {
     signalX.Advanced.Trace(correlationId, $"User {context?.ConnectionId} is leaving group {groupName}...");
     groups.Remove(context?.ConnectionId, groupName);
     signalX.Settings.ConnectionEventsHandler.ForEach(h => h?.Invoke(ConnectionEvents.SignalXGroupLeave.ToString(), groupName));
     signalX.Receiver.ReceiveInGroupManager(correlationId, "leave", context?.ConnectionId, groupName, context, clients, groups);
 }
Beispiel #13
0
        /// <summary>
        /// 客户端连接维护
        /// </summary>
        /// <param name="value"></param>
        /// <param name="clients"></param>
        /// <param name="connectionId"></param>
        public void MsgProcess(ClientMsgPackEntity value, IHubCallerConnectionContext <dynamic> clients = null, string connectionId = "")
        {
            if (value != null)
            {
                ClientConnMsgPack clientPack = JsonUtil <ClientConnMsgPack> .Deserialize(value.mp_cotent.ToString());

                if (clientPack != null)
                {
                    Parallel.Invoke(
                        () => { AddClientInfo(connectionId, clientPack); },
                        () => { AddClientConnInfo(connectionId, clientPack); }
                        );
                }
            }
        }
Beispiel #14
0
 public async Task SendMessageToServer(
     string correlationId,
     SignalX signalX,
     HubCallerContext context,
     IHubCallerConnectionContext <dynamic> clients,
     IGroupManager groups,
     string handler,
     object message,
     string replyTo,
     object sender,
     string messageId,
     List <string> groupList)
 {
     await signalX.RespondToServer(context ?? signalX.NullHubCallerContext, clients, groups, handler, message, sender, replyTo ?? signalX.NullHubCallerContext.ConnectionId, groupList);
 }
Beispiel #15
0
        public void Setup()
        {
            _fixture = new Fixture()
                       .Customize(new AutoFakeItEasyCustomization());

            _infoQuery          = A.Fake <IInformationQuery>();
            _connectionsManager = A.Fake <IConnectionsManager>();
            _commandProcessor   = A.Fake <ICommandProcessor>();
            _refreshInfo        = A.Fake <IRefreshInformation>();
            _principal          = A.Fake <IPrincipal>();
            _context            = A.Fake <HubCallerContext>();

            _fakeClient  = A.Fake <ICiDashboardHub>();
            _fakeClients = A.Fake <IHubCallerConnectionContext <ICiDashboardHub> >();
        }
        private static ResponseRd SendOrderToStore(OrderModelDto model, IHubCallerConnectionContext <dynamic> clients, CustomerOrder.Order order)
        {
            using (var client = new CustomerOrderClient(new BasicHttpBinding(), new EndpointAddress(model.Store.WsAddress + SettingsData.Constants.StoreOrder.WsCustomerOrder)))
            {
                var iTries = 0;
                while (iTries < 3)
                {
                    try
                    {
                        var result = client.AddOrder(order);
                        if (result.IsSuccess && result.Order.orderIdField.IsValidId())
                        {
                            clients.Caller.OnSendToStoreEventChange(new ResponseMessage
                            {
                                Code      = SettingsData.Constants.StoreConst.STORE_RESPONSE_CALL_WS_SUCCESS,
                                IsSuccess = true,
                                Message   = String.Format("Pedido (ATO ID {0}) enviado de forma exitosa", result.Order.orderIdField)
                            });
                            client.Close();
                            return(result);
                        }

                        var resultOrderId = result.IsSuccess ? result.Order.orderIdField : "ND";

                        SharedLogger.LogError(new Exception(
                                                  String.Format("SendOrderToStore: {0} | {1} | {2} | {3} | {4}", result.IsSuccess, result.ErrMsg, result.ResultCode, result.ResultData))
                                              , model.PosOrder, model.Store, model.Phone, model.OrderDetails, model.OrderToStoreId, resultOrderId);
                    }
                    catch (Exception ex)
                    {
                        SharedLogger.LogError(ex);
                        clients.Caller.OnSendToStoreEventChange(new ResponseMessage
                        {
                            Code      = SettingsData.Constants.StoreConst.STORE_RESPONSE_CALL_WS_ERROR,
                            IsSuccess = false,
                            Message   = String.Format("Intento {0} fallido. Error: {1}", (iTries + 1), ex.Message)
                        });
                    }
                    Thread.Sleep(1000);
                    iTries++;
                }

                client.Close();
            }

            return(null);
        }
Beispiel #17
0
        public void ConnectToTimetable(int doctorId, DateTime date)
        {
            var observerInfo = new ObserverInfo(this.Context.ConnectionId, date);

            TimetableObservers.AddOrUpdate(
                doctorId,
                id => new List <ObserverInfo> {
                observerInfo
            },
                (id, pairs) =>
            {
                pairs.Add(observerInfo);
                return(pairs);
            });

            ConnectionContext = this.Clients;
        }
Beispiel #18
0
        private async Task Publish(CurrencyPairUpdateDto update)
        {
            IHubCallerConnectionContext context = _contextHolder.ReferenceDataHubClients;

            if (context == null)
            {
                return;
            }

            const string groupName = ReferenceDataHub.CurrencyPairUpdateGroupName;

            try
            {
                await context.Group(groupName).OnCurrencyPairUpdate(update);

                Log.InfoFormat("Published currency pair update to group {0}: {1}", groupName, update);
            }
            catch (Exception e)
            {
                Log.Error(
                    string.Format("An error occurred while publishing currency pair update to group {0}: {1}", groupName,
                                  update), e);
            }
        }
Beispiel #19
0
 public void NewSnek(string name)
 {
     Rng = new Random();
     Point start = new Point(Rng.Next(300, 700), Rng.Next(300, 700));
     string color = RandomColor();
     List<SnekPart> pos = new List<SnekPart>()
     {
         new SnekPart() {Color = color, Position = start, Name = name},
         new SnekPart() {Color = color, Position = new Point(start.X - 6, start.Y - 6),},
         new SnekPart() {Color = color, Position = new Point(start.X - 12, start.Y - 12)},
         new SnekPart() {Color = color, Position = new Point(start.X - 18, start.Y - 18)},
         new SnekPart() {Color = color, Position = new Point(start.X - 24, start.Y - 24)},
         new SnekPart() {Color = color, Position = new Point(start.X - 30, start.Y - 30)},
         new SnekPart() {Color = color, Position = new Point(start.X - 36, start.Y - 36)},
         new SnekPart() {Color = color, Position = new Point(start.X - 42, start.Y - 42)},
         new SnekPart() {Color = color, Position = new Point(start.X - 48, start.Y - 48)},
         new SnekPart() {Color = color, Position = new Point(start.X - 54, start.Y - 54)},
         new SnekPart() {Color = color, Position = new Point(start.X - 60, start.Y - 60)},
         new SnekPart() {Color = color, Position = new Point(start.X - 66, start.Y - 66)},
         new SnekPart() {Color = color, Position = new Point(start.X - 72, start.Y - 72)},
         new SnekPart() {Color = color, Position = new Point(start.X - 78, start.Y - 78)},
     };
     lock (Sneks)
     {
         Sneks.Add(new Snake()
         {
             Name = name,
             ConnectionId = Context.ConnectionId,
             Direction = 0,
             Parts = pos,
             Width = 5,
             Color = RandomColor()
         });
     }
     clientsStatic = Clients;
 }
        public void MsgProcess(ClientMsgPackEntity value, IHubCallerConnectionContext <dynamic> clients = null, string connectionId = "")
        {
            Task <bool> ts = new Task <bool>((arg) =>
            {
                bool ret = ConvertUtil.ConvertObjectToBool(arg, false);
                try
                {
                    if (value != null)
                    {
                        NewPushMsgPack newMsgPack = JsonUtil <NewPushMsgPack> .Deserialize(value.mp_cotent.ToString());
                        if (newMsgPack != null)
                        {
                            List <string> connIds = RedisHelper.Hash_Get <List <string> >(Constant.RedisClusterConn, Constant.ClientConnKey, newMsgPack.uid);
                            if (connIds != null && connIds.Any())
                            {
                                if (clients != null)
                                {
                                    clients.Clients(connIds).Push(newMsgPack.resdata);
                                    ret = true;
                                }
                            }
                        }
                    }
                }
                catch { }
                return(ret);
            }, false);

            ts.Start();
            ts.ContinueWith(t =>
            {
                clients.Client(connectionId).Push(ts.Result ? "推送消息到客户端成功!" : "推送消息到客户端失败!");
            });

            clients.Client(connectionId).Push("服务端接受到消息!");
        }
 /// <summary>
 ///     Called by framework
 /// </summary>
 /// <param name="correlationId"></param>
 /// <param name="contextConnectionId"></param>
 /// <param name="methods"></param>
 /// <param name="context"></param>
 /// <param name="groups"></param>
 /// <param name="clients"></param>
 public void ReceiveScripts(string correlationId, string contextConnectionId, string methods, HubCallerContext context, IGroupManager groups, IHubCallerConnectionContext <dynamic> clients)
 {
     clients.Caller?.addMessage(methods);
 }
Beispiel #22
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public override Task OnConnected()
 {
     ClientList    = Clients;
     ServerContext = Context;
     return(base.OnConnected());
 }
Beispiel #23
0
 public void RegisterUser(string userId)
 {
     GroupClients = Clients;
     Groups.Add(Context.ConnectionId, userId);
 }
 protected BaseInformation(IHubCallerConnectionContext<dynamic> clients)
 {
     HubCaller = clients;
 }
 public WebRenderer(IHubCallerConnectionContext<dynamic> hubCallerConnectionContext, Game game, IKingSurvivalData kingSurvivalData)
 {
     this.hubCallerConnectionContext = hubCallerConnectionContext;
     this.game = game;
     this.data = kingSurvivalData;
 }
 public void Subscribe(string id, float initialAmount, IHubCallerConnectionContext <IStockTickerHubClient> caller)
 => coordinatorAgent.Post(CoordinatorMessage.NewSubscribe(id, initialAmount, caller));
Beispiel #27
0
        public void SendToSignalRClient(IHubCallerConnectionContext <dynamic> Clients)
        {
            CallerContext = Clients;

            spawnWatcher();
        }
 public void NotifyDeleteSms(SmsDTO smsDTO, IHubCallerConnectionContext <dynamic> clients)
 {
     clients.All.notifyDeleteSms(smsDTO);
     clients.All.notifyChangeToCharts();
 }
 /// <summary>
 ///     Notifies client using its callback that the group has been added successfully
 ///     signalx.groups.join(name, callback : function(groupName){ })
 /// </summary>
 /// <param name="correlationId"></param>
 /// <param name="operation"></param>
 /// <param name="userId"></param>
 /// <param name="groupName"></param>
 /// <param name="context"></param>
 /// <param name="clients"></param>
 /// <param name="groups"></param>
 public void ReceiveInGroupManager(string correlationId, string operation, string userId, string groupName, HubCallerContext context, IHubCallerConnectionContext <dynamic> clients, IGroupManager groups)
 {
     clients.Caller?.groupManager(groupName, operation);
 }
 public FileSystemHubTest(IEnvironment environment, ITracer tracer, HubCallerContext context,
     IGroupManager group, IHubCallerConnectionContext clients) : base(environment, tracer)
 {
     Context = context;
     Groups = group;
     Clients = clients;
 }
 public ProcessDataRequestModel(IHubCallerConnectionContext<dynamic> clients)
     : base(clients)
 {
 }
        private void SendOrderToStoreEvent(OrderModelDto model, IHubCallerConnectionContext <dynamic> clients)
        {
            try
            {
                if (StoreIsAlive(model) == false)
                {
                    clients.Caller.OnSendToStoreEventChange(new ResponseMessage
                    {
                        Code      = SettingsData.Constants.StoreConst.STORE_RESPONSE_PING_ERROR,
                        IsSuccess = false,
                        Message   = String.Format("La sucursal se encuentra fuera de línea, intente de nuevo por favor o reporte a su supervisor")
                    });

                    return;
                }

                clients.Caller.OnSendToStoreEventChange(new ResponseMessage
                {
                    Code      = SettingsData.Constants.StoreConst.STORE_RESPONSE_PING_OK,
                    IsSuccess = true,
                    Message   = String.Format("La sucursal está en línea, se continua con el envío del pedido")
                });


                var order    = GenerateCustomerOrder(model);
                var response = SendOrderToStore(model, clients, order);

                if (response == null)
                {
                    clients.Caller.OnSendToStoreEventChange(new ResponseMessage
                    {
                        Code      = SettingsData.Constants.StoreConst.STORE_RESPONSE_FAILURE,
                        IsSuccess = true,
                        Message   = String.Format("Después de varios intentos no fue posible enviar el pedido a la sucursal. Por favor intente de nuevo o reporte a su supervisor")
                    });
                    return;
                }


                clients.Caller.OnSendToStoreEventChange(new ResponseMessage
                {
                    Code      = SettingsData.Constants.StoreConst.STORE_RESPONSE_ORDER_OK,
                    IsSuccess = true,
                    Message   = String.Format("El pedido se ha enviado a la sucursal de forma exitosa.{0}# del pedido en la sucursal: {1}" +
                                              "{0}Fecha y tiempo estimado de llegada {2:F}",
                                              Environment.NewLine, response.Order.orderIdField, response.Order.promiseTimeField.ToDateTimeSafe())
                });

                SaveRecurrence(model);
                SaveOrderStatus(model, response);
            }
            catch (Exception ex)
            {
                clients.Caller.OnSendToStoreEventChange(new ResponseMessage
                {
                    Code      = SettingsData.Constants.StoreConst.STORE_RESPONSE_ORDER_ERROR,
                    IsSuccess = false,
                    Message   = String.Format("Error al procesar el pedido: {0}", ex.Message)
                });
            }
        }
Beispiel #33
0
 public SocketItem(string ConnectionId, TransferParam param, IHubCallerConnectionContext <dynamic> Clients)
 {
     this.ConnectionId = ConnectionId;
     this.param        = param;
     this.Clients      = Clients;
 }
        public ResponseMessageData <OrderModelDto> SendOrderToStore(OrderModelDto model, IHubCallerConnectionContext <dynamic> clients)
        {
            var responseCod = new AccountService().IsValidInfoServer();
            var response    = responseCod.DeserializeAndDecrypt <ConnectionInfoResponse>();
            var resMsg      = new ResponseMessageData <OrderModelDto>();

            if (response.NxWn != SharedConstants.Client.STATUS_SCREEN_LOGIN)
            {
                resMsg.IsSuccess = false;
                resMsg.Message   = response.Msg;
                return(resMsg);
            }


            using (_repositoryStore)
            {
                var store = model.Store;

                //var store = FactoryAddress.GetQueryToSearchStore(_repositoryStore.InnerDbEntities, model.FranchiseCode, model.AddressInfo, out franchiseId);
                //TODO Falta verificar si tiene la capacidad para albergar una orden más

                if (store == null || store.IdKey.HasValue == false)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message   = "No se encontró una sucursal cercana a este domicilio, por favor reporte a soporte técnico";
                    return(resMsg);
                }

                var franchiseId = _repositoryStore.GetFranchiseIdByStoreId((int)store.IdKey.Value);

                model.Store       = store;
                model.FranchiseId = franchiseId;
                model.UserId      = AccountRepository.GetIdByUsername(model.Username, _repositoryStore.InnerDbEntities);
                _repositoryStore.SaveOrderToStore(model);

                var offline = _repositoryStore.IsStoreOnline((int)store.IdKey.Value, DateTime.UtcNow);

                if (offline != null)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message   = GetMessageStoreOffline(offline, store);
                    return(resMsg);
                }
            }

            Task.Run(() => SendOrderToStoreEvent(model, clients));

            resMsg.Data      = model;
            resMsg.IsSuccess = true;

            return(resMsg);
        }
 public async Task RequestScripts(SignalX SignalX, HubCallerContext context, IHubCallerConnectionContext <dynamic> clients, IGroupManager groups, string correlationId)
 {
     correlationId = correlationId ?? Guid.NewGuid().ToString();
     await SignalX.RespondToScriptRequest(correlationId, context, clients, groups).ConfigureAwait(false);
 }
Beispiel #36
0
 public TypedHubCallerConnectionContext(IHubCallerConnectionContext <dynamic> dynamicContext)
     : base(dynamicContext)
 {
     _dynamicContext = dynamicContext;
 }
 /// <summary>
 ///     Call this to send message to server
 /// </summary>
 /// <param name="correlationId"></param>
 /// <param name="SignalX"></param>
 /// <param name="context"></param>
 /// <param name="clients"></param>
 /// <param name="groups"></param>
 /// <param name="handler"></param>
 /// <param name="message"></param>
 /// <param name="replyTo"></param>
 /// <param name="sender"></param>
 /// <param name="messageId"></param>
 /// <param name="groupList"></param>
 public async Task SendMessageToServer(string correlationId, SignalX SignalX, HubCallerContext context, IHubCallerConnectionContext <dynamic> clients, IGroupManager groups, string handler, object message, string replyTo, object sender, string messageId, List <string> groupList)
 {
     await SignalX.SendMessageToServer(correlationId, context, clients, groups, handler, message?.ToString(), replyTo, sender, messageId, groupList, false, message);
 }