Exemple #1
0
        private static void ConsumerOnReceived(object sender, BasicDeliverEventArgs e)
        {
            // Read the body into a UTF8 string.
            var body    = e.Body;
            var message = Encoding.UTF8.GetString(body);

            string json;

            try
            {
                json = EncryptProvider.AESDecrypt(message, KEY, IV);
                if (string.IsNullOrWhiteSpace(json))
                {
                    throw new ArgumentNullException(nameof(json));
                }
            }
            catch
            {
                Log.Warning("Invalid attempt to send message, wrong encryption Key and IV");
                return;
            }

            var service = JsonConvert.DeserializeObject <Service>(json);

            // Generate a new authentication token.
            var token = TokenProducer.ProduceToken();

            service.Token = token;

            SaveService(service);

            var producer = RabbitMqProducer.Create(service.ApplicationId);

            producer.SendMessage(token);
        }
        public bool ExecuteEmail(EbApi Api, RabbitMqProducer MessageProducer3)
        {
            bool status;

            try
            {
                EbEmailTemplate emailTemplate = Api.GetEbObject <EbEmailTemplate>(this.Reference, Api.Redis, Api.ObjectsDB);

                List <Param> InputParams = EbApiHelper.GetEmailParams(emailTemplate, Api.Redis, Api.ObjectsDB);

                Api.FillParams(InputParams);

                MessageProducer3.Publish(new EmailAttachmentRequest()
                {
                    ObjId      = Convert.ToInt32(this.Reference.Split(CharConstants.DASH)[3]),
                    Params     = InputParams,
                    UserId     = Api.UserObject.UserId,
                    UserAuthId = Api.UserObject.AuthId,
                    SolnId     = Api.SolutionId,
                    RefId      = this.Reference
                });

                status = true;

                string msg = $"The mail has been sent successfully to {emailTemplate.To} with subject {emailTemplate.Subject} and cc {emailTemplate.Cc}";

                Api.ApiResponse.Message.Description = msg;
            }
            catch (Exception ex)
            {
                throw new ApiException("[ExecuteEmail], " + ex.Message);
            }
            return(status);
        }
Exemple #3
0
        private static void OnAuthReceived(object sender, BasicDeliverEventArgs args)
        {
            var body  = args.Body;
            var token = Encoding.UTF8.GetString(body);

            var rabbitMqProducer = RabbitMqProducer.Create(StaticQueues.LoggingQueue);

            Console.WriteLine($"Gained token: {token}, Start writing messages.");
            while (true)
            {
                var message = Console.ReadLine();

                if (message == "q")
                {
                    break;
                }

                var payload = new LoggingMessage {
                    Sender = APPLICATIONID, Group = GROUPID, Body = message
                };
                var json            = JsonConvert.SerializeObject(payload);
                var basicProperties =
                    new BasicProperties {
                    Headers = new Dictionary <string, object> {
                        { "token", token }
                    }
                };
                rabbitMqProducer.SendMessage(json, basicProperties);
            }

            rabbitMqProducer.Disconnect();
        }
        public void Test()
        {
            var factory = new RabbitMqMessageQueueFactory("localhost");

            var sender = new RabbitMqProducer(factory);

            sender.SendData();
        }
 public OpsLogAsyncInterceptor(UserContext userContext
                               , RabbitMqProducer mqProducer
                               , ILogger <OpsLogAsyncInterceptor> logger)
 {
     _userContext = userContext;
     _mqProducer  = mqProducer;
     _logger      = logger;
 }
Exemple #6
0
        /// <summary>
        /// Main method ran when executing the program.
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            ConfigureLogger();
            Log.Information("Setting up MicroMonitor Authentication Token Provider");
            _authProducer = RabbitMqProducer.Create(string.Empty, StaticQueues.IsAuthenticatedReply);
            _authReceiver = RabbitMqReceiver.Create(StaticQueues.IsAuthenticated, IsAuthenticatedOnReceived);

            _authReceiver.Run();
            Log.Information("Setup complete, waiting for request.");
        }
Exemple #7
0
 public AccountAppService(IEfRepository <SysUser> userRepository,
                          IEfRepository <SysRole> roleRepository,
                          IEfRepository <SysMenu> menuRepository,
                          RabbitMqProducer mqProducer)
 {
     _userRepository = userRepository;
     _roleRepository = roleRepository;
     _menuRepository = menuRepository;
     _mqProducer     = mqProducer;
 }
 private void TimerElapsed(object sender, ElapsedEventArgs e)
 {
     Parallel.ForEach(Enumerable.Range(0, ConfigHelper.ProducerBatchCount), (index) =>
     {
         RabbitMqProducer.Publish(
             ConfigHelper.QueueId,
             new PressureTestContent()
         {
             Content        = $"{DateTime.Now.ToString("yyyyMMddhhmmssfff")}-{index}",
             CreateDateTime = DateTime.Now
         });
     });
 }
Exemple #9
0
 public AccountAppService(IMapper mapper,
                          IEfRepository <SysUser> userRepository,
                          IEfRepository <SysRole> roleRepository,
                          IEfRepository <SysMenu> menuRepository,
                          IEfRepository <NullEntity> rsp,
                          RabbitMqProducer mqProducer)
 {
     _mapper         = mapper;
     _userRepository = userRepository;
     _roleRepository = roleRepository;
     _menuRepository = menuRepository;
     _rsp            = rsp;
     _mqProducer     = mqProducer;
 }
Exemple #10
0
        public static object GetResult(ApiResources resource, EbApi Api, RabbitMqProducer mqp, Service service, EbStaticFileClient FileClient)
        {
            ResultWrapper res = new ResultWrapper();

            switch (resource)
            {
            case EbSqlReader reader:
                res.Result = (reader as EbSqlReader).ExecuteDataReader(Api);
                break;

            case EbSqlWriter writer:
                res.Result = (writer as EbSqlWriter).ExecuteDataWriter(Api);
                break;

            case EbSqlFunc func:
                res.Result = (func as EbSqlFunc).ExecuteSqlFunction(Api);
                break;

            case EbEmailNode email:
                res.Result = (email as EbEmailNode).ExecuteEmail(Api, mqp);
                break;

            case EbProcessor processor:
                res.Result = (processor as EbProcessor).ExecuteScript(Api, mqp, service, FileClient);
                break;

            case EbConnectApi ebApi:
                res.Result = (ebApi as EbConnectApi).ExecuteConnectApi(Api, service);
                break;

            case EbThirdPartyApi thirdParty:
                res.Result = (thirdParty as EbThirdPartyApi).ExecuteThirdPartyApi(thirdParty, Api);
                break;

            case EbFormResource form:
                res.Result = (form as EbFormResource).ExecuteFormResource(Api, service);
                break;

            case EbEmailRetriever retriever:
                res.Result = (retriever as EbEmailRetriever).ExecuteEmailRetriever(Api, service, FileClient, true);
                break;

            default:
                res.Result = null;
                break;
            }

            return(res.Result);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationFlow"/> class.
        /// </summary>
        public AuthenticationFlow(bool useAuthentication)
        {
            if (!useAuthentication)
            {
                return;
            }

            _unprocessed         = new Dictionary <string, string>();
            _authenticatedTokens = new Dictionary <string, Service>();
            _authSender          = RabbitMqProducer.Create(StaticQueues.IsAuthenticated);
            var faker = new Faker();

            _replyReceiver = RabbitMqReceiver.Create(faker.Random.AlphaNumeric(15), ConsumerOnReceived, StaticQueues.IsAuthenticatedReply);

            _replyReceiver.Run();
        }
Exemple #12
0
        static void Main(string[] args)
        {
            Console.WriteLine("Test Client");
            Console.WriteLine("Waiting for services to start...\nPress enter when ready.");
            Console.ReadLine();

            authProducer = RabbitMqProducer.Create(StaticQueues.RequestAuth);

            authReceiver = RabbitMqReceiver.Create(APPLICATIONID, OnAuthReceived);

            var service = new Service {
                ApplicationId = APPLICATIONID, GroupId = GROUPID
            };

            var json = JsonConvert.SerializeObject(service);

            var encrypt = EncryptProvider.AESEncrypt(json, KEY, IV);

            authProducer.SendMessage(encrypt);
            Console.WriteLine("Waiting for response.");
        }
Exemple #13
0
        public void SendWelcomeMail(RabbitMqProducer MessageProducer3, User user, Eb_Solution solution)
        {
            string Html = this.MailHtml
                          .Replace("{SolutionName}", solution.SolutionName)
                          .Replace("{eSolutionId}", solution.ExtSolutionID)
                          .Replace("{iSolutionId}", solution.SolutionID)
                          .Replace("{UserName}", this.UserCredentials.Name)
                          .Replace("{Email}", this.UserCredentials.Email)
                          .Replace("{Password}", this.UserCredentials.Pwd)
                          .Replace("{SolutionAdmin}", string.IsNullOrEmpty(user.FullName) ? $"{solution.SolutionName} Team" : user.FullName);

            //this.EbConnectionFactory.EmailConnection.Send("*****@*****.**", "test", "Hiii", null, null, null, "");

            MessageProducer3.Publish(new EmailServicesRequest()
            {
                To         = this.UserCredentials.Email,
                Message    = Html,
                Subject    = $"Welcome to {solution.SolutionName} Solution",
                UserId     = user.UserId,
                UserAuthId = user.AuthId,
                SolnId     = solution.SolutionID
            });
        }
Exemple #14
0
        /// <summary>
        /// 使用消息队列
        /// </summary>
        public static IServiceCollection AddRabbitMq(this IServiceCollection collection, RabbitMqOption configuration)
        {
            var factory = new ConnectionFactory
            {
                AutomaticRecoveryEnabled  = true,
                UseBackgroundThreadsForIO = true,
                HostName                = configuration.HostName,
                UserName                = configuration.UserName,
                Password                = configuration.Password,
                VirtualHost             = configuration.VirtualHost,
                NetworkRecoveryInterval = TimeSpan.FromSeconds(5)
            };

            if (configuration.SocketTimeout != null)
            {
                factory.RequestedConnectionTimeout = factory.SocketWriteTimeout = factory.SocketReadTimeout
                                                                                      = configuration.SocketTimeout.Value;
            }
            if (configuration.ContinuationTimeout != null)
            {
                factory.ContinuationTimeout = factory.HandshakeContinuationTimeout = configuration.ContinuationTimeout.Value;
            }

            collection.AddDisposableSingleInstanceService(new RabbitConnectionWrapper(factory));
            collection.AddSingleton <IConnection>(provider => provider.Resolve_ <RabbitConnectionWrapper>().Connection);
            //add default message producer
            collection.AddSingleton <IRabbitMqProducer>(provider =>
            {
                var con        = provider.Resolve_ <IConnection>();
                var serializer = provider.ResolveSerializer();
                var res        = new RabbitMqProducer(con, serializer);
                return(res);
            });

            return(collection);
        }
        public object ExecuteScript(EbApi Api, RabbitMqProducer mqp, Service service, EbStaticFileClient Fileclient)
        {
            ApiGlobalParent global;

            if (this.EvaluatorVersion == EvaluatorVersion.Version_1)
            {
                global = new ApiGlobals(Api.GlobalParams);
            }
            else
            {
                global = new ApiGlobalsCoreBase(Api.GlobalParams);
            }

            global.ResourceValueByIndexHandler += (index) =>
            {
                object resourceValue = Api.Resources[index].Result;

                if (resourceValue != null && resourceValue is string converted)
                {
                    if (converted.StartsWith("{") && converted.EndsWith("}") || converted.StartsWith("[") && converted.EndsWith("]"))
                    {
                        string formated = converted.Replace(@"\", string.Empty);
                        return(JObject.Parse(formated));
                    }
                }
                return(resourceValue);
            };

            global.ResourceValueByNameHandler += (name) =>
            {
                int index = Api.Resources.GetIndex(name);

                object resourceValue = Api.Resources[index].Result;

                if (resourceValue != null && resourceValue is string converted)
                {
                    if (converted.StartsWith("{") && converted.EndsWith("}") || converted.StartsWith("[") && converted.EndsWith("]"))
                    {
                        string formated = converted.Replace(@"\", string.Empty);
                        return(JObject.Parse(formated));
                    }
                }
                return(resourceValue);
            };

            global.GoToByIndexHandler += (index) =>
            {
                Api.Step = index;
                Api.Resources[index].Result = EbApiHelper.GetResult(Api.Resources[index], Api, mqp, service, Fileclient);
            };

            global.GoToByNameHandler += (name) =>
            {
                int index = Api.Resources.GetIndex(name);
                Api.Step = index;
                Api.Resources[index].Result = EbApiHelper.GetResult(Api.Resources[index], Api, mqp, service, Fileclient);
            };

            global.ExitResultHandler += (obj) =>
            {
                ApiScript script = new ApiScript
                {
                    Data = JsonConvert.SerializeObject(obj),
                };
                Api.ApiResponse.Result = script;
                Api.Step = Api.Resources.Count - 1;
            };

            ApiResources lastResource = Api.Step == 0 ? null : Api.Resources[Api.Step - 1];

            if (this.EvaluatorVersion == EvaluatorVersion.Version_1 && lastResource?.Result is EbDataSet dataSet)
            {
                (global as ApiGlobals).Tables = dataSet.Tables;
            }

            ApiScript result;

            try
            {
                result = this.Execute(global);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }
        void AddProducerBinding()
        {
            if (_producer != null)
                return;

            _producer = new RabbitMqProducer(_address);

            _connectionHandler.AddBinding(_producer);
        }
Exemple #17
0
 public OpsLogInterceptor(UserContext userContext
                          , RabbitMqProducer mqProducer)
 {
     _userContext = userContext;
     _mqProducer  = mqProducer;
 }
Exemple #18
0
 public BaseService(IServerEvents _se, IMessageProducer _mqp)
 {
     this.ServerEvents     = _se;
     this.MessageProducer3 = _mqp as RabbitMqProducer;
 }
        void AddProducerBinding()
        {
            if (_producer != null)
                return;

            lock (_lock)
            {
                if (_producer != null)
                    return;

                var producer = new RabbitMqProducer(_address, _bindToQueue);
                _connectionHandler.AddBinding(producer);

                _producer = producer;
            }
        }