Pub Sub Service in asp.net core

 Controller

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc;

using QHSE.Services.Common;

using System.Collections.Generic;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Azure.WebJobs.Extensions.WebPubSub;

using Azure.Messaging.WebPubSub;

using Microsoft.Extensions.Configuration;

using System.Threading.Tasks;

using System;

using Microsoft.Graph;


namespace QHSE.API.Controllers.Common

{

    [Route("api/alerts")]

    [ApiController]

    public class AlertController : ControllerBase

    {

        private readonly IAlertService _alertService;

        private readonly WebPubSubServiceClient _serviceClient;

        private readonly string _hubName;


        public AlertController(IAlertService alertService, IConfiguration configuration)

        {

            _alertService = alertService;

            //string connectionString = configuration["WebPubSub:ConnectionString"];

            string connectionString = " ";

            _hubName = " ";


           // _hubName = configuration["WebPubSub:Hub"];


            _serviceClient = new WebPubSubServiceClient(connectionString, _hubName);


        }

        [HttpPost]

        public async Task<IActionResult> ComposeAlert(string docname, [FromBody] Dictionary<string, object> fieldValues, string formurl = "", string btncaption = "", string alerttype = "",  string message="")

        {

            var result = _alertService.ComposeAlert( message);


            //var result = _alertService.ComposeAlert(docname, fieldValues, formurl, btncaption, alerttype, message);

            if (result.Successful)

            {

                return Ok(new { Response = result.Response, Url = result.Url });

            }

            else

            {

                return BadRequest(result.Error.Message);

            }



            var groupName = "AWCGroup";

            await _serviceClient.SendToGroupAsync(groupName, message);


            return Ok();


        }


        //[HttpPost]

        //[Route("notification")]

        //public IActionResult SendNotification(string msgbody, string custName, int UserPK = 1, int UserCompanyPK = 0)

        //{

        //    var result = _alertService.SendNotification(msgbody, custName, UserPK, UserCompanyPK);

        //    if (result.Successful)

        //    {

        //        return Ok(result.Response);

        //    }

        //    else

        //    {

        //        return BadRequest(result.Error.Message);

        //    }

        //}


        //[HttpPost]

        //[Route("notification")]

        //public async Task<IActionResult> PostAsync([FromForm] string message)

        //{

        //    await _alertService.ComposeAlert(message);

        //    return Ok();

        //}


        //[HttpPost("ComposeAlert")]

        //public IActionResult ComposeAlert([FromForm] string message)

        //{

        //    try

        //    {

        //        var result =_alertService.ComposeAlert(message);

        //        if (result.Successful)

        //        {

        //            return Ok(result.Response);

        //        }

        //        else

        //        {

        //            return BadRequest(result.Error.Message);

        //        }

        //    }

        //    catch (Exception ex)

        //    {

        //        return StatusCode(500, ex.Message);

        //    }

        // }


        //[HttpPost("SendNotification")]

        //public IActionResult SendNotification([FromBody] string message)

        //{

        //    try

        //    {

        //        var result = _alertService.SendNotification(message);

        //        if (result.Successful)

        //        {

        //            return Ok(result.Response);

        //        }

        //        else

        //        {

        //            return BadRequest(result.Error.Message);

        //        }

        //    }

        //    catch (Exception ex)

        //    {

        //        return StatusCode(500, ex.Message);

        //    }

        //}


    }


}



Interface :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace QHSE.Services.Common
{
    public interface IAlertService
    {
        public FCMNotificationStatus ComposeAlert(string docname, Dictionary<string, object> fieldValues, string formurl = "", string btncaption = "", string alerttype = "", string message = null);
        public FCMNotificationStatus ComposeAlert(string message);
        //public FCMNotificationStatus SendNotification(string msgbody, string custName, int UserPK = 1, int UserCompanyPK = 0);

    }
}


Service  :

using Azure;
using Azure.Core;
using Azure.Messaging.WebPubSub;
using QHSE.DBEntity;
//using QHSE.IRepository.Common;
using QHSE.Models.Common;
using QHSE.Models.General;
using QHSE.Models.Organization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace QHSE.Services.Common
{
    public class AlertPubSubService : IAlertService
    {
        //private EmailConfig _emailConfig;
        //public AlertsService(IOptions<EmailConfig> _emailConfig)
        //{
        //    this._emailConfig = _emailConfig?.Value ?? throw new ArgumentNullException(nameof(_emailConfig));

        //}

        public FCMNotificationStatus ComposeAlert(string docname = "", Dictionary<string, object> fieldValues = null, string formurl = "", string btncaption = "", string alerttype = "", string message = "")
        {
            FCMNotificationStatus result = new FCMNotificationStatus();
            try
            {
                using (var _DBEntity = new CommonDbEntity())
                {
                    List<GenMessagingCenterRecipients> recipients = new List<GenMessagingCenterRecipients>();
                    recipients = (from msg in _DBEntity.messagetemplate
                                  join recp in _DBEntity.GenMessagingCenterRecipients on msg.msgtemplate_mst_pk equals recp.msgtemplate_mst_fk
                                  join usr in _DBEntity.SecUserProfile on recp.recipientpk equals usr.usermaster_pk
                                  where msg.document_name == docname
                                  select recp).ToList();

                    foreach (var recipient in recipients)
                    {
                        int userpk = recipient.recipientpk;
                        List<SecUserLoginDetail> userloglist = new List<SecUserLoginDetail>();
                        if (userpk > 0)
                        {
                            userloglist = (from ul in _DBEntity.userLoginDetails
                                           where ul.sec_user_master_fk == userpk
                                           && ul.sec_user_deviceid != null
                                           select ul
                                          ).OrderByDescending(o => o.sec_user_login_detail_pk).ToList();
                        }
                        SecUserLoginDetail userlogindetails = new SecUserLoginDetail();
                        if (userloglist.Count > 0)
                        {
                            userlogindetails = (from userlogindetail in _DBEntity.userLoginDetails
                                                where userlogindetail.sec_user_login_detail_pk == (userloglist.Select(s => s.sec_user_login_detail_pk).Max())
                                                && userlogindetail.sec_user_deviceid != null
                                                select userlogindetail).FirstOrDefault();
                        }

                        MessageTemplateSF msgTemplate = _DBEntity.messagetemplate.Where(w => w.document_name == docname && w.intext_flag == "I").FirstOrDefault();
                        List<MessageFieldSF> msgFields = new List<MessageFieldSF>();
                        if (msgTemplate != null)
                        {
                            msgFields = _DBEntity.messagefield.Where(w => w.msgtemplate_mst_fk == msgTemplate.msgtemplate_mst_pk && w.active_flag == true).ToList();
                        }
                        List<MessageLog> messageLog = new List<MessageLog>();

                        string msgBody = msgTemplate != null ? msgTemplate.default_sms_msg : "";
                        if (fieldValues != null)
                        {
                            foreach (var field in msgFields)
                            {

                                msgBody = msgBody.Replace("&lt;&lt;" + field.db_field_name + "&gt;&gt;", fieldValues[field.db_field_name].ToString());
                                msgBody = msgBody.Replace("<<" + field.db_field_name + ">>", fieldValues[field.db_field_name].ToString());
                            }
                        }
                        messageLog.Add(new MessageLog()
                        {
                            messagelogpk = 0,
                            process = msgTemplate.document_name,
                            message_type = msgTemplate.message_type,
                            receiver_fk = userpk,
                            message_header = msgTemplate.document_name,
                            message_body = msgBody,
                            action_url = formurl,// msgTemplate.default_doc_path,
                            generated_date = DateTime.Now,
                            sent_date = DateTime.Now,
                            sent_status = "Sent",
                            active_flag = true,
                            created_by_fk = 1,
                            created_dt = DateTime.Now,
                            version_no = 1,
                            delete_status = false,
                            sender_fk = userpk,
                            read_status = "Un Read"
                        });
                        int cnt = _DBEntity.messagelog.Where(x => x.receiver_fk == userpk && x.message_body == msgBody && x.created_dt.Date == DateTime.Today).Count();
                        if (cnt == 0 || (alerttype == "Alert" && cnt < 2))
                        {
                            if (alerttype != "Alert")
                            {
                                result = SendNotification(docname, msgBody, null, msgTemplate.message_type, userlogindetails.sec_user_deviceid, 1, "", formurl, btncaption);

                                //result = SendNotification(docname, msgBody, null, msgTemplate.message_type, userlogindetails.sec_user_deviceid, 1, "", formurl, btncaption);



                            }
                            if (messageLog.Count > 0)
                            {
                                _DBEntity.messagelog.AddRange(messageLog);
                            }
                            _DBEntity.SaveChanges();
                        }
                    }


                    return result;
                }


                result = SendNotification(message);
                // return result;



                //SendNotification(docname, msgBody, null, msgTemplate.message_type, userlogindetails.sec_user_deviceid, 1, "", formurl, btncaption);


            }
            catch (Exception ex)
            {
                result.Successful = false;
                result.Response = null;
                result.Error = ex;
                return result;
            }
        }

        private FCMNotificationStatus SendNotification(string msgtitle, string msgBody, object value, string message_type, string sec_user_deviceid, int v1, string v2, string formurl, string btncaption)
        {
            FCMNotificationStatus result = new FCMNotificationStatus();


            string connectionString = "Endpoint=https://qhse-dev-webpubservice.webpubsub.azure.com;AccessKey=VRJKBW5zvup8d2Thh3INj7K2r6t6XZY+19tNUvMDQb4=;Version=1.0;";
            // Either generate the URL or fetch it from server or fetch a temp one from the portal
            var serviceClient = new WebPubSubServiceClient(connectionString, "qhseclient1");
            var url = serviceClient.GetClientAccessUri(userId: "anil@gmail.com");


            string userEmail = "anil@gmail.com";
            serviceClient.AddUserToGroup("qhseclient1", userEmail);




            var data = new
            {
                notification = new
                {
                    title = msgtitle,
                    body = msgBody,
                    name = "Anil Dwivedi",
                    type = message_type,

                },
                //to = deviceId
            };

            string jsonString;
            jsonString = JsonSerializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(jsonString);


            //Avoid sending messages to users who do not exist.
            if (serviceClient.UserExists(userEmail).Value)
            {


                serviceClient.SendToUser(userEmail, jsonString);
                //Index++;

            }
            result.Response = jsonString;
            result.Url = url.ToString();



            result.Successful = true;
            result.Error = null;

            return result;
        }

        #region Test Validate
        public string ValidateSave(int Cnt)
        {
            string result = "Success";
            try
            {
                using (var _DBEntity = new CommonDbEntity())
                {


                    List<MessageLog> messageLog = new List<MessageLog>();


                    messageLog.Add(new MessageLog()
                    {
                        messagelogpk = 0,
                        process = "Test",
                        message_type = "Info",
                        receiver_fk = 1,
                        message_header = "Test",
                        message_body = "Testing" + Cnt,
                        action_url = "",
                        generated_date = DateTime.Now,
                        sent_date = DateTime.Now,
                        sent_status = "Not Sent",
                        active_flag = true,
                        created_by_fk = 1,
                        created_dt = DateTime.Now,
                        version_no = 1,
                        delete_status = false
                    });

                    if (messageLog.Count > 0)
                    {
                        _DBEntity.messagelog.AddRange(messageLog);
                    }
                    _DBEntity.SaveChanges();
                }
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion


        //surya code start

        public FCMNotificationStatus SendNotification(string msg)
        {
            FCMNotificationStatus result = new FCMNotificationStatus();


            string connectionString = " ";
            // Either generate the URL or fetch it from server or fetch a temp one from the portal
            var serviceClient = new WebPubSubServiceClient(connectionString, "qhseclient1");
            var url = serviceClient.GetClientAccessUri(userId: "anil@gmail.com");


            string userEmail = "anil@gmail.com";
            serviceClient.AddUserToGroup("qhseclient1", userEmail);



           
            var data = new
            {
                notification = new
                {
                    title = "Alice",
                    body = "Booking Confirmed",
                    name = "Anil Dwivedi",
                    type = "info",

                },
                //to = deviceId
            };

            string jsonString;
            jsonString = JsonSerializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(jsonString);


            //Avoid sending messages to users who do not exist.
            if (serviceClient.UserExists(userEmail).Value)
            {


                serviceClient.SendToUser(userEmail, jsonString);
                //Index++;

            }
            result.Response = jsonString;
            result.Url = url.ToString();



            result.Successful = true;
            result.Error = null;

            return result;


        }

        public FCMNotificationStatus ComposeAlert(/*string docname, Dictionary<string, object> fieldValues, string formurl = "", string btncaption = "", string alerttype = ""*/ String message)
        {
            string docname = "Anil Sender message";
            string msgBody = "Notification message body";
            string messageType = null; // Assuming messageType is not provided in this case
            string deviceID =  "12344";
            int userId = 1;
            string formURL = "";
            string buttonCaption = "View Details";

            var result= SendNotification(docname, msgBody, null, messageType, deviceID, 1, "", formURL, buttonCaption);


            //var result = SendNotification(message);
            return result;

            //throw new NotImplementedException();
        }
 
 
 


    }


  

    public class FCMNotificationStatus
    {
        public bool Successful { get; set; }
        public string Response { get; set; }
        public string Url { get; set; }
        public Exception Error { get; set; }
    }

}


If u wanna check msg then try code in Console application

// See https://aka.ms/new-console-template for more information
using Azure.Messaging.WebPubSub;
using Websocket.Client;

//Console.WriteLine("Hello, World!");
//var connectionString = "Endpoint=https://qhsedevpubsubservice.webpubsub.azure.com;AccessKey=6JV5ETlk9R5B85a9lJwaoBp5OIemvsCUB9i3tZKRvSo=;Version=1.0;";
//var hub = "qhsedevpubsubHub1";
//// Either generate the URL or fetch it from server or fetch a temp one from the portal  
//var serviceClient = new WebPubSubServiceClient(connectionString, hub);
//var url = serviceClient.GetClientAccessUri();
//using (var client = new WebsocketClient(url))
//{
//    client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
//    await client.Start();
//    Console.WriteLine("I'm connected.");
//    Console.Read();
//}
try
{
    string connectionString = " ";
    // Either generate the URL or fetch it from server or fetch a temp one from the portal
    var serviceClient = new WebPubSubServiceClient(connectionString, "qhseclient1");
    var url = serviceClient.GetClientAccessUri(userId: "anil@gmail.com");



    using (var client = new WebsocketClient(url))
    {
        // Disable the auto disconnect and reconnect because the sample would like the client to stay online even no data comes in
        client.ReconnectTimeout = null;
        client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
        await client.Start();
        Console.WriteLine("Connected.");
        Console.Read();
    }
}
catch (Exception ex)
{ }


Comments

Popular posts from this blog

Show Toaster message Simple example in HTML

₹2.5 Lakh ki Alkaline Machine: Investment Ya Hype?" Japan Technology Wale Alkaline Water Systems: Science Ya Sirf Marketing? "Alkaline Water Machines — Health Ke Naam Par Business?

SQL interview questions