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

Advertisements

Remote modal validation attribute in ASP.NET MVC

We can use validation attribute to validate forms. Using Jquery validation plugin we can do client side validation with the help of modal validation attribute in mvc.

I have a post on client side validation.

Client Side Form validation in ASP.NET MVC

So some times we need to connect with server to validate properties. So now it is painless. We have Remote  attribute to validate such properties behind the seen.

Let’s suppose we need to validate user name property. User name should be validated with server. It can not be duplicated. So we can Use Remote validation attribute.

To validate want to connect to the server. So we can provide controller action to Remote attribute to call action and validate property behind the seen.

We can decorate property as below


[Remote("CheckUserName","Home", ErrorMessage ="User name already exists" ) ]
public string UserName { get; set; }

Modal class

usermodal

In action we should return true or false. if false returned from action error message will be shown.

Action


public JsonResult CheckUserName(string username)
{
//logic for check user name with database

return Json(false, JsonRequestBehavior.AllowGet);
}

action

My sample view contains form for enter user data


@model RemoteAttributeTestMVC.Models.User
@{
ViewBag.Title = "Home Page";
}
<div class="row" style="margin-top:10px;">
@using (Html.BeginForm("CreateUser", "Home"))
{
<div class="form-group order-form-group">
@Html.LabelFor(m => m.UserName)
@Html.EditorFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
}
</div>

This will render following form

form

To allow client side validation we have to add jquery validation plugin . I have added reference in _Layout.cshtml  as below

jval

Then run the project and when we enter values in user name text box and press tab it sends a request to CheckUserName action with parameter of user name behind the seen.

if action return false validation message will be shown in the form.

error

Download source code

Custom session store in ASP.NET MVC with Dependency Injection

In this post I will explain creating custom session helper with Unity DI.

Step 1

Create empty MVC project

Step 2

Add new folder called Utility and Add a interface with name of ISession. In a real project we can separate this logic into another project.

ISession interface


 T Get<T>(string key);
 void Set<T>(string key, T entry);

Step 3

Add a class called CustomSessionStore and implement ISession interface.

Add following logic to class.


public T Get<T>(string key)
 {
 HttpContext currentContext = GetSessionContext();

return (T)currentContext.Session[key];
 }

public void Set<T>(string key, T entry)
 {
 HttpContext currentContext = GetSessionContext();
 currentContext.Session[key] = entry;
 }
 private static HttpContext GetSessionContext()
 {
 HttpContext currentContext = HttpContext.Current;

if (currentContext == null)
 {
 throw new InvalidOperationException();
 }
 return currentContext;
 }

we have to add System.Web reference in top of page

using System.Web;

Step 4

Add Unity.MVC to project via nuget package manager

unity

Then we can see Two new classes inside App_Start folder

unityclasses

In UnityConfig.cs we can register dependecy as below.

registerTypes

Step 5

The add a controller called HomeController and implement as below

 

homecontroller

So as above we can easily set value to session using Set method. We can store any type of values since it is generic. Only thing we have to provide is type when saving and retrieving values as shown as above.

Source code

Could not load file or assembly ‘Newtonsoft.Json, Version=6.0.0.0, or one of its dependencies. The system cannot find the file specified.

Could not load file or assembly ‘Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed’ or one of its dependencies. The system cannot find the file specified.

I got this error when I added to WEB API to ASP.NET MVC project.

So This is how I get it solved

Run this command in package manager console

Update-Package –reinstall Newtonsoft.Json

 

Client Side Form validation in ASP.NET MVC

Client side form validation increases User friendliness. User doesn’t want to wait for page refresh and see form validation errors.

In ASP.NET MVC we can validate using Data Annotation. So we can use these validation to client side validation. No more huge validation codes.

We can use Jquery validation plugin comes with ASP.NET MVC. This bundle is not referenced in _layout.cshtml by default. We have to add it manually.

Watch youtube video 

Download source code

 

ASP.NET MVC Multilingual web site

In this article I am going to explain how to handle multiple language in your ASP.NET MVC web site.

This a very basic step.

Step 1

Create ASP.NET MVC web application

Step 2

Add new controller called BaseController. (any name as you wish)

override BeginExecuteCore() method.


 protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
 {
 string language = "en";
 HttpCookie cultureCookie = Request.Cookies["_culture"];
 if (cultureCookie != null)
 language = cultureCookie.Value;

 Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(language);

 return base.BeginExecuteCore(callback, state);
 }

Step 3

Inherit Home Controller from BaseController


public class HomeController : BaseController

step 4

Add action to change language.

To store the culture I have used cookies. It is a simple way.


 public ActionResult ChangeLanguage(string lang) {
 HttpCookie cookie = Request.Cookies["_culture"];
 if (cookie != null)
 cookie.Value = lang; 
 else
 {

 cookie = new HttpCookie("_culture");
 cookie.Value = lang;
 cookie.Expires = DateTime.Now.AddYears(1);
 }
 Response.Cookies.Add(cookie);

 return RedirectToAction("Index");
 }

step 5 

Add resource files.

Different languages are stored in resource files.

For this demo I have used English, Dutch and french languages.

I have added three resource files naming as follow

Resource.resx -> default resource file for English language

Resource.fr.resx -> French language

Resource.nl.resx -> Dutch

Add each language words for the English word “Wel Come”

resource

resource.fr

resource.nl

add words as above and build the project.

step 6

add view to change language. Wellcome text will be changes according to language selections.

It is used in view as @Resources.Resource.wellcome .

Behind the seen it is checked current culture and set appropriate word using resource files.

view

step 7 

Done. Run the project and click links to change language

Capture1

Capture2

Capture3