Beispiel #1
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine("OrderProcessing Service Started");

            while (!stoppingToken.IsCancellationRequested)
            {
                var    consumerHelper = new ConsumerWrapper(consumerConfig, "orderrequests");
                string orderRequest   = consumerHelper.ReadMessage();

                if (string.IsNullOrWhiteSpace(orderRequest))
                {
                    Console.WriteLine("No message available!");
                    return;
                }

                //Deserilaize
                OrderRequest order = JsonConvert.DeserializeObject <OrderRequest>(orderRequest);
                if (order == null)
                {
                    Console.WriteLine("Order details not available!");
                    return;
                }

                //TODO:: Process Order
                Console.WriteLine($"Info: OrderHandler => Processing the order for {order.productname}");
                order.status = OrderStatus.COMPLETED;

                //Write to ReadyToShip Queue

                var producerWrapper = new ProducerWrapper(producerConfig, "readytoship");
                await producerWrapper.WriteMessage(JsonConvert.SerializeObject(order));
            }
        }
Beispiel #2
0
        public async Task <KafkaProcesStatus> ProcessFeedFile()
        {
            var config = new ProducerConfig
            {
                BootstrapServers = "localhost:9092"
            };
            //var response = new DeliveryResult<string, string>();
            var feedFileRecords = getFileDetails.GetFileDetails();

            if (feedFileRecords != null)
            {
                try
                {
                    foreach (Profile record in feedFileRecords)
                    {
                        var    producer        = new ProducerWrapper(config, "kafkaservice");
                        string serializedOrder = JsonConvert.SerializeObject(record);
                        /* response =*/
                        await producer.writeMessage(serializedOrder);
                    }
                    getFileDetails.FeedFileRemove();
                }
                catch (Exception e)
                {
                }
            }
            //if(response.Status.ToString().Equals("Persisted"))
            //{
            //    return KafkaProcesStatus.completed;
            //}
            return(KafkaProcesStatus.error);
        }
Beispiel #3
0
        public async Task <IActionResult> PostAsync([FromBody] string value)
        {
            string serializedOrder = JsonConvert.SerializeObject(value);

            Console.WriteLine("========");
            Console.WriteLine("Info: DepartmentsController => Post => Recieved a new deparment details:");
            Console.WriteLine(serializedOrder);
            Console.WriteLine("=========");
            Dept newDept;

            using (var db = new IshaMasterContext())
            {
                newDept          = new Dept();
                newDept.DeptName = value;
                db.Dept.Add(newDept);
                var count = db.SaveChanges();
            }

            var message = new StringBuilder();

            message.Append("{ \n event: \n DepartmentCreated \n entity: Department \n value:{ \n");
            message.Append(" ID: ");
            message.Append(newDept.DeptId);
            message.Append(",\n Name: ");
            message.Append(serializedOrder);
            message.Append("\n} \n }");

            var producer = new ProducerWrapper(this._config, "DepartmentCreated");
            await producer.writeMessage(message.ToString());

            return(Created(Url.RouteUrl(newDept.DeptId), "Your deparment " + newDept.DeptId + " is created."));
        }
        public async Task <IActionResult> PostAsync([FromBody] Vendor value)
        {
            string serializedOrder = JsonConvert.SerializeObject(value);

            Console.WriteLine("========");
            Console.WriteLine("Info: DepartmentUserController => Post => Recieved a new vendor details:");
            Console.WriteLine(serializedOrder);
            Console.WriteLine("=========");
            Vendor newVendor;

            using (var db = new IshaMasterContext())
            {
                newVendor = new Vendor(value);
                db.Vendor.Add(newVendor);
                var count = db.SaveChanges();
            }

            var message = new StringBuilder();

            message.Append("{ \n event: \n VendorRequested \n entity: vendor \n value:{ \n");
            message.Append(" ID: ");
            message.Append(newVendor.ID);
            message.Append(",\n details: ");
            message.Append(serializedOrder);
            message.Append("\n} \n }");

            var producer = new ProducerWrapper(this._config, "VendorRequested");
            await producer.writeMessage(message.ToString());

            return(Created(Url.RouteUrl(newVendor.ID), "Your Vendor " + newVendor.Name + " with mobile number " + newVendor.MobileNumber + " is created."));
        }
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("OrderProcessing Service Started");

            while (!cancellationToken.IsCancellationRequested)
            {
                using (var consumer = new ConsumerBuilder <Ignore, string>(consumerConfig).Build())
                {
                    consumer.Subscribe("orderrequests");

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        var result = consumer.Consume(cancellationToken);
                        // handle the message
                        var order = JsonConvert.DeserializeObject <OrderRequest>(result.Message.Value);

                        Console.WriteLine($"Info: OrderHandler => Processing the order for {order.productname}");
                        order.status = OrderStatus.COMPLETED;

                        var producerWrapper = new ProducerWrapper(producerConfig, "readytoship");
                        await producerWrapper.PublishMessage(JsonConvert.SerializeObject(order));
                    }

                    consumer.Close();
                }
            }
        }
Beispiel #6
0
        public static void Main(string[] args)
        {
            ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            ILogger        logger        = loggerFactory.CreateLogger("ChannelsDemo");
            var            cts           = new CancellationTokenSource();

            logger.LogInformation("Starting Producer / Consumer demo");

            var producerFactory = new ProducerFactory <char>(
                cts.Token,
                logger,
                GetWorkingDirectory(),
                (char c) => BitConverter.GetBytes(c));

            var channel  = new UnboundedChannelFacade <char>();
            var producer = new ProducerWrapper <char>(producerFactory, cts.Token, channel);

            Task producerTask = producer.RunAsync();

            RunLoop(channel, logger);
            cts.Cancel();

            Console.WriteLine();
            logger.LogInformation("Waiting for producer to shutdown");
            producerTask.Wait();
            logger.LogInformation("Finished. Exiting.");
        }
Beispiel #7
0
        public async Task <IActionResult> CreateAsync(Raporlar rapor)
        {
            if (ModelState.IsValid)
            {
                try {
                    using (var db = new setur_databaseContext())
                    {
                        await db.Raporlars.AddAsync(rapor);

                        await db.SaveChangesAsync();

                        // Kafkaya rapor hazirlama islemini bildir
                        string serializedOrder = JsonConvert.SerializeObject(rapor);

                        var producer = new ProducerWrapper(this.config, "raporrequests");
                        await producer.writeMessage(serializedOrder);

                        return(Ok(rapor));
                    }
                }
                catch (Exception ex) {
                    return(BadRequest(ex));
                }
            }

            return(BadRequest(ModelState));
        }
        public async Task <ActionServiceResult> SubmitExam(Exam exam)
        {
            StringValues userHeader;

            Request.Headers.TryGetValue("UserID", out userHeader);
            var userID = userHeader.FirstOrDefault().ToString();
            var result = new ActionServiceResult();

            if (userID == null || string.IsNullOrEmpty(userID) || exam == null)
            {
                result.Success = false;
                result.Code    = ApplicationCore.Enums.Enumration.Code.NotFound;
            }
            else
            {
                if (exam.Status == 0)
                {
                    exam.ModifiedDate = DateTime.Now;
                    var message = JsonConvert.SerializeObject(exam);
                    using (var producer = new ProducerWrapper <Null, string>(_producerConfig, "autosubmit"))
                    {
                        await producer.SendMessage(message);
                    }
                    return(new ActionServiceResult()
                    {
                        Success = true,
                        Code = Code.Success,
                        Message = Resources.Success,
                        Data = exam.ExamId
                    });
                }
                else
                {
                    var contest = await _contestRepo.GetEntityByIdAsync(exam.ContestId);

                    if (DateTime.Compare(DateTime.Now, contest.FinishTime) <= 0)
                    {
                        //Todo tinh diem
                        exam.Point   = 10;
                        exam.IsDoing = 0;
                        exam.Status  = 1;
                        await _baseEntityService.Update(exam);

                        result.Data = exam.ExamId;
                    }
                    else
                    {
                        return(new ActionServiceResult
                        {
                            Code = Code.NotFound,
                            Data = null,
                            Message = Resources.NotFound,
                            Success = false
                        });
                    }
                }
            }
            return(result);
        }
Beispiel #9
0
 public async Task Handle(CupcakeOrderPackagedEvent boxedEvent,CancellationToken cancellationToken)
 {
    Console.WriteLine($"Hanlding event - {nameof(CupcakeOrderPackagedEvent)} ");
    //Serialize 
     string serializedOrder = JsonConvert.SerializeObject(boxedEvent.Order);
     var producer = new ProducerWrapper(this._config,"readytoship");
     await producer.writeMessage(serializedOrder);
 }
Beispiel #10
0
 public async Task Handle(CupcakeNewOrderRecievedEvent newOrderEvent,CancellationToken cancellationToken)
 {
    Console.WriteLine($"Hanlding event - {nameof(CupcakeNewOrderRecievedEvent)} ");
    //Serialize 
     string serializedOrder = JsonConvert.SerializeObject(newOrderEvent.Order);
     var producer = new ProducerWrapper(this._config,"orderrequests");
     await producer.writeMessage(serializedOrder);
 }
 private static Responses.Producer MapProducer(ProducerWrapper source)
 {
     return(new Responses.Producer
     {
         Id = source.Id,
         Name = source.Name,
         User = source.User,
         ExpiresAt = source.ExpiresAt,
         Owner = source.Owner
     });
 }
Beispiel #12
0
        public async Task <ActionResult <User> > Post([FromBody] User User)
        {
            User.Id = await this._userrepo.GetNextId();

            var    producer = new ProducerWrapper(this._producerConfig, "testtopic");
            string jsondata = JsonConvert.SerializeObject(User);
            await producer.WriteMessage(jsondata);

            await _userrepo.Create(User);

            return(new OkObjectResult(User));
        }
 private static ProducerWithToken MapProducerWithToken(ProducerWrapper source)
 {
     return(new ProducerWithToken
     {
         Id = source.Id,
         Name = source.Name,
         User = source.User,
         ExpiresAt = source.ExpiresAt,
         Owner = source.Owner,
         Token = source.Token
     });
 }
        public PassengerService(IPassengersDatabaseSettings settings, IKafkaConfig kafkaConfig)
        {
            var client   = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);

            _passengers = database.GetCollection <Passenger>(settings.PassengersCollectionName);

            if (kafkaConfig != null)
            {
                _producer    = new ProducerWrapper(kafkaConfig);
                _kafkaTopics = kafkaConfig.KafkaTopics;
            }
        }
Beispiel #15
0
        public override async Task <Payment> Pay(PaymentRequest request, ServerCallContext context)
        {
            var createdPayment = await _paymentRepository.CreatePayment(_mapper.Map <PaymentEntity>(request));

            if (!createdPayment.Success)
            {
                throw new RpcException(new Status(StatusCode.InvalidArgument, createdPayment.Message));
            }

            ProducerWrapper.ProduceAsync(_producerConfig, "handle-payment", createdPayment.Data);
            return(_mapper.Map <Payment>(createdPayment.Data));

            throw new RpcException(new Status(StatusCode.OK, "In progress"));
        }
        public async Task <Client> save([FromBody] Client client)
        {
            CatalogueRepository.Clients.Add(client);
            CatalogueRepository.SaveChanges();

            string serializedClient = JsonSerializer.Serialize(client);

            Console.WriteLine("========");
            Console.WriteLine("Info: ClientController => Post => send a new client to kafka:");
            Console.WriteLine(serializedClient);
            Console.WriteLine("=========");

            var producer = new ProducerWrapper("clients");
            await producer.writeMessage(serializedClient);

            return(client);
        }
Beispiel #17
0
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                using (var scope = _serviceScopeFactory.CreateScope())
                {
                    var _paymentRepository = scope.ServiceProvider.GetRequiredService <IPaymentRepository>();

                    await ConsumerWrapper.Consume(_consumerConfig, stoppingToken, "handle-payment", async (cr) =>
                    {
                        var entity    = JsonConvert.DeserializeObject <PaymentEntity>(cr.Message.Value);
                        var payResult = await _paymentRepository.Pay(entity.Id);
                        if (!payResult.Success)
                        {
                            var data = new PaymentSagaEntity(entity.Id, payResult.Message);
                            ProducerWrapper.ProduceAsync(_producerConfig, "handle-payment-error", data);
                        }
                    });
                }
            }
Beispiel #18
0
        public async Task <IActionResult> ReportOrderFailureAsync([FromBody] ReportOrderFailureCommand cmd)
        {
            if (!ModelState.IsValid)
            {
                BadRequest();
            }

            var failedOrder = cmd.Order;

            Console.WriteLine("===============Recieved Failure Order====================");
            //TODO: Add command handler and raise event to capture this in the system.
            //Serialize
            string serializedOrder = JsonConvert.SerializeObject(failedOrder);
            var    producer        = new ProducerWrapper(this._config, "orderfailures");
            await producer.writeMessage(serializedOrder);

            return(Ok());
        }
Beispiel #19
0
        public async Task <ActionResult> PostAsync([FromBody] OrderRequest value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var order = JsonConvert.SerializeObject(value);

            Console.WriteLine("=============");
            Console.WriteLine("Info: OrderController => Post => Received a new purchase order:");
            Console.WriteLine(order);
            Console.WriteLine("=============");

            var producer = new ProducerWrapper(this.config, "orderrequests");
            await producer.PublishMessage(order);

            return(Created($"TransactionId", "Your order is in progress"));
        }
Beispiel #20
0
        private static void Setup(
            out List <string> logLines,
            out IWriteBuffer <char> writeBuffer,
            out BlockingLoggingProducer blockingLoggingProducer,
            out ProducerWrapper <char> producer,
            CancellationTokenSource cts = null)
        {
            CancellationToken token = cts == null ? CancellationToken.None : cts.Token;

            logLines = new List <string>();
            ILogger log = MemoryLog.Create(logLines);

            // use a regular logging producer unless an override is passed in
            var factory = new BlockingLoggingProducerFactory(log);

            blockingLoggingProducer = factory.Instance;
            var channel = new UnboundedChannelFacade <char>();

            producer    = new ProducerWrapper <char>(factory, token, channel);
            writeBuffer = channel;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine("OrderProcessing Service Started");

            while (!stoppingToken.IsCancellationRequested)
            {
                var    consumerHelper = new ConsumerWrapper(consumerConfig, "orderrequests");
                string orderRequest   = consumerHelper.ReadMessage();

                //Deserialize
                OrderRequest order = JsonConvert.DeserializeObject <OrderRequest>(orderRequest);

                //TODO:: Process Order
                Console.WriteLine($"Info: OrderHandler => Processing the order for {order.ProductName}");
                order.Status = OrderStatus.Completed;

                //Write to ReadyToShip Queue
                var producerWrapper = new ProducerWrapper(producerConfig, "readytoship");
                await producerWrapper.WriteMessage(JsonConvert.SerializeObject(order));
            }
        }
Beispiel #22
0
        public async Task <IActionResult> PutAsync(int id, [FromBody] string value)
        {
            string serializedOrder = JsonConvert.SerializeObject(value);

            Console.WriteLine("========");
            Console.WriteLine("Info: DepartmentsController => Update => Recieved a updated deparment details:");
            Console.WriteLine(serializedOrder);
            Console.WriteLine("=========");


            using (var db = new IshaMasterContext())
            {
                Dept dept = db.Dept.FirstOrDefault(d => d.DeptId == id);
                if (dept == null)
                {
                    return(NotFound());
                }
                else
                {
                    dept.DeptName = value;
                    db.Dept.Update(dept);
                    var count = db.SaveChanges();
                    // return Ok();
                }
            }

            var message = new StringBuilder();

            message.Append("{ \n event: \n DepartmentUpdated \n entity: Department \n value: { \n");
            message.Append(" ID: ");
            message.Append(id);
            message.Append(",\n Name: ");
            message.Append(serializedOrder);
            message.Append("\n} }");

            var producer = new ProducerWrapper(this._config, "DepartmentUpdated");
            await producer.writeMessage(message.ToString());

            return(Created("departmentId", "Your deparment " + id + " is updated."));
        }
Beispiel #23
0
        public async Task <IActionResult> DeleteAsync(int id)
        {
            string serializedOrder = JsonConvert.SerializeObject(id);

            Console.WriteLine("========");
            Console.WriteLine("Info: DepartmentsController => Deleted => Recieved a deleted deparment details:");
            Console.WriteLine(serializedOrder);
            Console.WriteLine("=========");
            Dept          dept;
            StringBuilder message = new StringBuilder();

            using (var db = new IshaMasterContext())
            {
                dept = db.Dept.FirstOrDefault(d => d.DeptId == id);
                if (dept == null)
                {
                    message.Append("{ \n event: \n DepartmentDeleted \n entity: Department \n value: \n");
                    message.Append("Department record not found");
                    message.Append("\n }");
                }
                else
                {
                    db.Dept.Remove(dept);
                    var count = db.SaveChanges();
                    message = new StringBuilder();
                    message.Append("{ \n event: \n DepartmentDeleted \n entity: Department \n value: { \n");
                    message.Append(" ID: ");
                    message.Append(id);
                    message.Append(",\n Name: ");
                    message.Append(dept.DeptName);
                    message.Append("\n} \n }");
                }
            }

            var producer = new ProducerWrapper(this._config, "DepartmentDeleted");
            await producer.writeMessage(message.ToString());

            return(Created("departmentId", "Your deparment " + id + " is deleted."));
        }
Beispiel #24
0
        public async Task <ActionResult> PostAsync([FromBody] OrderRequest value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            //Serialize
            string serializedOrder = JsonConvert.SerializeObject(value);

            Console.WriteLine("========");
            Console.WriteLine("Info: OrderController => Post => Recieved a new purchase order:");
            Console.WriteLine(serializedOrder);
            Console.WriteLine("=========");

            var producer = new ProducerWrapper(this.config, "orderrequests");
            await producer.writeMessage(serializedOrder);

            //Deserialize
            var value1 = JsonConvert.DeserializeObject <OrderRequest>(serializedOrder);

            _orderRequestRepository.Create(value1);
            return(Created("TransactionId", "Your order is in progress"));
        }
        public async Task <ActionServiceResult> SubmitExam(Examination exam)
        {
            StringValues userHeader;

            Request.Headers.TryGetValue("UserID", out userHeader);
            var userID = userHeader.FirstOrDefault().ToString();
            var result = new ActionServiceResult();

            if (userID == null || string.IsNullOrEmpty(userID) || exam == null)
            {
                result.Success = false;
                result.Code    = Code.NotFound;
                return(result);
            }

            var contest = await _contestRepo.GetEntityByIdAsync(exam.ContestId);

            var oldExam = await _baseEntityService.GetEntityById(exam.ExamId);

            if (contest == null || oldExam == null)
            {
                return(new ActionServiceResult
                {
                    Code = Code.Exception,
                    Data = null,
                    Message = "Entity null",
                    Success = false
                });
            }
            exam.Question     = oldExam.Question;
            exam.Answer       = oldExam.Answer;
            exam.CreatedDate  = oldExam.CreatedDate;
            exam.ModifiedDate = DateTime.Now;
            exam.StartAgain   = oldExam.StartAgain;


            if (oldExam != null && oldExam.Status == 1)
            {
                return(new ActionServiceResult()
                {
                    Success = false,
                    Code = Code.SubmitDone,
                    Message = "Hệ thống đã ghi nhận bài làm trước đó",
                    Data = new
                    {
                        Point = oldExam.Point,
                        ExamID = exam.ExamId
                    }
                });
            }
            if (DateTime.Compare(Utils.GetNistTime(), contest.FinishTime) <= 0)
            {
                var totaltimes = oldExam.TimeUsing;

                totaltimes += ((DateTime.Now - oldExam.ModifiedDate.Value).TotalSeconds / 60.0);

                exam.TimeUsing = totaltimes;


                //Con thoi gian lam bai
                if (totaltimes < contest.TimeToDo)
                {
                    if (exam.Status == 0)
                    {
                        exam.Point = Utils.TinhDiem(exam.Result, oldExam.Answer);
                        //tinh diem
                        var message = JsonConvert.SerializeObject(exam);
                        using (var producer = new ProducerWrapper <Null, string>(_producerConfig, "autosubmit"))
                        {
                            await producer.SendMessage(message);
                        }

                        return(new ActionServiceResult()
                        {
                            Success = true,
                            Code = Code.Success,
                            Message = Resources.Success,
                            Data = new
                            {
                                ExamID = exam.ExamId,
                                Point = exam.Point
                            }
                        });
                    }
                    else
                    {
                        exam.Point = Utils.TinhDiem(exam.Result, oldExam.Answer);
                        //tinh diem
                        await _baseEntityService.Update(exam);

                        return(new ActionServiceResult()
                        {
                            Success = true,
                            Code = Code.Success,
                            Message = Resources.Success,
                            Data = new
                            {
                                ExamID = exam.ExamId,
                                Point = exam.Point
                            }
                        });
                    }
                }
                //Vua het thoio gian lam bai
                else if (totaltimes == contest.TimeToDo)
                {
                    exam.Status = 1;
                    //tinh diem
                    exam.Point = Utils.TinhDiem(exam.Result, oldExam.Answer);
                    await _baseEntityService.Update(exam);

                    return(new ActionServiceResult()
                    {
                        Success = true,
                        Code = Code.Success,
                        Message = Resources.Success,
                        Data = new
                        {
                            ExamID = exam.ExamId,
                            Point = exam.Point
                        }
                    });
                }
                //Het thoi gian lam bai
                else
                {
                    exam.Status = 1;
                    //exam.Point = oldExam.Point;
                    exam.Point = Utils.TinhDiem(exam.Result, oldExam.Answer);
                    await _baseEntityService.Update(exam);

                    return(new ActionServiceResult()
                    {
                        Success = true,
                        Code = Code.Success,
                        Message = Resources.Success,
                        Data = new
                        {
                            ExamID = exam.ExamId,
                            Point = exam.Point
                        }
                    });
                }
            }
            exam.Point = Utils.TinhDiem(exam.Result, oldExam.Answer);;
            //Tinh diem oldexam
            return(new ActionServiceResult
            {
                Code = Code.TimeOut,
                Data = new
                {
                    ExamID = exam.ExamId,
                    Point = oldExam.Point
                },
                Message = "Hết thời gian làm bài",
                Success = false
            });
        }
 public KafkaReservationProducer(ProducerConfig config)
 {
     _config   = config;
     _producer = new ProducerWrapper("libraryreservations", _config);
 }