TechNet Guru Awards May 2017 - Azure - Silver medal
I won the SILVER medal for one of my Azure article on TechNet Guru competition
<appSettings>
<add key="StorageConnectionstring"
value="DefaultEndpointsProtocol=https;AccountName=mailfilestore;AccountKey=pO+lfN4ycIRtC7LncRjUynQ94/Qk0tKnNupYfaXMclH1NCqxwDMXa05PyqwZ0FVaWNgVfVARF4xvCKWq+POkSQ==;EndpointSuffix=core.windows.net"/>
Create a class to handle blob storage saving part, In this example PropertyHandler class is going to do that. In PropertyHandler class, initialize a private variable to hold the storage connection string
private static string storagekey = ConfigurationManager.AppSettings["StorageConnectionstring"];
public static void SaveBlobs () var storageAccount = CloudStorageAccount.Parse(storagekey);
Create blob service client using azure storage account,
//create blob service client var blobClient = storageAccount.CreateCloudBlobClient();
add a configuration into app.config file to define the container,
<add key="container" value="testcontainer"/>
private static string containerstring = ConfigurationManager.AppSettings["container"];
var container = blobClient.GetContainerReference(containerstring);
//create blob container
container.CreateIfNotExists();
container.SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
<add key="imagePath" value="C:\store\images.jpg"/>
//Get a reference to block blob container
var blockBlob = container.GetBlockBlobReference(filename);
upload the image to blob storage, don't forget to set the content type of the image as jpeg, and update blob properties after that.
using (var stream = File.OpenRead(filePath))
{
//upload file stream to block blob
blockBlob.UploadFromStream(stream);
blockBlob.Properties.ContentType = "image/jpeg";
blockBlob.SetProperties();
}
#region Save Image to a blob
string filePath = ConfigurationManager.AppSettings["imagePath"];
var extension = Path.GetExtension(filePath);
var filename = "image" + extension;
//Get a reference to block blob container
var blockBlob = container.GetBlockBlobReference(filename);
using (var stream = File.OpenRead(filePath))
{
//upload file stream to block blob
blockBlob.UploadFromStream(stream);
blockBlob.Properties.ContentType = "image/jpeg";
blockBlob.SetProperties();
}
#endregion
This code sample describes how to store a text file into blob storage, Get the configured file path, and store file in blob storage and set content type as text/plain
#region Save text file to a blob
filePath = ConfigurationManager.AppSettings["filePath"];
extension = Path.GetExtension(filePath);
filename = "file" + extension;
//Get a reference to block blob container
blockBlob = container.GetBlockBlobReference(filename);
using (var stream = File.OpenRead(filePath))
{
//upload file stream to block blob
blockBlob.UploadFromStream(stream);
blockBlob.Properties.ContentType = "text/plain";
blockBlob.SetProperties();
}
#endregion
#region Save video file to a blob
filePath = ConfigurationManager.AppSettings["vedioPath"];
extension = Path.GetExtension(filePath);
filename = "vedio" + extension;
//Get a reference to block blob container
blockBlob = container.GetBlockBlobReference(filename);
using (var stream = File.OpenRead(filePath))
{
//upload file stream to block blob
blockBlob.UploadFromStream(stream);
blockBlob.Properties.ContentType = "video/mpeg";
blockBlob.SetProperties();
}
#endregion
<add key="emailServer" value="smtp.gmail.com"/><add key="emailPort" value="587"/><add key="emailCredentialUserName" value="hansamaligamage@gmail.com"/><add key="emailCredentialPassword" value="SavingHope2016"/><add key="fromAddress" value="hansamaligamage@gmail.com"/><add key="mailTo" value="ham@tiqri.com"/>
class Email
{
public string Subject { get; set; }
public string[] MailRecipientsTo { get; set; }
public string[] MailRecipientsCc { get; set; }
public string Content { get; set; }
public Attachment Image { get; set; }
public Attachment File { get; set; }
public Attachment Vedio { get; set; }
}
public static void SendEmail ()
{
Email email = new Email();
email.MailRecipientsTo = new string[] { ConfigurationManager.AppSettings["mailTo"] };
email.MailRecipientsCc = new string[] { ConfigurationManager.AppSettings["mailTo"] };
email.Subject = "test email";
email.Content = "Hi, How are you doing ? " + "<br/><br/>";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storagekey);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("testcontainer");
Get a reference to image, we stored in testcontainer,
#region Image
CloudBlockBlob blob = container.GetBlockBlobReference("image.jpg");
Download file to a memeory stream, and set content type and create a new attatchment object from it.
var stream = new MemoryStream();
blob.DownloadToStream(stream);
stream.Seek(0, SeekOrigin.Begin);
ContentType content = new ContentType(MediaTypeNames.Image.Jpeg);
email.Image = new Attachment(stream, content);
As same as image, create a new attatchment from text file as well and set the content type as plain, if content type doesnt set properly, it will attatch the file as a invalid type of file.
#region text file
blob = container.GetBlockBlobReference("file.txt");
stream = new MemoryStream();
blob.DownloadToStream(stream);
stream.Seek(0, SeekOrigin.Begin);
content = new ContentType(MediaTypeNames.Text.Plain);
email.File = new Attachment(stream, content);
#endregion
create the video attatchment as well,
#region vedio file
blob = container.GetBlockBlobReference("vedio.mp4");
stream = new MemoryStream();
blob.DownloadToStream(stream);
stream.Seek(0, SeekOrigin.Begin);
content = new ContentType("video/mpeg");
email.Vedio = new Attachment(stream, content);
#endregion
SendMail(email);
Create a method to send email as below, its going to construct the email and sends it
private static void SendMail(Email email)
{
try
{
SmtpClient smtpClient = EmailClientBuilder();
var emailMessage = MessageBuilder(email);
smtpClient.Send(emailMessage);
}
catch (Exception ex)
{
throw ex;
}
}
Create a method to return smtpclient object, initialize a smtpclient instance and set email configurations as below.
private static SmtpClient EmailClientBuilder()
{
string emailServer = ConfigurationManager.AppSettings["emailServer"];
int emailPort = Convert.ToInt32(ConfigurationManager.AppSettings["emailPort"]);
string emailCredentialUserName = ConfigurationManager.AppSettings["emailCredentialUserName"];
string emailCredentialPassword = ConfigurationManager.AppSettings["emailCredentialPassword"];
SmtpClient smtpClient = new SmtpClient(emailServer, emailPort);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(emailCredentialUserName, emailCredentialPassword);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
return smtpClient;
}
In MessageBuilder method, populate MailMessage object using Email object we constructed earlier.
private static MailMessage MessageBuilder(Email email)
{
string fromAddress = ConfigurationManager.AppSettings["fromAddress"];
MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromAddress);
mail.Body = email.Content;
mail.Subject = email.Subject;
mail.IsBodyHtml = true;
if (email.Image != null)
mail.Attachments.Add(email.Image);
if (email.File != null)
mail.Attachments.Add(email.File);
if (email.Vedio != null)
mail.Attachments.Add(email.Vedio);
foreach (var mailRecipient in email.MailRecipientsTo)
{
mail.To.Add(new MailAddress(mailRecipient));
}
return mail;
}
public
Scheduler(){}protected
override
void OnStart(string[] args){}protected
override
void OnStop(){}protected
override
void OnStart(string[] args) { Debugger.Launch(); logger.Info("Service is started."); try { Timer tmrEmailScheduler =
new
Timer(); tmrEmailScheduler.Interval = 120000; tmrEmailScheduler.Elapsed += tmrEmailScheduler_Elapsed; tmrEmailScheduler.Start(); ProcessEmail.CreateEmail(); } catch
(Exception ex) { logger.Error(ExceptionHandler.ToLongString(ex)); } }private
void
tmrEmailScheduler_Elapsed(object
sender, ElapsedEventArgs e) { logger.Info("Timer is ticked"); ProcessEmail.CreateEmail(); }protected
override
void OnStop() { logger.Info("Service is stopped."); tmrEmailScheduler.Stop(); }[RunInstaller(true)]public
partial
class ProjectInstaller : System.Configuration.Install.Installer{ private
ServiceProcessInstaller process; private
ServiceInstaller service; public
ProjectInstaller() { InitializeComponent(); process =
new
ServiceProcessInstaller(); process.Account = ServiceAccount.LocalSystem; service =
new
ServiceInstaller(); service.ServiceName =
"test Service"; Installers.Add(process); Installers.Add(service); } }