Simple smtp email with html body

Smtp Email

This post describes an easy way to send a email using a smtp server.

Smtp Client

To create a smtp client, we need to specify a smtp host and port, port is an optional parameter.
for some Smtp clients, we need to provide credintials. we need a NetworkCredintial instance for that. We can use Secure Socket Layer (SSL) to encrypt the connection.

SMTP Client

This shows how to instantiate a smtp client, If you are using gmail, host is smtp.gmail.com or else some specific smtp server. If port is available, specify the port

Mail Message

After working with Smtp client, then we need is MailMessage object.

Mail Message

MailMessage from and to should be MailAddress instances.
In this example we used IsBodyHtml attribute, to notify mail body can be a html string.

Complete code is shown below

Complete code to send an email

You can clone sample code from this github repository and play with it, https://github.com/hansamaligamage/Scheduler

NLog Configurations

Many of the systems, we develop today needs some kind of a logging/tracing mechanism to identify issues or any kind of information.

NLog

NLog is a free logging framework to log various kind of messages into a specified place. We can use NLog in a .NET environment, as well as with Xamarin and Windows phone.

Logging

If we want to log a message from our application, We can use EventViewer without any libraries. But If we want to share the log file with someone else and analyse it in the future, we can’t do that with Eventviewer.
So we have to go for a logging framework if we want to write messages into a file or a database.

Logging Frameworks

We can use any of these frameworks for logging purpose, Log4net, NLog, ELMAH, Microsoft Enterprise Library, NSpring. ELMAH is a web logging framework, All the other frameworks can be used with any .NET type of application.
When we use NLog or Log4net for logging, it takes just few minutes to integrate it to the application, But performancewise its not the same. NLog is much faster than Log4net and as well as all the above mentioned logging frameworks.
NSpring also easy to setup, but it requires more coding to log a message. With a large scale enterprise application, It will be tedious to work with NSpring.
Microsoft Enterprise Library (EntLib) is much faster, But need heavy configurations and coding to work with it. ELMAH is a web logger, It’s going to log the messages into a xml file by default.

If you application needs file logging and more performance, better to go with NLog or NSpring. We can use Log4net also, it’s not that much faster, but easy to setup and use it in the application

Install NLog

Latest stable version of NLog is NLog 4.3.5.
With Nuget Package manager, I installed NLog,

NLog installation

NLog Targets

NLog targets are used to show, store or pass the message into another destination. Some commonly used NLog targets are shown below,

  • Console : writes message to a console window.
  • Event Log : writes message to event viewer.
  • Debugger : writes messagee to the attatched debugger.
  • File : writes log message to a file.
  • Database : store log message in database.
  • Memory : can write log message into a arraylist in memory.
  • Mail : send log message by email.
  • Method call : For log message, calls specific static method.
  • Network : send log message over a network.
  • Service : calls a web service for each log message.

And if these targets dont satisfy your requirements, you can create your own targets as well, (custom target)

Target Layout

Target layout means how our log message is going to display, in which format, which order. We can create custom layout renders as well. Commonly used layouts are as follows,

  • ${callsite} : Class name, method name or source information of the log message.
  • ${callsite-linenumber} : line no of call site source.
  • ${date} : date and time
  • ${exception} : exception details
  • ${level} : log level
  • ${logger} : logger name
  • ${longdate} : date and time in long format.
  • ${message} : log message.
  • ${stacktrace} : stack trace

NLog rules

NLog rules are called as a log routing table. It’s going to matches with a target and writes into a log with specified layout. Some of the attributes in NLog rules,

  • name : logger name,
  • minlevel : minimum log level for a rule to match
  • maxlevel : maximum log level for a rule to match
  • level : single log level for a rule to match
  • levels : comma seperated list of logs for a rule to match
  • write to : comma seperated list of targets to be written when a rule matches
  • final : no further rules are processed when this rule matches
  • enabled : going to disable/enable rules

Nlog levels

One thing to note, In these level attribute, log messages are ordered from type. Trace is the minlevel log type, then Debug, Info, Warn, Error and Fatal.

  • Trace level can be used when we need to notify the begining and end of a method
  • Debug logs, we can identify whether session is expired, user is authenticated
  • Info logs are used for more generic scenarios like, Email sent.
  • Warn level can be used to notify warnings
  • Error logs are used for exceptions and when application crashes.
  • Fatal logs are highest level, used for most important cases.

Let’s see what’s in action

In configuration file, I have configured log type and log level, I have used file logging, Trace as a minimum logging level.

configuration file

In code, I have written like this,

code i have written

Let’s check how it’s written in the log file

output seeems like this

In output, we can see the layout has been applied, ${longdate} ${callsite} ${callsite-linenumber} ${date} ${level} ${message}

How to use multiple targets

Let’s see how to add multiple targets for logging

configuration file

In configuration file, i added two targets, one is to log into a file, other target is to log into a console window

configuration file

File logging output is same as previous output, console output is seems like this. In console logging, I used a different layout like this, ${date} ${callsite} ${level} ${message} and minimmum log level is added as Warning level, So output got changed like this.

Some resources i referred,

I creted a github repo to these code samples, Please have a look, https://github.com/hansamaligamage/Logger

LINQ comes to rescue!

Today, I’m going to explain a very small but tricky code part, day to day we use this, but never give it a second glance, because of that we miss this in many places :)

Let’s first create a simple class

Car class

we have list of cars, like this.

List of cars

I want to set Milege property as ‘100’ when year is ‘2015’
so, what’s the method comes into your mind ?
for loop, foreach or while loop, Iterations are not so good when it comes to the performance.

With the help of LINQ, we can perform the filtering and modification both in just one line :)

In LINQ world, we have many operations to filter, to projection, to modify and many more.

Solution from LINQ,

LINQ query to filter and modify list values.

Yes, It’s difficult to read the code though, But if you have performance concerns, and want to write the program with few lines of code, You can get use of this LINQ query.

ODATA Reads with Parameters

Data READs with Parameters

In this post, We’ll focus on how to read a OData service with a parameter.

Service method with a parameter

Get Method With a Parameter.

Now, we’ll see how to retrieve data with a parameter,

Url in the browser

Get Method Url With a Parameter.

In browser, we can see only filtered students. in url, append the parameter with values.

Power Query Window

Power Query editor.

From the Power Query window, we can see dataset like this.

I could create a github repo for this code sample, Please feel free to check it, https://github.com/hansamaligamage/ODATAExample

ODATA Reads

Data READs

Let’s start with a newer version of ODATA to access data from a existing service, In this solution I have used Web API 2.2 with ODATA v4

ODATA v4 package

Visual Studio has a built in package to create ODATA v4 services, Package contains all the libraries required to create a ODATA v4 endpoint.

Integrate ODATA v4 package into solution

We can add the necessary OData package into solution like this, Select Microsoft ASP.NET Web API 2.2 for OData v4.0

nuget package management store.

All the relevant libraries are installing

All the ODATA related libraries are installing.

Register OData endpoint

Register service endpoint in Register method of WebApiConfig file

Register service endpoints.

In line no 22, I have exposed the Student entity, Data read method is implemented in OData controller, StudentController

Student Controller implements OData Controller

Student Controller

StudentController inherits from OData Controller, So all the CRUD operations related to student can be implemented in this controller.

How it works in the browser

now ping to the OData endpoint,

Available entities

We can see all the available entities in the endpoint with metadata.

Read Students

Read Students

By appending entity, Student into url, we can read student data

Read Data types

Read data types

We can read data types of student using the $metadata tag

Excel 2016 with OData v4

We already know office is not only for manipulating documents, We can perform many advanced queries with Excel. Excel supports to fetch data from different other sources, newer update is OData sources

Excel 2016 - ODATA v4

In excel 2016, We can connect to a OData source like this,

Data connection wizard

But we get an error!!!!!!

error from Data connection wizard - office 2016 odata v4

It clearly says Excel 2016 can be only integrated with Odata v3 or any earlier data feeds :) But for your information, with Excel 2016 as well as Excel 2013, we can integrate OData v3

Excel 2013 & OData v4 ?

With Excel 2013, ODATA v4 is not compatible. But we can use a V3 format service with Excel 2013.

error - office 2013 odata v4

Excel 2016 with OData v4 - Power Query

With ODATA v4, we can’t use ODATA source option, But we have Power Query option to analyse data.

Excel 2016 - ODATA v4 with Power Query

In Data tab, we have many options to fetch data from different other sources, We can select From OData Feed option.

PowerQuery - Odata feed

We can use Office 2016 Power Query option with OData v4.

Power Query Editor

PowerQuery editor

This is the query editor, we can select/remove columns, can remove duplicates, group by a column, create a new column based on a mathematical function and much more advanced operations.

Query editor window

In the next section, we’ll see how to read data by passing a value :)

I could create a github repo for this code sample, Please feel free to check it, https://github.com/hansamaligamage/ODATAExample

ODATA Features

ODATA

ODATA is a open data protocol to access data using REST architecture. ODATA is a Microsoft standard, but available with Android & IOS platforms as well. ODATA supports for JSON and Atom formats. With the help of ODATA , we can access data in variety of sources like relational databases, Web sites, File systems and Content Management Systems.

ODATA has more features than REST!

REST is an architectural pattern to implement a service, But with ODATA it’s going to provide more features to more sources like File systems, Content Management Systems. ODATA services supports for query options like filter, select, expand, order by and many more. As per our requirement, we can filter the result set, order as we want. And we can skip some rows, Even we can select the top row as well.

It’s 2016!!!!

Microsoft has introduced variety of features with Office 2016, If your old REST services are using ODATA protocol, We can implement a simple power BI solution just with Excel itself.

ODATA Versions so far

After ODATA V2 and ODATA V3, Now ODATA V4 has been released as a major release. If you want to build a open data service, we can use ODATA v4 with WebAPI 2.2 as a solution.