示例#1
0
        //登录方法
        public ActionResult LoginFunction(Base_User u)
        {
            ErrorResult err = new ErrorResult();

            try
            {
                string    pwd   = Util.Extention.ToMD5String(u.Password);
                Base_User findu = userinfo.GetList().Where(find => find.UserName == u.UserName && find.Password == pwd).FirstOrDefault();
                if (findu != null)
                {
                    SessionHelper.Session["UserId"] = findu.UserId;
                    err.Success = true;
                    err.Msg     = "登陆成功!";
                    err.Data    = "/Base_SysManage/Base_SysMenu/Index";
                    return(Json(err, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    err.Msg = "用户名或密码错误";
                }
            }
            catch (Exception ex)
            {
                BusHelper.WriteSysLog(ex.Message, EnumType.LogType.系统异常);
            }
            return(Json(err, JsonRequestBehavior.AllowGet));
        }
示例#2
0
        public virtual void DefaultReceiveCommand(ICommand <TAuthenticationToken> command, RouteManager routeManager, string framework)
        {
            Type commandType = command.GetType();

            if (command.Frameworks != null && command.Frameworks.Contains(framework))
            {
                Logger.LogInfo("The provided command has already been processed in Azure.", string.Format("{0}\\DefaultReceiveCommand({1})", GetType().FullName, commandType.FullName));
                return;
            }

            CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);

            bool isRequired = BusHelper.IsEventRequired(commandType);

            RouteHandlerDelegate commandHandler = routeManager.GetSingleHandler(command, isRequired);

            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (commandHandler == null)
            {
                Logger.LogDebug(string.Format("The command handler for '{0}' is not required.", commandType.FullName));
                return;
            }

            Action <IMessage> handler = commandHandler.Delegate;

            handler(command);
        }
示例#3
0
        /// <summary>
        /// Action执行完毕之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            try
            {
                //判断是否需要登录
                List <string> attrList  = FilterHelper.GetFilterList(filterContext);
                bool          needLogin = attrList.Contains(typeof(CheckLoginAttribute).FullName) && !attrList.Contains(typeof(IgnoreLoginAttribute).FullName);

                //转到登录
                if (needLogin && !Operator.Logged())
                {
                    RedirectToLogin();
                }
            }
            catch (Exception ex)
            {
                BusHelper.HandleException(ex);
                RedirectToLogin();
            }

            void RedirectToLogin()
            {
                filterContext.Result = new ContentResult
                {
                    Content = new AjaxResult {
                        Success = false, Code = 401, Msg = "未登录"
                    }.ToJson(),
                    ContentType = "application/json;charset=UTF-8"
                };
            }
        }
示例#4
0
 /// <summary>
 /// Subscribes to recieve published messages of type T.
 /// This method is only necessary if you turned off auto-subscribe
 /// </summary>
 /// <param name="type">The type to subscribe</param>
 public void Subscribe(Type type)
 {
     Guard.ArgumentNotNull(type, "type");
     logger.Info("Subscribe={0}", type.FullName);
     subscribedTypes.Add(type);
     BusHelper.SubscribeOrUnsubscribeType((s) => { logger.Info(s); }, type, config, receiver.CreateSubscription);
 }
示例#5
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.RequestContext.HttpContext.Request;

            try
            {
                //若为本地测试,则不需要登录
                if (GlobalSwitch.RunModel == RunModel.LocalTest)
                {
                    return;
                }
                //判断是否需要登录
                bool needLogin = filterContext.ContainsAttribute <CheckLoginAttribute>() && !filterContext.ContainsAttribute <IgnoreLoginAttribute>();

                //转到登录
                if (needLogin && !Operator.Logged())
                {
                    RedirectToLogin();
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                BusHelper.HandleException(ex);
                RedirectToLogin();
            }

            void RedirectToLogin()
            {
                if (request.IsAjaxRequest())
                {
                    filterContext.Result = new ContentResult
                    {
                        Content = new AjaxResult {
                            Success = false, ErrorCode = 1, Msg = "未登录"
                        }.ToJson(),
                        ContentEncoding = Encoding.UTF8,
                        ContentType     = "application/json"
                    };
                }
                else
                {
                    UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
                    string    loginUrl  = urlHelper.Content("~/Home/Login");
                    string    script    = $@"    
<html>
    <script>
        top.location.href = '{loginUrl}';
    </script>
</html>
";
                    filterContext.Result = new ContentResult {
                        Content = script, ContentType = "text/html", ContentEncoding = Encoding.UTF8
                    };
                }
            }
        }
        private static void SendMessages()
        {
            var helper      = new BusHelper();
            var queueClient = helper.CreateQueueClient();
            var topicClient = helper.CreateTopicClient();
            var messages    = CreateQueueMessages(50, CreateMessagePayload());

            Console.WriteLine("\nSending messages to Queue...");
            var rand = new Random(1000);

            foreach (var message in messages)
            {
                try
                {
                    var topicMessage = message.Clone();
                    //for simplicity clone the message and send the event
                    topicClient.Send(topicMessage);
                    queueClient.Send(message);
                }
                catch (MessagingException e)
                {
                    if (!e.IsTransient)
                    {
                        Console.WriteLine(e.Message);
                        throw;
                    }
                    HandleTransientErrors(e);
                }
                Console.WriteLine($"Message received: Id = {message.MessageId} ApplicationType = {message.Properties[Constants.CustomProperties.ApplicationType.ToString()]}");
                // sleep for a short period of time
                Thread.Sleep(rand.Next(500, 2000));
            }
        }
示例#7
0
 /// <summary>
 /// Applies the stored ReceiverMessageHandler and ReceiverMessageHandlerOptions to all receivers in
 /// <see cref="PrivateServiceBusReceivers"/> and <see cref="PublicServiceBusReceivers"/>.
 /// </summary>
 protected override void ApplyReceiverMessageHandler()
 {
     foreach (SubscriptionClient serviceBusReceiver in PrivateServiceBusReceivers.Values)
     {
         serviceBusReceiver
         .OnMessage
         (
             message =>
         {
             BusHelper.SetWasPrivateBusUsed(true);
             ReceiverMessageHandler(message);
         },
             ReceiverMessageHandlerOptions
         );
     }
     foreach (SubscriptionClient serviceBusReceiver in PublicServiceBusReceivers.Values)
     {
         serviceBusReceiver
         .OnMessage
         (
             message =>
         {
             BusHelper.SetWasPrivateBusUsed(false);
             ReceiverMessageHandler(message);
         },
             ReceiverMessageHandlerOptions
         );
     }
 }
示例#8
0
        public virtual void ReceiveEvent(IEvent <TAuthenticationToken> @event)
        {
            switch (@event.Framework)
            {
            case FrameworkType.Akka:
                Logger.LogInfo(string.Format("An event arrived of the type '{0}' but was marked as coming from the '{1}' framework, so it was dropped.", @event.GetType().FullName, @event.Framework));
                return;
            }

            CorrelationIdHelper.SetCorrelationId(@event.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(@event.AuthenticationToken);

            Type eventType  = @event.GetType();
            bool isRequired = BusHelper.IsEventRequired(eventType);

            IEnumerable <Action <IMessage> > handlers = Routes.GetHandlers(@event, isRequired).Select(x => x.Delegate).ToList();

            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (!handlers.Any())
            {
                Logger.LogDebug(string.Format("The event handler for '{0}' is not required.", eventType.FullName));
            }

            foreach (Action <IMessage> handler in handlers)
            {
                handler(@event);
            }
        }
示例#9
0
        private static void ReceiveMessages()
        {
            Console.WriteLine("\nReceiving message from Queue...");
            Console.WriteLine($"Connectionstring = {CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString")}");
            var helper      = new BusHelper();
            var queueClient = helper.CreateQueueClient();

            queueClient.OnMessage(message =>
            {
                try
                {
                    var body = message.GetBody <Applicant>();

                    Console.WriteLine(
                        $"Message received: Id = {message.MessageId}; Custom Property={message.Properties[Constants.CustomProperties.Custom1.ToString()]}; Body = {body}");
                    message.Complete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    message.Abandon();
                }
            }, new OnMessageOptions
            {
                AutoComplete = false
            });
        }
示例#10
0
        /// <summary>
        /// The default command handler that
        /// check if the <see cref="ICommand{TAuthenticationToken}"/> has already been processed by this framework,
        /// checks if the <see cref="ICommand{TAuthenticationToken}"/> is required,
        /// finds the handler from the provided <paramref name="routeManager"/>.
        /// </summary>
        /// <param name="command">The <see cref="ICommand{TAuthenticationToken}"/> to process.</param>
        /// <param name="routeManager">The <see cref="RouteManager"/> to get the <see cref="ICommandHandler{TAuthenticationToken,TCommand}"/> from.</param>
        /// <param name="framework">The current framework.</param>
        /// <returns>
        /// True indicates the <paramref name="command"/> was successfully handled by a handler.
        /// False indicates the <paramref name="command"/> wasn't handled, but didn't throw an error, so by convention, that means it was skipped.
        /// Null indicates the command<paramref name="command"/> wasn't handled as it was already handled.
        /// </returns>
        public virtual bool?DefaultReceiveCommand(ICommand <TAuthenticationToken> command, RouteManager routeManager, string framework)
        {
            Type commandType = command.GetType();

            if (command.Frameworks != null && command.Frameworks.Contains(framework))
            {
                // if this is the only framework in the list, then it's fine to handle as it's just pre-stamped, if there is more than one framework, then exit.
                if (command.Frameworks.Count() != 1)
                {
                    Logger.LogInfo("The provided command has already been processed in Azure.", string.Format("{0}\\DefaultReceiveCommand({1})", GetType().FullName, commandType.FullName));
                    return(null);
                }
            }

            CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);

            bool isRequired = BusHelper.IsEventRequired(commandType);

            RouteHandlerDelegate commandHandler = routeManager.GetSingleHandler(command, isRequired);

            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (commandHandler == null)
            {
                Logger.LogDebug(string.Format("The command handler for '{0}' is not required.", commandType.FullName));
                return(false);
            }

            Action <IMessage> handler = commandHandler.Delegate;

            handler(command);
            return(true);
        }
示例#11
0
        /// <summary>
        /// The default event handler that
        /// check if the <see cref="IEvent{TAuthenticationToken}"/> has already been processed by this framework,
        /// checks if the <see cref="IEvent{TAuthenticationToken}"/> is required,
        /// finds the handler from the provided <paramref name="routeManager"/>.
        /// </summary>
        /// <param name="event">The <see cref="IEvent{TAuthenticationToken}"/> to process.</param>
        /// <param name="routeManager">The <see cref="RouteManager"/> to get the <see cref="IEventHandler{TAuthenticationToken,TCommand}"/> from.</param>
        /// <param name="framework">The current framework.</param>
        /// <returns>
        /// True indicates the <paramref name="event"/> was successfully handled by a handler.
        /// False indicates the <paramref name="event"/> wasn't handled, but didn't throw an error, so by convention, that means it was skipped.
        /// Null indicates the <paramref name="event"/> wasn't handled as it was already handled.
        /// </returns>
        public virtual bool?DefaultReceiveEvent(IEvent <TAuthenticationToken> @event, RouteManager routeManager, string framework)
        {
            Type eventType = @event.GetType();

            if (@event.Frameworks != null && @event.Frameworks.Contains(framework))
            {
                // if this is the only framework in the list, then it's fine to handle as it's just pre-stamped, if there is more than one framework, then exit.
                if (@event.Frameworks.Count() != 1)
                {
                    Logger.LogInfo("The provided event has already been processed in Azure.", string.Format("{0}\\DefaultReceiveEvent({1})", GetType().FullName, eventType.FullName));
                    return(null);
                }
            }

            CorrelationIdHelper.SetCorrelationId(@event.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(@event.AuthenticationToken);

            bool isRequired = BusHelper.IsEventRequired(eventType);

            IEnumerable <Action <IMessage> > handlers = routeManager.GetHandlers(@event, isRequired).Select(x => x.Delegate).ToList();

            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (!handlers.Any())
            {
                Logger.LogDebug(string.Format("The event handler for '{0}' is not required.", eventType.FullName));
                return(false);
            }

            foreach (Action <IMessage> handler in handlers)
            {
                handler(@event);
            }
            return(true);
        }
示例#12
0
        public void GetBusIdWithLowestWaitTimeTest()
        {
            // For example, suppose you have the following notes:
            // 939
            // 7,13,x,x,59,x,31,19
            // Here, the earliest timestamp you could depart is 939, and the
            // bus IDs in service are 7, 13, 59, 31, and 19.
            // The earliest bus you could take is bus ID 59. It doesn't depart
            // until timestamp 944, so you would need to wait 944 - 939 = 5
            // minutes before it departs. Multiplying the bus ID by the number
            // of minutes you'd need to wait gives 295.
            var testData = new List <Tuple <string, string, Tuple <int, int> > >()
            {
                new Tuple <string, string, Tuple <int, int> >(
                    "939",
                    "7,13,x,x,59,x,31,19",
                    new Tuple <int, int>(59, 5))
            };

            foreach (var testExample in testData)
            {
                var busData = BusHelper.ParseInputLines(testExample.Item1, testExample.Item2);
                var actual  = BusHelper.GetBusIdWithLowestWaitTime(busData);
                Assert.Equal(testExample.Item3, actual);
            }
        }
示例#13
0
        public virtual bool PrepareAndValidateEvent <TEvent>(TEvent @event, string framework, out IEnumerable <RouteHandlerDelegate> handlers)
            where TEvent : IEvent <TAuthenticationToken>
        {
            Type eventType = @event.GetType();

            if (@event.Frameworks != null && @event.Frameworks.Contains(framework))
            {
                Logger.LogInfo("The provided event has already been processed in Akka.", string.Format("{0}\\PrepareAndValidateEvent({1})", GetType().FullName, eventType.FullName));
                handlers = Enumerable.Empty <RouteHandlerDelegate>();
                return(false);
            }

            PrepareEvent(@event, framework);


            bool isRequired = BusHelper.IsEventRequired(eventType);

            handlers = Routes.GetHandlers(@event, isRequired);
            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (handlers == null || !handlers.Any())
            {
                Logger.LogDebug(string.Format("An event handler for '{0}' is not required.", eventType.FullName));
            }

            return(true);
        }
示例#14
0
        public bool Start(HostControl hostControl)
        {
            BusHelper.Instance.StartAsync();

            var uri = "http://localhost:81";

            using (var host = new NancyHost(new Uri(uri)))
            {
                var container = new UnityContainer();

                container.RegisterType <FormularioConsumer>();

                _busControl = BusHelper.GetBusConfiguration(container);

                container.RegisterInstance <IBusControl>(_busControl);
                container.RegisterInstance <IBus>(_busControl);

                _busControl.Start();

                host.Start();

                Console.WriteLine($"On {uri}");
                Console.ReadLine();
            }

            return(true);
        }
示例#15
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            try
            {
                //若为本地测试,则不需要登录
                if (GlobalSwitch.RunModel == RunModel.LocalTest)
                {
                    return;
                }
                //判断是否需要登录
                List <string> attrList  = FilterHelper.GetFilterList(filterContext);
                bool          needLogin = attrList.Contains(typeof(CheckLoginAttribute).FullName) && !attrList.Contains(typeof(IgnoreLoginAttribute).FullName);

                //转到登录
                if (needLogin && !Operator.Logged())
                {
                    RedirectToLogin();
                }
            }
            catch (Exception ex)
            {
                BusHelper.HandleException(ex);
                RedirectToLogin();
            }

            void RedirectToLogin()
            {
                if (request.IsAjaxRequest())
                {
                    filterContext.Result = new ContentResult
                    {
                        Content = new AjaxResult {
                            Success = false, Code = 401, Msg = "未登录"
                        }.ToJson(),
                        ContentType = "application/json;charset=UTF-8"
                    };
                }
                else
                {
                    UrlHelper urlHelper = new UrlHelper(filterContext);
                    string    loginUrl  = urlHelper.Content("~/Admin/Home/Login");
                    string    script    = $@"    
<html>
    <script>
        top.location.href = '{loginUrl}';
    </script>
</html>
";
                    filterContext.Result = new ContentResult {
                        Content = script, ContentType = "text/html"
                    };
                }
            }
        }
        /// <summary>
        /// 获取验证码,只有已支付、退款中、退款完成由验证码
        /// </summary>
        /// <param name="orderId"></param>
        private void GetIdentifyingCode(int orderId)
        {
            var request = new GetIdentifyingCodeByOrderRequest()
            {
                OrderId = orderId
            };
            var result = BusHelper.Send <GetIdentifyingCodeByOrderResponse>(request);

            _listCode = result.Codes;
        }
示例#17
0
        /// <summary>
        /// Unsubscribes from receiving published messages of the specified type.
        /// </summary>
        /// <param name="type">The type of message to unsubscribe from</param>
        public void Unsubscribe(Type type)
        {
            Guard.ArgumentNotNull(type, "type");
            logger.Info("Unsubscribe={0}", type.FullName);

            if (subscribedTypes.Contains(type))
            {
                subscribedTypes.Remove(type);
            }
            BusHelper.SubscribeOrUnsubscribeType((s) => { logger.Info(s); }, type, config, receiver.CancelSubscription);
        }
示例#18
0
        public void OnException(ExceptionContext context)
        {
            var ex = context.Exception;

            BusHelper.HandleException(ex);

            context.Result = new ContentResult {
                Content = new AjaxResult {
                    Success = false, Msg = ex.Message
                }.ToJson()
            };
        }
示例#19
0
        /// <summary>
        /// Register an event handler that will listen and respond to all events.
        /// </summary>
        public void RegisterGlobalEventHandler <TMessage>(ITelemetryHelper telemetryHelper, RouteManager routeManger, Action <TMessage> handler,
                                                          bool holdMessageLock = true) where TMessage : IMessage
        {
            Action <TMessage> registerableHandler = BusHelper.BuildActionHandler(handler, holdMessageLock);

            routeManger.RegisterGlobalEventHandler(registerableHandler);

            telemetryHelper.TrackEvent(string.Format("Cqrs/RegisterGlobalEventHandler/{0}", typeof(TMessage).FullName), new Dictionary <string, string> {
                { "Type", "Azure/Bus" }
            });
            telemetryHelper.Flush();
        }
示例#20
0
        public virtual void RegisterHandler <TMessage>(ITelemetryHelper telemetryHelper, RouteManager routeManger, Action <TMessage> handler, Type targetedType, bool holdMessageLock = true)
            where TMessage : IMessage
        {
            Action <TMessage> registerableHandler = BusHelper.BuildTelemeteredActionHandler <TMessage, TAuthenticationToken>(telemetryHelper, handler, holdMessageLock, "Azure/Bus");

            routeManger.RegisterHandler(registerableHandler, targetedType);

            telemetryHelper.TrackEvent(string.Format("Cqrs/RegisterHandler/{0}", typeof(TMessage).FullName), new Dictionary <string, string> {
                { "Type", "Azure/Bus" }
            });
            telemetryHelper.Flush();
        }
示例#21
0
        public bool Start(HostControl hostControl)
        {
            var container = new UnityContainer();

            _busControl = BusHelper.GetBusConfiguration(container);

            container.RegisterInstance <IBusControl>(_busControl);
            container.RegisterInstance <IBus>(_busControl);

            _busControl.Start();

            return(true);
        }
示例#22
0
        public void GetEarliestValidTimestampTest()
        {
            // For example, suppose you have the same list of bus IDs as above:
            // 7,13,x,x,59,x,31,19
            // An x in the schedule means there are no constraints on what bus IDs must depart at that time.
            // This means you are looking for the earliest timestamp(called t) such that:
            // Bus ID 7 departs at timestamp t.
            // Bus ID 13 departs one minute after timestamp t.
            // There are no requirements or restrictions on departures at two or three minutes after timestamp t.
            // Bus ID 59 departs four minutes after timestamp t.
            // There are no requirements or restrictions on departures at five minutes after timestamp t.
            // Bus ID 31 departs six minutes after timestamp t.
            // Bus ID 19 departs seven minutes after timestamp t.
            // The only bus departures that matter are the listed bus IDs at their specific offsets from t.Those bus IDs can depart at other times, and other bus IDs can depart at those times.For example, in the list above, because bus ID 19 must depart seven minutes after the timestamp at which bus ID 7 departs, bus ID 7 will always also be departing with bus ID 19 at seven minutes after timestamp t.
            // In this example, the earliest timestamp at which this occurs is 1068781
            // In the above example, bus ID 7 departs at timestamp 1068788(seven minutes after t).This is fine; the only requirement on that minute is that bus ID 19 departs then, and it does.
            // Here are some other examples:
            // The earliest timestamp that matches the list 17,x,13,19 is 3417.
            // 67,7,59,61 first occurs at timestamp 754018.
            // 67,x,7,59,61 first occurs at timestamp 779210.
            // 67,7,x,59,61 first occurs at timestamp 1261476.
            // 1789,37,47,1889 first occurs at timestamp 1202161486.
            var testData = new List <Tuple <string, BigInteger> >()
            {
                new Tuple <string, BigInteger>(
                    "7,13,x,x,59,x,31,19",
                    1068781),
                new Tuple <string, BigInteger>(
                    "17,x,13,19",
                    3417),
                new Tuple <string, BigInteger>(
                    "67,7,59,61",
                    754018),
                new Tuple <string, BigInteger>(
                    "67,x,7,59,61",
                    779210),
                new Tuple <string, BigInteger>(
                    "67,7,x,59,61",
                    1261476),
                new Tuple <string, BigInteger>(
                    "1789,37,47,1889",
                    1202161486)
            };

            foreach (var testExample in testData)
            {
                var busData = BusHelper.ParseInputLines("1", testExample.Item1);
                var actual  = BusHelper.GetEarliestValidTimestamp(busData.Item2);
                Assert.Equal(testExample.Item2, actual);
            }
        }
        /// <summary>
        /// 获取订单
        /// </summary>
        /// <param name="orderId"></param>
        private void GetData(int orderId)
        {
            var orderRequest = new GetHotelOrderByOrderIdRequest()
            {
                OrderId = orderId
            };
            var result = BusHelper.Send <GetHotelOrderResponse>(orderRequest);

            Order = result;
            GetIdentifyingCode(orderId);
            GetOrderList(orderId);
            GetUserMsg(Order);
            //            GetOrderStatusMsg(Order);
        }
        /// <summary>
        /// Subscribes to recieve published messages of type T.
        /// This method is only necessary if you turned off auto-subscribe
        /// </summary>
        /// <param name="type">The type to subscribe</param>
        public void Subscribe(Type type)
        {
            Guard.ArgumentNotNull(type, "type");

            BusHelper.SubscribeOrUnsubscribeType((s) => { Debug.WriteLine(s); }, type, config, (info) => {
                var filter = new SqlFilter(string.Format(AzureSenderReceiverBase.TYPE_HEADER_NAME + " = '{0}'", info.MessageType.FullName.Replace('.', '_')));

                var desc           = new SubscriptionDescription(config.TopicName, info.SubscriptionName);
                _endpointMap[desc] = info;

                CreateSubscription(desc, filter);

                //TODO determine if we should and can call CreateSubscription on the receiver.
                //receiver.CreateSubscription(info);
            });
        }
示例#25
0
        protected virtual bool PrepareAndValidateCommand <TCommand>(TCommand command, out RouteHandlerDelegate commandHandler)
            where TCommand : ICommand <TAuthenticationToken>
        {
            Type commandType = command.GetType();

            if (command.Frameworks != null && command.Frameworks.Contains("Akka"))
            {
                // if this is the only framework in the list, then it's fine to handle as it's just pre-stamped, if there is more than one framework, then exit.
                if (command.Frameworks.Count() != 1)
                {
                    Logger.LogInfo("The provided command has already been processed in Akka.", string.Format("{0}\\PrepareAndValidateEvent({1})", GetType().FullName, commandType.FullName));
                    commandHandler = null;
                    return(false);
                }
            }

            ICommandValidator <TAuthenticationToken, TCommand> commandValidator = null;

            try
            {
                commandValidator = DependencyResolver.Resolve <ICommandValidator <TAuthenticationToken, TCommand> >();
            }
            catch (Exception exception)
            {
                Logger.LogDebug("Locating an ICommandValidator failed.", string.Format("{0}\\Handle({1})", GetType().FullName, commandType.FullName), exception);
            }

            if (commandValidator != null && !commandValidator.IsCommandValid(command))
            {
                Logger.LogInfo("The provided command is not valid.", string.Format("{0}\\Handle({1})", GetType().FullName, commandType.FullName));
                commandHandler = null;
                return(false);
            }

            PrepareCommand(command);

            bool isRequired = BusHelper.IsEventRequired(commandType);

            commandHandler = Routes.GetSingleHandler(command, isRequired);
            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (commandHandler == null)
            {
                Logger.LogDebug(string.Format("The command handler for '{0}' is not required.", commandType.FullName));
            }

            return(true);
        }
示例#26
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                //若为本地测试,则不需要登录
                if (GlobalSwitch.RunModel == RunModel.LocalTest)
                {
                    return;
                }
                //判断是否需要登录
                List <string> attrList  = FilterHelper.GetFilterList(filterContext);
                bool          needLogin = attrList.Contains(typeof(CheckLoginAttribute).FullName) && !attrList.Contains(typeof(IgnoreLoginAttribute).FullName);

                //转到登录
                if (needLogin && !Operator.Logged())
                {
                    RedirectToLogin();
                }
            }
            catch (Exception ex)
            {
                BusHelper.HandleException(ex);
                RedirectToLogin();
            }

            void RedirectToLogin()
            {
                UrlHelper urlHelper = new UrlHelper(filterContext);
                string    loginUrl  = urlHelper.Content("~/Home/Login");
                string    script    = $@"    
<html>
    <script>
        top.location.href = '{loginUrl}';
    </script>
</html>
";

                filterContext.Result = new ContentResult {
                    Content = script, ContentType = "text/html"
                };
            }
        }
示例#27
0
        /// <summary>
        /// 处理系统错误
        /// </summary>
        /// <param name="exContext">错误消息</param>
        public override void OnException(ExceptionContext exContext)
        {
            base.OnException(exContext);

            exContext.ExceptionHandled = true;
            exContext.HttpContext.Response.StatusCode = 200;

            var theEx = exContext.Exception;

            BusHelper.HandleException(theEx);

            AjaxResult res = new AjaxResult()
            {
                Success = false,
                Msg     = theEx.Message
            };

            exContext.Result = new ContentResult()
            {
                Content = res.ToJson(), ContentEncoding = Encoding.UTF8
            };
        }
        private void GetUserMsg(GetHotelOrderResponse order)
        {
            //订单信息
            if (order != null)
            {
                var request = new GetHotelRequest()
                {
                    HotelId = order.HotelId
                };
                var hotel      = BusHelper.Send <GetHotelResponse>(request);
                var createTime = string.Format("{0:yyyy/MM/dd HH:mm}", Order.CreateDate);

                Dingdanren += "<tr> <td>酒店商户或门店:" + hotel.Name + "</td></tr>";
                Dingdanren += "<tr> <td>商户或门店编号:" + hotel.Code + "</td></tr>";
                Dingdanren += "<tr><td width=\"70\">订单编号: " + order.OrderNum + "</td></tr>";
                Dingdanren += "<tr> <td>交易日期:" + createTime + "</td></tr>";
                Dingdanren += "<tr><td>预定人:" + order.OrderPersonName + "</td></tr>";
                Dingdanren += "<tr><td>电话:" + order.Tel + "</td></tr>";
                //                dingdanren += "<tr><td>地址:" + manage.address + "</td></tr>";
                //                dingdanren += "<tr><td>备注 :" + manage.oderRemark + "</td></tr>";

                status      = HotelStatusManager.OrderStatus.GetStatusDict(order.OrderStatus);
                Dingdanren += "<tr><td>订单状态:<em  style='width:70px;' class='" + status.CssClass
                              + "'>" + status.StatusName + "</em></td></tr>";
            }
            else
            {
                Dingdanren += "<tr> <td>酒店商户或门店:</td></tr>";
                Dingdanren += "<tr> <td>商户或门店编号:</td></tr>";
                Dingdanren += "<tr><td width=\"70\">订单编号:</td></tr>";
                Dingdanren += "<tr> <td>交易日期:</td></tr>";
                Dingdanren += "<tr><td>预定人:</td></tr>";
                Dingdanren += "<tr><td>电话:</td></tr>";

                Dingdanren += "<tr><td>订单状态:<em  style='width:70px;' class='no'>未处理</em></td></tr>";
            }
        }
示例#29
0
        protected virtual void ReceiveEvent(BrokeredMessage message)
        {
            var brokeredMessageRenewCancellationTokenSource = new CancellationTokenSource();

            try
            {
                Logger.LogDebug(string.Format("An event message arrived with the id '{0}'.", message.MessageId));
                string messageBody = message.GetBody <string>();
                IEvent <TAuthenticationToken> @event;

                try
                {
                    @event = MessageSerialiser.DeserialiseEvent(messageBody);
                }
                catch (JsonSerializationException exception)
                {
                    JsonSerializationException checkException = exception;
                    bool safeToExit = false;
                    do
                    {
                        if (checkException.Message.StartsWith("Could not load assembly"))
                        {
                            safeToExit = true;
                            break;
                        }
                    } while ((checkException = checkException.InnerException as JsonSerializationException) != null);
                    if (safeToExit)
                    {
                        const string pattern = @"(?<=^Error resolving type specified in JSON ').+?(?='\. Path '\$type')";
                        Match        match   = new Regex(pattern).Match(exception.Message);
                        if (match.Success)
                        {
                            string[] typeParts = match.Value.Split(',');
                            if (typeParts.Length == 2)
                            {
                                string classType  = typeParts[0];
                                bool   isRequired = BusHelper.IsEventRequired(string.Format("{0}.IsRequired", classType));

                                if (!isRequired)
                                {
                                    // Remove message from queue
                                    message.Complete();
                                    Logger.LogDebug(string.Format("An event message arrived with the id '{0}' but processing was skipped due to event settings.", message.MessageId));
                                    return;
                                }
                            }
                        }
                    }
                    throw;
                }

                CorrelationIdHelper.SetCorrelationId(@event.CorrelationId);
                Logger.LogInfo(string.Format("An event message arrived with the id '{0}' was of type {1}.", message.MessageId, @event.GetType().FullName));

                bool canRefresh;
                if (!ConfigurationManager.TryGetSetting(string.Format("{0}.ShouldRefresh", @event.GetType().FullName), out canRefresh))
                {
                    canRefresh = false;
                }

                if (canRefresh)
                {
                    Task.Factory.StartNew(() =>
                    {
                        while (!brokeredMessageRenewCancellationTokenSource.Token.IsCancellationRequested)
                        {
                            //Based on LockedUntilUtc property to determine if the lock expires soon
                            if (DateTime.UtcNow > message.LockedUntilUtc.AddSeconds(-10))
                            {
                                // If so, repeat the message
                                message.RenewLock();
                            }

                            Thread.Sleep(500);
                        }
                    }, brokeredMessageRenewCancellationTokenSource.Token);
                }

                ReceiveEvent(@event);

                // Remove message from queue
                message.Complete();
                Logger.LogDebug(string.Format("An event message arrived and was processed with the id '{0}'.", message.MessageId));

                IList <IEvent <TAuthenticationToken> > events;
                if (EventWaits.TryGetValue(@event.CorrelationId, out events))
                {
                    events.Add(@event);
                }
            }
            catch (Exception exception)
            {
                // Indicates a problem, unlock message in queue
                Logger.LogError(string.Format("An event message arrived with the id '{0}' but failed to be process.", message.MessageId), exception: exception);
                message.Abandon();
            }
            finally
            {
                // Cancel the lock of renewing the task
                brokeredMessageRenewCancellationTokenSource.Cancel();
            }
        }
示例#30
0
        /// <summary>
        /// Publishes the provided <paramref name="event"/> on the event bus.
        /// </summary>
        public virtual void Publish <TEvent>(TEvent @event)
            where TEvent : IEvent <TAuthenticationToken>
        {
            DateTimeOffset startedAt          = DateTimeOffset.UtcNow;
            Stopwatch      mainStopWatch      = Stopwatch.StartNew();
            string         responseCode       = null;
            bool           mainWasSuccessfull = false;
            bool           telemeterOverall   = false;

            IDictionary <string, string> telemetryProperties = new Dictionary <string, string> {
                { "Type", "Azure/Servicebus" }
            };
            string telemetryName    = string.Format("{0}/{1}/{2}", @event.GetType().FullName, @event.GetIdentity(), @event.Id);
            var    telemeteredEvent = @event as ITelemeteredMessage;

            if (telemeteredEvent != null)
            {
                telemetryName = telemeteredEvent.TelemetryName;
            }
            else
            {
                telemetryName = string.Format("Event/{0}", telemetryName);
            }

            try
            {
                if (!AzureBusHelper.PrepareAndValidateEvent(@event, "Azure-ServiceBus"))
                {
                    return;
                }

                Type eventType            = typeof(TEvent);
                bool?isPublicBusRequired  = BusHelper.IsPublicBusRequired(eventType);
                bool?isPrivateBusRequired = BusHelper.IsPrivateBusRequired(eventType);

                // We only add telemetry for overall operations if two occured
                telemeterOverall = isPublicBusRequired != null && isPublicBusRequired.Value && isPrivateBusRequired != null && isPrivateBusRequired.Value;

                // Backwards compatibility and simplicity
                bool      wasSuccessfull;
                Stopwatch stopWatch = Stopwatch.StartNew();
                if ((isPublicBusRequired == null || !isPublicBusRequired.Value) && (isPrivateBusRequired == null || !isPrivateBusRequired.Value))
                {
                    stopWatch.Restart();
                    responseCode   = "200";
                    wasSuccessfull = false;
                    try
                    {
                        var brokeredMessage = new BrokeredMessage(MessageSerialiser.SerialiseEvent(@event))
                        {
                            CorrelationId = CorrelationIdHelper.GetCorrelationId().ToString("N")
                        };
                        brokeredMessage.Properties.Add("Type", @event.GetType().FullName);
                        PublicServiceBusPublisher.Send(brokeredMessage);
                        wasSuccessfull = true;
                    }
                    catch (QuotaExceededException exception)
                    {
                        responseCode = "429";
                        Logger.LogError("The size of the event being sent was too large or the topic has reached it's limit.", exception: exception, metaData: new Dictionary <string, object> {
                            { "Event", @event }
                        });
                        throw;
                    }
                    catch (Exception exception)
                    {
                        responseCode = "500";
                        Logger.LogError("An issue occurred while trying to publish an event.", exception: exception, metaData: new Dictionary <string, object> {
                            { "Event", @event }
                        });
                        throw;
                    }
                    finally
                    {
                        TelemetryHelper.TrackDependency("Azure/Servicebus/EventBus", "Event", telemetryName, "Default Bus", startedAt, stopWatch.Elapsed, responseCode, wasSuccessfull, telemetryProperties);
                    }
                    Logger.LogDebug(string.Format("An event was published on the public bus with the id '{0}' was of type {1}.", @event.Id, @event.GetType().FullName));
                }
                if ((isPublicBusRequired != null && isPublicBusRequired.Value))
                {
                    stopWatch.Restart();
                    responseCode   = "200";
                    wasSuccessfull = false;
                    try
                    {
                        var brokeredMessage = new BrokeredMessage(MessageSerialiser.SerialiseEvent(@event))
                        {
                            CorrelationId = CorrelationIdHelper.GetCorrelationId().ToString("N")
                        };
                        brokeredMessage.Properties.Add("Type", @event.GetType().FullName);
                        PublicServiceBusPublisher.Send(brokeredMessage);
                        wasSuccessfull = true;
                    }
                    catch (QuotaExceededException exception)
                    {
                        responseCode = "429";
                        Logger.LogError("The size of the event being sent was too large.", exception: exception, metaData: new Dictionary <string, object> {
                            { "Event", @event }
                        });
                        throw;
                    }
                    catch (Exception exception)
                    {
                        responseCode = "500";
                        Logger.LogError("An issue occurred while trying to publish an event.", exception: exception, metaData: new Dictionary <string, object> {
                            { "Event", @event }
                        });
                        throw;
                    }
                    finally
                    {
                        TelemetryHelper.TrackDependency("Azure/Servicebus/EventBus", "Event", telemetryName, "Public Bus", startedAt, stopWatch.Elapsed, responseCode, wasSuccessfull, telemetryProperties);
                    }
                    Logger.LogDebug(string.Format("An event was published on the public bus with the id '{0}' was of type {1}.", @event.Id, @event.GetType().FullName));
                }
                if (isPrivateBusRequired != null && isPrivateBusRequired.Value)
                {
                    stopWatch.Restart();
                    responseCode   = "200";
                    wasSuccessfull = false;
                    try
                    {
                        var brokeredMessage = new BrokeredMessage(MessageSerialiser.SerialiseEvent(@event))
                        {
                            CorrelationId = CorrelationIdHelper.GetCorrelationId().ToString("N")
                        };
                        brokeredMessage.Properties.Add("Type", @event.GetType().FullName);
                        PrivateServiceBusPublisher.Send(brokeredMessage);
                        wasSuccessfull = true;
                    }
                    catch (QuotaExceededException exception)
                    {
                        responseCode = "429";
                        Logger.LogError("The size of the event being sent was too large.", exception: exception, metaData: new Dictionary <string, object> {
                            { "Event", @event }
                        });
                        throw;
                    }
                    catch (Exception exception)
                    {
                        responseCode = "500";
                        Logger.LogError("An issue occurred while trying to publish an event.", exception: exception, metaData: new Dictionary <string, object> {
                            { "Event", @event }
                        });
                        throw;
                    }
                    finally
                    {
                        TelemetryHelper.TrackDependency("Azure/Servicebus/EventBus", "Event", telemetryName, "Private Bus", startedAt, stopWatch.Elapsed, responseCode, wasSuccessfull, telemetryProperties);
                    }

                    Logger.LogDebug(string.Format("An event was published on the private bus with the id '{0}' was of type {1}.", @event.Id, @event.GetType().FullName));
                }
                mainWasSuccessfull = true;
            }
            finally
            {
                mainStopWatch.Stop();
                if (telemeterOverall)
                {
                    TelemetryHelper.TrackDependency("Azure/Servicebus/EventBus", "Event", telemetryName, null, startedAt, mainStopWatch.Elapsed, responseCode, mainWasSuccessfull, telemetryProperties);
                }
            }
        }