Note: First Message will save on Database
and after that that message will send to Queue. Before that, we will go to
azure portal and Storage Account. In Storage Account on Queue we are creating,
a queue name is mailsending and smssending.
Next, Declare a Class file for SMS and mail
sending and Class Name is SendOTPToStorageQueueService.
In addition, write below code
using
Satya.Models;
using
Microsoft.WindowsAzure.Storage;
using
Microsoft.WindowsAzure.Storage.Queue;
using
Newtonsoft.Json;
using System;
using
System.Collections.Generic;
using
System.Diagnostics;
using
System.Linq;
using
System.Net.Http;
using
System.Net.Http.Headers;
using
System.Web;
namespace
Satya.Utils
{
public class SendOTPToStorageQueueService
{
public
SendOTPToStorageQueueService()
{
var url = "http://satyamasterapi.azurewebsites.net/api/"; // for
API
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
HttpClient client = new HttpClient();
public int
OTPSendDetails(string mid, string mobno, string sss)
{
string mode = "Mobile";
Master_OTPSendDetail otpInfo = new Master_OTPSendDetail();
otpInfo.User_RegistrationId = 1;
if (mode == "email")
{
otpInfo.IsEmail = true;
otpInfo.IsMobile = false;
}
else
{
otpInfo.IsEmail = false;
otpInfo.IsMobile = true;
}
otpInfo.SendFrom = "satya";
otpInfo.SendTO = mobno;
otpInfo.MessageId = "1";
otpInfo.OTP = sss;
otpInfo.DeliveryStatus = "Fail";
otpInfo.InsertedOn = DateTime.Now;
otpInfo.InsertedBy = 1;
HttpResponseMessage res =
client.PostAsJsonAsync("MasterOTPSendDetail",
otpInfo).Result;
int Master_OTPDetailId
= Convert.ToInt32(res.Content.ReadAsStringAsync().Result);
CloudStorageAccount
storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=satyadmin;AccountKey=I/mTWtgGpgiDTgqF45BrOwI8dssdsd9wjwtv8/dsdsdsds+ASJ9Uid3z4NqQ==");
CloudQueueClient
queueClient = storageAccount.CreateCloudQueueClient();
CloudQueue queue = queueClient.GetQueueReference("smssending");
queue.CreateIfNotExists();
Master_MobileOTPMessage
sendsmsMessage = new Master_MobileOTPMessage() {
Message_Id = 1, Message = sss, MobileNo = mobno, IsSend = false };
queue.AddMessage(new CloudQueueMessage(JsonConvert.SerializeObject(sendsmsMessage)));
Trace.TraceInformation("Created
queue message for AdId {0}", mid);
return
Master_OTPDetailId;
}
public int
MailSendDetails(string mid, string
frommailid, string tomailid, string sss, bool isSend)
{
string mode = "email";
Master_OTPSendDetail otpInfo = new Master_OTPSendDetail();
otpInfo.User_RegistrationId = null;
if (mode == "email")
{
otpInfo.IsEmail = true;
otpInfo.IsMobile = false;
}
else
{
otpInfo.IsEmail = false;
otpInfo.IsMobile = true;
}
otpInfo.SendFrom = frommailid;
otpInfo.SendTO = tomailid;
otpInfo.MessageId = "1";
otpInfo.OTP = sss;
otpInfo.DeliveryStatus = "Fail";
otpInfo.InsertedOn = DateTime.Now;
otpInfo.InsertedBy = 1;
otpInfo.IsActive = true;
otpInfo.IsDelete = false;
HttpResponseMessage res =
client.PostAsJsonAsync("MasterOTPSendDetail",
otpInfo).Result;
int
Master_OTPDetailId = Convert.ToInt32(res.Content.ReadAsStringAsync().Result);
CloudStorageAccount
storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=satyadmin;AccountKey=I/mTWtgGpgiDTgqF45BrOwI8dssdsd9wjwtv8/dsdsdsds+ASJ9Uid3z4NqQ==");
CloudQueueClient
queueClient = storageAccount.CreateCloudQueueClient();
CloudQueue queue =
queueClient.GetQueueReference("mailsending");
queue.CreateIfNotExists();
Master_MailOTPMessage
sendsmsMessage = new Master_MailOTPMessage() {
Message_Id = 1, FromEmailId = frommailid, ToEmailId = tomailid, Message = sss,
IsSend = false };
queue.AddMessage(new CloudQueueMessage(JsonConvert.SerializeObject(sendsmsMessage)));
Trace.TraceInformation("Created
queue message for AdId {0}", mid);
return
Master_OTPDetailId;
}
}
}
Next, Add Web Job for Mail Sending. (Storage
Account connection String)
In App Config File
<connectionStrings>
<!-- The format of the
connection string is "DefaultEndpointsProtocol=https;AccountName=NAME;AccountKey=KEY"
-->
<!-- For local execution,
the value can be set either in this config file or through environment
variables -->
<add name="AzureWebJobsDashboard" connectionString="DefaultEndpointsProtocol=https;AccountName=satyaadmin;AccountKey=I/xcxccxcxfddgdgdf/GX6XB9gSugWdA51t3N71tA+dffd==;EndpointSuffix=core.windows.net" />
<add name="AzureWebJobsStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=
satyaadmin;AccountKey=sLA1TmwIgXMlKGp0d/ttg4g/gdfgfdgdfgdfgdfggg+dfdffdg==;EndpointSuffix=core.windows.net" />
</connectionStrings>
Go TO Functions
using System;
using
System.Collections.Generic;
using System.IO;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
Microsoft.Azure.WebJobs;
using
System.Net.Mail;
namespace
satyaMailSendingWebJOB
{
public class Functions
{
// This function will
get triggered/executed when a new message is written
// on an Azure Queue
called queue.
//public static void
ProcessQueueMessage([QueueTrigger("mailsending")] string message,
TextWriter log)
//{
public static void
ProcessQueueMessage([QueueTrigger("mailsending")] Master_MailOTPMessage
mailmessage, TextWriter log)
{
MailSender(mailmessage.Message_Id,
mailmessage.FromEmailId, mailmessage.ToEmailId, mailmessage.Message,
mailmessage.IsSend);
//
log.WriteLine(message);
}
public static void
MailSender(int Message_Id, string FromEmailId, string ToEmailId,
string message, bool IsSend)
{
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(ToEmailId));
msg.From = new MailAddress("satya@gmail.com
", "satya company");
msg.Subject = "Test
Mail";
string body = "Dear
User,<br/>";
body += "<br/>Please
use " + message + " " + "as
the Onte Time Password, Please do not share this anyone. This Password is valid
for 2 minutes.";
body += "<br/>For
Further Queries , please write us at satya@gmail.com
(satya@gmail.com) or call us at our given contact.";
body += "<br/>
Regards";
body += "<br/>
satya@gmail.com TEAM ";
msg.Body = body; //"Test
message using smtp.office365.com on Azure from a Web App";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new
System.Net.NetworkCredential("satya@gmail.com", "satya2018");
client.Port = 587;
client.Host = " satya@gmail.com
";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (Exception ex)
{
}
}
}
}
Next In Program.cs
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using System.Threading.Tasks;
using
Microsoft.Azure.WebJobs;
namespace satyaMailSendingWebJOB
{
// To learn more about Microsoft Azure
WebJobs SDK, please see https://go.microsoft.com/fwlink/?LinkID=320976
class Program
{
// Please set the
following connection strings in app.config for this WebJob to run:
//
AzureWebJobsDashboard and AzureWebJobsStorage
static void Main()
{
var config = new JobHostConfiguration();
if
(config.IsDevelopment)
{
config.UseDevelopmentSettings();
}
var host = new JobHost(config);
// The following code
ensures that the WebJob will be running continuously
host.RunAndBlock();
}
}
}
Next, Add Web Job for SMS Sending. (Storage
Account connection String)
In App Config File
<connectionStrings>
<!-- The format of the
connection string is
"DefaultEndpointsProtocol=https;AccountName=NAME;AccountKey=KEY" -->
<!-- For local execution,
the value can be set either in this config file or through environment
variables -->
<add name="AzureWebJobsDashboard" connectionString="DefaultEndpointsProtocol=https;AccountName=satyaadmin;AccountKey=I/xcxccxcxfddgdgdf/GX6XB9gSugWdA51t3N71tA+dffd==;EndpointSuffix=core.windows.net" />
<add name="AzureWebJobsStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=
satyaadmin;AccountKey=sLA1TmwIgXMlKGp0d/ttg4g/gdfgfdgdfgdfgdfggg+dfdffdg==;EndpointSuffix=core.windows.net" />
</connectionStrings>
Go TO Functions
using System;
using
System.Collections.Generic;
using System.IO;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
Microsoft.Azure.WebJobs;
using
Newtonsoft.Json.Linq;
using RestSharp;
namespace
satyaSmsSendingsWebJob
{
public class Functions
{
// This function will
get triggered/executed when a new message is written
// on an Azure Queue
called queue.
public static void
ProcessQueueMessage([QueueTrigger("smssending")] Master_MobileOTPMessage message, TextWriter log)
{
SMSSender(message.Message_Id,
message.Message, message.MobileNo, message.IsSend);
}
public static void SMSSender(int
Message_Id, string Message, string MobileNo, bool IsSend)
{
var jsonObject
= new JObject
{
{"from", "satya"},
{"to","91"+MobileNo},
{"text",Message+"
"+"is OTP for your satya Registration. OTP Valid for 2
minutes. Do not share this OTP with anyone."},
};
string sss = EncodingForBase64.Base64Encode("satya:satya@1234");
// string authEncoded =
EncodingForBase64.base64_encode('myuserame:password');
var client = new RestClient("https://api.infobip.com/sms/1/text/single");
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Basic
" + sss);
request.AddParameter("application/json",
jsonObject, ParameterType.RequestBody); //"{\"from\":\"InfoSMS\",
\"to\":\"9040049188\",\"text\":\"Test
SMS.\"}", ParameterType.RequestBody);
IRestResponse response =
client.Execute(request);
}
}
}
Next in Program.cs
using System;
using System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
Microsoft.Azure.WebJobs;
namespace
SatyaSmsSendingsWebJob
{
// To learn more about Microsoft Azure
WebJobs SDK, please see https://go.microsoft.com/fwlink/?LinkID=320976
class Program
{
//Please set the
following connection strings in app.config for this WebJob to run:
//
AzureWebJobsDashboard and AzureWebJobsStorage
static void Main()
{
var config = new JobHostConfiguration();
if
(config.IsDevelopment)
{
config.UseDevelopmentSettings();
}
var host = new JobHost(config);
// The following code
ensures that the WebJob will be running continuously
host.RunAndBlock();
}
//static void
Main(string[] args)
//{
// JobHost host = new JobHost();
// host.RunAndBlock();
//}
}
}
No comments:
Post a Comment