Upload file and send email with attachment in ASP.NET MVC5 using Postal

So In previous post we came to know about Postal. yes it is easy.

We can send email in ASP.NET MVC easily.

So How about sending attachment using Postal Nuget package.

So I did create a sample project for uploading file and send email with that attachment using postal.

Indeed it is very easy.

Add Postal Your tool box.

  1. Create empty ASP.net MVC5 project
  2. Add Posta Package

nuget command

Then Package references are added and New folder is created as Email under the Views folder.

email folder

3. Added controller named HomeController and added simple view to enter email and upload file.

indexview

yes it is ugly. no need to worry. wanted make this work. no fancy works here.

indexviewui

4. Add smtp configurations to web.config

webconfig

I am using gmail smtp. fill user name and password. Postman will use this configurations to send emails.

5. Add coding to send email


[HttpPost]
public ActionResult Index(string email) {
if (!string.IsNullOrEmpty(email)) {
if (Request.Files.Count > 0) {

dynamic emailToSend = new Email("EmailWithAttachement");

byte[] data = new byte[0];
data = new byte[Request.Files[0].ContentLength];

var fileName = Request.Files[0].FileName;
var extension = Path.GetExtension(Request.Files[0].FileName);
Request.Files[0].InputStream.Read(data, 0, Request.Files[0].ContentLength);

using (var stream = new MemoryStream(data, true))
{
emailToSend.Attach(new Attachment(stream, fileName + extension));
emailToSend.To = email;
emailToSend.Send();
}
}
}

return View();
}

 

codes

Read uploaded file and convert it into byte array and attach it into email.

So finally we want to add view to be used by postal to send email.

Add view name “EmailWithAttachement” under email folder under Views folder.

emailview

edit view as below. you can edit view as you wish.

emailviewcode

finally run the project and enter email address and upload a file then email will be sent to provided email with attachment

actualemail

 

yes it is very simple.

Download source code here

Enabling Cross-Origin Requests in ASP.NET Web API

Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘<domain>’ is therefore not allowed access. The response had HTTP status code 405.

capture

We want to expose our api to be called from other domain. In default browsers doesen’t allow cross domain xhr requests.

To get it fixed we want to allow CORS in our web api.

I have created video on enabling CORS in web api.

watch video

More about CORS in Web api

Reading Excel files easily in c# using Excel Data Reader

So I found a useful Package to read excel files easily. No more cumbersome codes needed.

I have written post on How to read Excel file in c# in here . But lot of codes.

So I found ExcelDataReader package in github.

Excel Data Reader

It is awesome.

Just few lines of codes to read files as below.


string filePath = "Book1.xlsx";
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

excelReader.Close();

done.

Download sample project file from github

Calling web service from sql server using sql clr

Problem :

In my previous project I was been asked call web service from sql server stored procedure.

So I get it done using SQL CLR. So using CLR we can run managed code inside sql server.

Code that runs within the CLR is referred to as managed code.

We can create stored procedures, triggers, user defined types, and user-defined aggregates in managed code.

We can achieve significant performance increases because managed code compiles to native code prior to execution.

We can use SQL CLR in in SQL Server 2005 and later.

Why Sql CLR in sql server:

In some cases some tasks are not possible by T-SQL as my requirement.

So in that point we can go with SQL CLR.

What tools I have used in this post

Visual Studio 2015

Sql Server 2014

In Action:

  1. Create SQL Server Database project in VS 2015

newproj

  1. Add SQL CLR C# Stored Procedure

add-new-item

Name stored procedure As CallWebService

3. Add C# codes to Call Web service. I am using below web service to do test

http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry


HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.webserviceX.NET//globalweather.asmx//GetCitiesByCountry?CountryName=Sri Lanka");

request.Method = "GET";

request.ContentLength = 0;

request.Credentials = CredentialCache.DefaultCredentials;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Stream receiveStream = response.GetResponseStream();

// Pipes the stream to a higher level stream reader with the required encoding format.

StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

System.IO.File.WriteAllText("d://response.txt", readStream.ReadToEnd());

response.Close();

readStream.Close();

I am simply writing response to a text file.  You can do whatever in here.

4.Enable clr and set trust worthy on database. I am using AdventureWorks database


sp_configure 'show advanced options', 1;

GO

RECONFIGURE;

GO

sp_configure 'clr enabled', 1;

GO

RECONFIGURE;

GO

alter database [AdventureDatabase] set trustworthy on;

5. Build Visual Studio Project

Then it will generate dll in bin folder

6. Register assembly in Database.

Go to AdventureWorks > Programmability > Assemblies

Right click on Assemblies and Click new Assembly

register-assembli

Set Permission to External access and browse for Our dll.  It is in bin folder of your project

Once you added we can see assembly registered in side Assemblies as below.

assembli

7. Create stored procedures to call assembly’s stored procedure

stored-procedure

Once you created a stored procedure you can see locked stored procedure.

locked-sp

8. So Now we have finished just execute the stored procedure. You can see text file is generated in drive

exec-sp

Source code

Angular js getting started – To do app

Developing applications using Javascript is always a challenge.

Javascripts use for

  • UI manipulation
  • Client server interaction
  • business processing and validation

Libraries such as Jquery is doing great job of developing javascript applications. But these libraries lack any structural guidance. We are going to have large co debase which difficult to maintain.

We know to do some data binding we have to write several lines of codes. So it is difficult to maintain.

This is where architectural patterns such as Model View Controller (MVC) and frameworks such as AngularJS come into the picture.

Building to do app with Angular JS

I am going to create to do app in angularjs using Plunker.

  1. Reference angular js

capture

      2. Create angular app in script.js 

app

So we are creating a angular module . Modules in Angularjs are containers that hold various artifacts that we create or are part of the framework.

The first parameter is name of the module and second is there to provide module dependencies.

  3. define angular js application using ng-app directive 

ngapp

The ng-app directive tells Angular to treat everything defined inside the html tag as an angular app and process it accordingly. The app value of the ng-app attribute tells angular to search for a module named app and load it. in previous step we created a angular module named app. so it is loaded now.

So now our angular module linked with html view. So now we want a controller to create link between Model and View.

   4. Create controller 

ctrl

angular.module function creates a module and returns a module object. This module object has a function controller that allows us to register a controller. The first parameter is name of the controller and second is the controller implementation.

We have pass $scope object to controller function. Who is passing this $scope object. Angular Dependency Injection framework responsible for passing this object.

What is scope object?

The scope is the binding part between the HTML and the controller. It is available with properties and methods.. It is available for both view and controller.

Now we have to registered our Controller with view. So we use ng-controller attribute

 5. Link controller to the view 

registerctrl

So Now we are going to create our model and bind it View.

So our to app’s model should contains newTodo property.

So we add it to our controller

newtodo

we add it as property of scope object. So it is available on view. So when user enter new to do it shold be bind to newTodo variable. So how it is happen. We want to bind model to the input field.

we can do it using ng-model directive.

ngmodel

ng-model directive bind the value of html controls to application data.

Add required features to model

ctrlupdated

After entering value in text box then user press add button . Then AddToList function is fired. AddToList function is link to the view using ng-click directives. So when button is clicked AddToList is called. It will push new entry to List array.

viewhtml

I have used ng-repeat directive to show list of to do item in a list.

todoview

The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object.

So we have created a part of to do app using angularjs. We want to improve it. More features should be added. I will continue it to another post.

Plunker code