public bool UpdateCardList(int cardlistId, UpdateCardListDTO cardListDTO, string username) { bool ret = false; using (UnitOfWork unit = new UnitOfWork()) { CardList cardList = unit.CardListRepository.GetById(cardlistId); if (cardList != null) { cardList.Name = cardListDTO.Name; cardList.Color = cardListDTO.Color; unit.CardListRepository.Update(cardList); ret = unit.Save(); if (ret) { BasicCardListDTO dto = new BasicCardListDTO(cardList); RabbitMQService.PublishToExchange(cardList.Board.ExchangeName, new MessageContext(new CardListMessageStrategy(dto, MessageType.Update, username))); BoardNotificationService.ChangeBoardNotifications(cardList.Board.BoardId); } } } return(ret); }
public BasicCardListDTO InsertCardList(CreateCardListDTO cardListDto, string username) { //if (!PermissionHelper.HasPermissionOnBoard(cardListDto.BoardId, userId)) //{ // return 0; //} BasicCardListDTO dto = null; CardList list = cardListDto.FromDTO(); using (UnitOfWork unit = new UnitOfWork()) { Board board = unit.BoardRepository.GetById(cardListDto.BoardId); if (board != null) { list.Board = board; unit.CardListRepository.Insert(list); if (unit.Save()) { dto = new BasicCardListDTO(list); RabbitMQService.PublishToExchange(board.ExchangeName, new MessageContext(new CardListMessageStrategy(dto, MessageType.Create, username))); BoardNotificationService.ChangeBoardNotifications(board.BoardId); } } } return(dto); }
public bool DeleteBoard(int id, string username) { bool ret = false; using (UnitOfWork unit = new UnitOfWork()) { bool isAdmin = unit.PermissionRepository .IsAdmin(id, username); if (isAdmin) { List <User> users = unit.PermissionRepository .GetAllUsersWithPermissionOnBoard(id); unit.BoardRepository.Delete(id); ret = unit.Save(); if (ret) { foreach (var u in users) { RabbitMQService.PublishToExchange(u.ExchangeName, new MessageContext(new BoardMessageStrategy(id))); } } } } return(ret); }
public TestController(ILogger <TestController> logger, RabbitMQService mqService, DbService dbService, StorageService storageService) { _mqService = mqService; _logger = logger; _dbService = dbService; _storageService = storageService; }
public void Post([FromBody] Product product) { RabbitMQService factory = new RabbitMQService(_config); using (var connection = factory.GetRabbitMQConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: _config.Value.QueueName, durable: false, exclusive: false, autoDelete: false, arguments: null); var productSerialized = JsonConvert.SerializeObject(product); var body = Encoding.UTF8.GetBytes(productSerialized); channel.BasicPublish(exchange: "", routingKey: _config.Value.QueueName, basicProperties: null, body: body); } } }
public BasicCardDTO InsertCard(string username, CreateCardDTO dto) { //if (!PermissionHelper.HasPermissionOnList(dto.ListId, userId)) //{ // return 0; //} BasicCardDTO cardDto = null; using (UnitOfWork uw = new UnitOfWork()) { CardList list = uw.CardListRepository.GetById(dto.ListId); User user = uw.UserRepository.GetUserByUsername(username); Card card = CreateCardDTO.FromDTO(dto); if (user != null && list != null) { card.User = user; card.List = list; uw.CardRepository.Insert(card); if (uw.Save()) { cardDto = new BasicCardDTO(card); RabbitMQService.PublishToExchange(list.Board.ExchangeName, new MessageContext(new CardMessageStrategy(cardDto, MessageType.Create, username))); BoardNotificationService.ChangeBoardNotifications(list.Board.BoardId); } } } return(cardDto); }
static void Main(string[] args) { using (var service = new RabbitMQService(new RabbitMQHelper())) { service.Run(); } }
public bool DeleteCardList(int id, string username) { bool ret = false; using (UnitOfWork unit = new UnitOfWork()) { CardList cardlist = unit.CardListRepository.GetById(id); if (cardlist != null) { Board board = cardlist.Board; string exchangeName = board.ExchangeName; int boardId = board.BoardId; unit.CardListRepository.Delete(id); ret = unit.Save(); if (ret) { RabbitMQService.PublishToExchange(exchangeName, new MessageContext(new CardListMessageStrategy(id, username))); BoardNotificationService.ChangeBoardNotifications(boardId); } } } return(ret); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddMvcCore() .AddApiExplorer(); services.ConfigureCors(); services.AddSwaggerDocumentation(); services.AddEntityFrameworkNpgsql().AddDbContext <AppDbContext>(options => { options.UseNpgsql(Configuration.GetConnectionString("databaseString")); options.EnableSensitiveDataLogging(); }, ServiceLifetime.Transient); services.ConfigureAuthetication(Configuration); services.AddIdentity <User, Role>() .AddEntityFrameworkStores <AppDbContext>(); services.Configure <RabbitMqSettings>(Configuration.GetSection(nameof(RabbitMqSettings))); services.AddUrlHelper(); services.RegisterServices(); services.RegisterRepositories(); services.AutoMapperConfig(); var serviceProvider = services.BuildServiceProvider(); var rabbitMQSettings = serviceProvider.GetRequiredService <IOptions <RabbitMqSettings> >().Value; IOptions <RabbitMqSettings> rabbitMQSettingsOptions = Options.Create(rabbitMQSettings); IRabbitMQService rabbitMQService = new RabbitMQService(rabbitMQSettingsOptions); rabbitMQService.CreateQueues(); }
public BasicCommentDTO InsertComment(string username, CreateCommentDTO dto) { Comment comment = CreateCommentDTO.FromDTO(dto); BasicCommentDTO commentDTO = null; using (UnitOfWork uw = new UnitOfWork()) { Card card = uw.CardRepository.GetById(dto.CardId); User user = uw.UserRepository.GetUserByUsername(username); if (card != null && user != null) { comment.Card = card; comment.User = user; uw.CommentRepository.Insert(comment); if (uw.Save()) { NotificationService notif = new NotificationService(); notif.CreateChangeNotification(new CreateNotificationDTO() { CardId = dto.CardId, UserId = user.UserId, NotificationType = NotificationType.Change }); commentDTO = new BasicCommentDTO(comment); RabbitMQService.PublishToExchange(card.List.Board.ExchangeName, new MessageContext(new CommentMessageStrategy(commentDTO, username))); BoardNotificationService.ChangeBoardNotifications(card.List.Board.BoardId); } } } return(commentDTO); }
static void Main(string[] args) { RabbitMQService _rabbitMQService = new RabbitMQService(); using (var connection = _rabbitMQService.GetRabbitMQConnection()) { //kanal olusturma using (var channel = connection.CreateModel()) { //kuyruk olusturma channel.QueueDeclare("test", false, false, false, null); var consumer = new EventingBasicConsumer(channel); channel.BasicConsume("test", true, consumer); consumer.Received += (s, e) => { Thread.Sleep(5000); Console.WriteLine("test123123"); }; Console.ReadLine(); //rabbitmq gönderme } Console.Read(); Console.WriteLine("Hello World!"); } }
protected void ProcessBotMessage(string writtenMessage) { RabbitMQService.PublishMessage(writtenMessage); var result = RabbitMQService.GetMessages(); GetBotMessages(); }
public static void ReceiveMeta() { var rbService = new RabbitMQService(); var conn = rbService.GetRabbitMQConnection(); var meta = conn.CreateModel(); meta.ExchangeDeclare("Metas", durable: true, type: ExchangeType.Fanout); var queueName = meta.QueueDeclare().QueueName; meta.QueueBind(queue: queueName, exchange: "Metas", routingKey: "UOFMetas"); meta.BasicQos(prefetchSize: 0, prefetchCount: 1, false); var metaConsumer = new EventingBasicConsumer(meta); meta.BasicConsume(queueName, false, metaConsumer); SerilogHelper.Information($"Connected Metas {queueName}"); metaConsumer.Received += (model, ea) => { var body = ea.Body; var data = Encoding.UTF8.GetString(body); var _data = UtcHelper.Deserialize <Meta>(data); Program.metaMainQueue.Enqueue(_data); meta.BasicAck(ea.DeliveryTag, multiple: false); }; }
public void RabbitMQ() { var builder = new ConfigurationBuilder() .AddConfigurationFile("appsettings.json", optional: true, reloadOnChange: true); var Configuration = builder.Build(); var mq = new RabbitMQService(AppConfig.GetSection("RabbitMQConnectionString")?.Value); var con = new ContainerBuilder(); con.AddRabbitMQService(); var icon = con.Build(); var mq1 = icon.Resolve <IRabbitMQService>(); //·¢ËÍ var originObject = new testclass() { id = 1, name = "ÐÕÃû1" }; mq.Send("changeNametest3", "direct", originObject); //½ÓÊÜ var mq2 = icon.Resolve <IRabbitMQService>(); mq2.Receive("aaa", "changeNametest3", "direct", q => { Assert.Equal(q, Serializer.Serialize(originObject)); }); }
public bool DeleteCard(int id) { bool success = false; using (UnitOfWork uw = new UnitOfWork()) { Card card = uw.CardRepository.GetById(id); if (card != null) { Board board = card.List.Board; uw.CardRepository.Delete(id); success = uw.Save(); if (success) { RabbitMQService.PublishToExchange(board.ExchangeName, new MessageContext(new CardMessageStrategy(id))); BoardNotificationService.ChangeBoardNotifications(board.BoardId); } } } return(success); }
public Consumer(string queueName) { _rabbitMQService = new RabbitMQService(); while (true) { using (var connection = _rabbitMQService.GetRabbitMQConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare(queueName, false, false, false, null); var consumer = new EventingBasicConsumer(channel); BasicGetResult result = channel.BasicGet(queueName, true); if (result != null) { string data = Encoding.UTF8.GetString(result.Body); Mail.Mail mail = new Mail.Mail(); mail.SendMail(data); Console.WriteLine(data); } } } } }
static void Main(string[] args) { var service = new RabbitMQService(); service.EnsureResourceCreation(); Console.WriteLine("Type your message or (q) to quit:"); while (true) { var message = Console.ReadLine(); if (message == "q") { return; } if (!string.IsNullOrEmpty(message)) { try { service.SendMessage(message); } catch (Exception ex) { Console.WriteLine($"[Error]: Failed to send message {ex.Message}"); } } } }
public void Publish() { var rabbitMQService = new RabbitMQService(); using (var connection = rabbitMQService.GetRabbitMQConnection()) { using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(CL_ConstModel.ExchangeName, ExchangeType.Direct, true, false, null); //QUEUE CREATED channel.QueueDeclare(CL_ConstModel.queueName, true, false, false, null); channel.QueueBind(CL_ConstModel.queueName, CL_ConstModel.ExchangeName, CL_ConstModel.queueRouteKey); //QUEUE MESSAGE SEND var publicationAddress = new PublicationAddress(ExchangeType.Direct, CL_ConstModel.ExchangeName, CL_ConstModel.queueRouteKey); string message = JsonConvert.SerializeObject(AccountService.Load()); var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(publicationAddress, null, body); Console.WriteLine("Message Sent!"); } } }
/// <summary> /// The constructor of the Document business logic layer. /// </summary> public DocumentBLL( IConfiguration configuration, ILogger <DocumentBLL> logger, IHttpContextAccessor httpContextAccessor, UserManager <User> userManager, FileService fileService, RabbitMQService rabbitMQService, DocumentRepository documentRepository, DocumentTypeRepository documentTypeRepository, ResumeBLL resumeBLL, ResumeRepository resumeRepository, DocumentResumeRepository documentResumeRepository ) { this.configuration = configuration; this.logger = logger; this.httpContextAccessor = httpContextAccessor; this.userManager = userManager; this.fileService = fileService; this.rabbitMQService = rabbitMQService; this.documentRepository = documentRepository; this.documentTypeRepository = documentTypeRepository; this.resumeBLL = resumeBLL; this.resumeRepository = resumeRepository; this.documentResumeRepository = documentResumeRepository; }
protected async override void OnStart() { Debug.WriteLine("app started"); // var config = await Helper.TryGetNewConfiguration(Constants.QR); RabbitMQService.StartService(); //await Task.Delay(5000); //CrossToastPopUp.Current.ShowToastMessage("Message"); //var notificator = DependencyService.Get<IToastNotificator>(); //var result = await notificator.Notify(new NotificationOptions() { Title = "some title", Description = "My description!", IsClickable = false, AllowTapInNotificationCenter = false }); //Debug.WriteLine("result is: " + result.ToString()); }
public RabbitMQ_Sender(string queueName, string message) { _rabbitMQService = new RabbitMQService(); using (var connection = _rabbitMQService.GetRabbitMQConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare(queueName, false, false, false, null); channel.BasicPublish("", queueName, null, Encoding.UTF8.GetBytes(message)); Console.WriteLine("{0} queue'su üzerine, \"{1}\" mesajı yazıldı.", queueName, message); } } }
static void rabbitMQSubscribe() { var appSettings = GetAppSettings(); var mqService = new RabbitMQService( appSettings.RabbitMQ.HostName, appSettings.RabbitMQ.Port, appSettings.RabbitMQ.UserName, appSettings.RabbitMQ.Password); //订阅用户注册消息 mqService.Subscribe <RegisterMemberEvent>( "RegisterMemberEvent", "RegisterMemberAddAccount", _ => { var accountBusiness = new AccountBusiness(); accountBusiness.dbContext = new MSSQLDbContext("MSDbConnection"); return(accountBusiness.AddAccount(_.MemberId)); }); //订阅支付成功消息--订单处理 mqService.Subscribe <PaymentPaidEvent>( "PaymentPaidEvent", "PaymentPaidOrder", _ => { if (_.Type != Example.IBusiness.Model.PaymentType.Order) { return(true); } var orderBusiness = new OrderBusiness(); orderBusiness.dbContext = new MSSQLDbContext("MSDbConnection"); return(orderBusiness.Notify(_.Identity_Id, _.PaymentId)); }); //订阅支付成功消息--充值处理 mqService.Subscribe <PaymentPaidEvent>( "PaymentPaidEvent", "PaymentPaidRecharge", _ => { if (_.Type != Example.IBusiness.Model.PaymentType.Recharge) { return(true); } //var rechargeBusiness = new RechargeBusiness(); //rechargeBusiness.dbContext = new MSSQLDbContext("MSDbConnection"); return(true); }); }
public void ConfigureServiceDefault_Return_TrueAndMessage() { // Arrange var actual = "Конфигурация установлена успешно."; // Act IRabbitMQService rabbitMQService = new RabbitMQService(_options); var(result, message) = rabbitMQService.ConfigureServiceDefault(); // Assert Assert.True(result); Assert.Equal(message, actual); }
static void Main(string[] args) { var rabbitMQService = new RabbitMQService(); using (var connection = rabbitMQService.GetRabbitMQConnection()) { using (var channel = connection.CreateModel()) { channel.ExchangeDeclare("roompublish.exchange", ExchangeType.Fanout, true, false, null); channel.QueueDeclare("roompublish.", true, false, false, null); } } }
public ReadUserDTO AddUserBoardPermision(AddUserBoardPermisionDTO dto, string admin) { bool ret = false; using (UnitOfWork unit = new UnitOfWork()) { bool isAdmin = unit.PermissionRepository.IsAdmin(dto.BoardId, admin); Permission perm = unit.PermissionRepository.GetPermissionByUsername(dto.BoardId, dto.Username); if (isAdmin && perm == null) { Board b = unit.BoardRepository.GetById(dto.BoardId); User u = unit.UserRepository.GetUserByUsername(dto.Username); if (u != null && b != null) { Permission p = new Permission() { Board = b, User = u }; BoardNotification boardNotification = new BoardNotification() { Board = b, User = u }; unit.PermissionRepository.Insert(p); unit.BoardNotificationRepository.Insert(boardNotification); ret = unit.Save(); if (ret) { RabbitMQService.PublishToExchange(u.ExchangeName, new MessageContext(new BoardMessageStrategy(new BasicBoardDTO(b), MessageType.Create, admin))); RabbitMQService.PublishToExchange(b.ExchangeName, new MessageContext(new PermissionMessageStrategy(new ReadUserDTO(u), MessageType.Create, admin))); return(new ReadUserDTO(u)); } } } } return(null); }
public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message) { COREobject core = COREobject.i; DBEntities context = core.Context; try { string rabbitMQName = (string)vars["rabbitMQ"]; object messageObject = vars["Message"]; if (string.IsNullOrEmpty(rabbitMQName)) { throw new Exception($"{Name}: Please attach RabbitMQ integration."); } if (messageObject == null) { throw new Exception($"{Name}: Message must not be null."); } N.RabbitMQ mq = context.RabbitMQs.SingleOrDefault(q => q.Name == rabbitMQName); if (mq == null) { throw new Exception($"{Name}: Requested RabbitMQ {rabbitMQName} was not found"); } RabbitMQService service = new RabbitMQService(mq); string body; if (messageObject is JToken) { body = messageObject.ToString(); } else { body = Convert.ToString(messageObject); } service.Send(body); service.Close(); outputVars["Result"] = true; outputVars["Error"] = ""; } catch (Exception e) { outputVars["Result"] = false; outputVars["Error"] = e.Message; } }
static void Main(string[] args) { RabbitMQService.Start(ConfigHelper.RabbitMQURI); var consumer = new RabbitMQConsumer( ConfigHelper.SubQueueNames, new PubSubDispatcher <RabbitMQEventStream>(AutofacConfig.Container), ConfigHelper.QueueId); consumer.Start(); Console.Read(); RabbitMQService.Stop(); }
/// <summary> /// 记录请求参数日志 /// </summary> /// <param name="context"></param> public override void OnActionExecuting(ActionExecutingContext context) { HttpContext httpc = context.HttpContext; LogEntity log = new LogEntity() { TrackId = httpc.TraceIdentifier, Method = httpc.Request.Method, Param = context.ActionArguments.Count == 0 ? new object() : context.ActionArguments.FirstOrDefault(), Result = "", BegTime = DateTime.Now, Url = string.Format("{0}://{1}{2}", httpc.Request.Scheme, httpc.Request.Host.Value, httpc.Request.Path.Value) }; RabbitMQService.Send("Log", log, true); Log.Info(log); }
/// <summary> /// 发送指令 /// </summary> /// <param name="Queue"></param> /// <param name="ShelfCode"></param> /// <returns></returns> public static void SendMessage(string Queue, string Operation, BaseAction ActionData, bool IsRabbit = false) { System.Console.WriteLine("开始执行发布\n"); BaseResult cabinet = Config.Bind <BaseResult>("Device.json", Operation); ActionData.Msg = string.Format(cabinet.Message, ActionData.Msg); cabinet.ActionData = ActionData; cabinet.Message = ActionData.Msg; if (IsRabbit) { System.Console.WriteLine("发送RabbitMq\n"); RabbitMQService.Send(Queue, cabinet); } System.Console.WriteLine("发送MqTT\n"); MqttHelp <MqttClientTcpOptions> .Publish <BaseResult>(Queue, cabinet); }
static void Consumer(int n) { var thread = $"thread{n}"; Console.WriteLine($"Waiting for messages on {thread}..."); var service = new RabbitMQService(); service.EnsureResourceCreation(); using (var conn = service.ConsumeMessages($"{thread}")) { Console.ReadLine(); Console.WriteLine($"Closing {thread}"); } }