European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Use C# To Send Emails with Mail Helper

clock February 27, 2016 00:28 by author Rebecca

In this post, I will create simple mail helper class for sending emails in ASP.NET MVC using C#.

IMPLEMENTATION

Step 1

Create a class name MailHelper and the add the following code:

public class MailHelper
    {
        private const int Timeout = 180000;
        private readonly string _host;
        private readonly int _port;
        private readonly string _user;
        private readonly string _pass;
        private readonly bool _ssl;

        public string Sender { get; set; }
        public string Recipient { get; set; }
        public string RecipientCC { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string AttachmentFile { get; set; }

        public MailHelper()
        {
            //MailServer - Represents the SMTP Server
            _host = ConfigurationManager.AppSettings["MailServer"];
            //Port- Represents the port number
            _port = int.Parse(ConfigurationManager.AppSettings["Port"]);
            //MailAuthUser and MailAuthPass - Used for Authentication for sending email
            _user = ConfigurationManager.AppSettings["MailAuthUser"];
            _pass = ConfigurationManager.AppSettings["MailAuthPass"];
            _ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"]);
        }

        public void Send()
        {
            try
            {

// We do not catch the error here... let it pass direct to the caller
                Attachment att = null;
                var message = new MailMessage(Sender, Recipient, Subject, Body) { IsBodyHtml = true };
                if (RecipientCC != null)
                {
                    message.Bcc.Add(RecipientCC);
                }
                var smtp = new SmtpClient(_host, _port);

                if (!String.IsNullOrEmpty(AttachmentFile))
                {
                    if (File.Exists(AttachmentFile))
                    {
                        att = new Attachment(AttachmentFile);
                        message.Attachments.Add(att);
                    }
                }

                if (_user.Length > 0 && _pass.Length > 0)
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new NetworkCredential(_user, _pass);
                    smtp.EnableSsl = _ssl;
                }

                smtp.Send(message);

                if (att != null)
                    att.Dispose();
                message.Dispose();
                smtp.Dispose();
            }

            catch (Exception ex)
            {
            }
        }
    }

Step 2

Place the following code in the app settings of your application:

appSettings>
<add key=”MailServer” value=”smtp.gmail.com”/>
<add key=”Port” value=”587″/>
<add key=”EnableSSL” value=”true”/>
<add key=”EmailFromAddress” value=”[email protected]”/>
<add key=”MailAuthUser” value=”[email protected]”/>
<add key=”MailAuthPass” value=”xxxxxxxx”/>
</appSettings>

Step 3

If you don’t have authentication for sending emails you can pass the emtpy string in MailAuthUser and MailAuthPass.

<appSettings>
<add key=”MailServer” value=”smtp.gmail.com”/>
<add key=”Port” value=”587″/>
<add key=”EnableSSL” value=”true”/>
<add key=”EmailFromAddress” value=”[email protected]”/>
<add key=”MailAuthUser” value=””/>
<add key=”MailAuthPass” value=””/>
</appSettings>

USAGE

Add the following code snippet in your controller to call Mail Helper class for sending emails:

var MailHelper = new MailHelper
   {
      Sender = sender, //email.Sender,
      Recipient = useremail,
      RecipientCC = null,
      Subject = emailSubject,
      Body = messageBody
   };
 MailHelper.Send();

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Perform CSV Files (Upload & Read) in ASP.NET MVC

clock February 20, 2016 00:39 by author Rebecca

To read CSV file doesn’t mean to use String.Split(). CSV files may contain commas, carriage returns, speechmarks…etc within strings. In this post, we will learn how to upload and read CSV File in ASP.NET MVC WITHOUT using Jet/ACE OLEDB provider. It is helpful when you have to deploy your code on shared hosting, Azure website or any server where ACE Database engine is not available. In this post, we will use a fast CSV Reader.

Step 1

Create ASP.NET MVC Empty Project

Step 2

To install CSVReader, run the following command in the Package Manager Console:

Install-Package LumenWorksCsvReader

Step 3

Add New Controller say HomeController and add following action:

public ActionResult Upload()
       {
           return View();
       }

Step 4

Add View of Upload action and use following code:

@model System.Data.DataTable
@using System.Data;
 
<h2>Upload File</h2>
 
@using (Html.BeginForm("Upload", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()   
    @Html.ValidationSummary()
    
    <div class="form-group">
        <input type="file" id="dataFile" name="upload" />
    </div>
    
    <div class="form-group">
        <input type="submit" value="Upload" class="btn btn-default" />
    </div>
    
    if (Model != null)
    {
        <table>
            <thead>
                <tr>
                    @foreach (DataColumn col in Model.Columns)
                    {        
                        <th>@col.ColumnName</th>
                    }
                </tr>
            </thead>
            <tbody>
                @foreach (DataRow row in Model.Rows)
                {       
                    <tr>
                        @foreach (DataColumn col in Model.Columns)
                        {            
                            <td>@row[col.ColumnName]</td>
                        }
                    </tr>
                }
            </tbody>
        </table>
    }
}

We will read CSV file, get data in DataTable and show DataTable in View.

Step 5

Here's how to read submitted CSV file:

[HttpPost]
[ValidateAntiForgeryToken]
 public ActionResult Upload(HttpPostedFileBase upload)
{
    if (ModelState.IsValid)
    {
 
        if (upload != null && upload.ContentLength > 0)
        {                  
 
            if (upload.FileName.EndsWith(".csv"))
            {
                Stream stream = upload.InputStream;
                DataTable csvTable = new DataTable();
                using (CsvReader csvReader =
                    new CsvReader(new StreamReader(stream), true))
                {
                    csvTable.Load(csvReader);
                }
                return View(csvTable);
            }
            else
            {
                ModelState.AddModelError("File", "This file format is not supported");
                return View();
            }
        }
        else
        {
            ModelState.AddModelError("File", "Please Upload Your file");
        }
    }
    return View();
}

It is assumed the file will have column names in first row.

Output

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Connect an MVC Project to an SQL database?

clock February 18, 2016 19:59 by author Peter

I'm simply getting to grips with MVC linq etc and came across what sounds like a standard stumbling block. All the tutorials are either Code first examples or they create the information from scratch within the App_Data directory. All well and smart for a tutorial that require to be simply moveable to the readers computer, however not very useful when putting in a full scale MVC application. My first problem was my lack of knowledge of Linq to SQL. Finally, how to add an external SQL database to your MVC project:

  • Right click on "Models" folder, choose "Add New Item"
  • Add a "Link to SQL Classes" item
  • Open your "Server Explorer" pane (if you cant see it attempt "View" on the menu bar and "Server Explorer"
  • Right click on "Data Connections" and choose "Add Connection"
  • Follow the instructions.
  • almost there....
  • Expand your newly added database to look at the tables.
  • Drag the tables you wish over to the main pane of the "Link to SQL Classes" item you added at the start.
  • Hey presto, you have a database context you'll run Linq queries against.

Please bear in mind you will need to use the "Models" namespace to reference you database context objects.
And now back to highly sophisticated programming!

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Use ASP.NET MVC To Increase Website Performance

clock February 12, 2016 23:50 by author Rebecca

In this tutorial, we will discuss about how you can increase the performance of website using ASP.NET MVC.

1. Remove Unused view engines

protected void Application_Start()
{
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new RazorViewEngine());
}

2. Deploying Production Code in Release Mode

Make sure your production application always runs in release mode in the web.config
<compilation debug=”false”></compilation>

<configuration> <system.web> <deployment retail=”true”></deployment> </system.web> </configuration>

3. Use OutputCacheAttribute When Appropriate

MVC will not do any View Look-up Caching if you are running your application in Debug Mode

[OutputCache(VaryByParam = "none", Duration = 3600)]
public ActionResult Categories()
{
    return View(new Categories());
}

4. Use HTTP Compression

Add gzip (HTTP compression) and static cache (images, css, …) in your web.config:

<system.webserver><urlcompression dodynamiccompression=”true” dostaticcompression=”true” dynamiccompressionbeforecache=”true”></urlcompression>
</system.webserver>

5. Add an Expires or a Cache-Control Header

<configuration><system.webServer>
<staticContent>
<clientCache cacheControlMode=”UseExpires”
httpExpires=”Mon, 06 May 2013 00:00:00 GMT” />
</staticContent>
</system.webServer>
</configuration>

6. Uncontrolled Actions

protected override void HandleUnknownAction(string actionName)
{
       RedirectToAction("Index").ExecuteResult(this.ControllerContext);
}

7. Other Ways

  • Avoid passing null models to views
  • Remove unused HTTP Modules
  • Put repetitive code inside your PartialViews
  • Put Stylesheets at the Top
  • Put Scripts at the Bottom
  • Make JavaScript and CSS External
  • Minify JavaScript and CSS
  • Remove Duplicate Scripts
  • No 404s
  • Avoid Empty Image src
  • Use a Content Delivery Network
  • Use either Microsoft, Google CDN for referencing the Javascript or Css libraries
  • Use GET for AJAX Requests
  • Optimize Images

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Restricting HTTP Methods in ASP.NET MVC

clock February 11, 2016 20:21 by author Peter

HTTP methods are not often thought about once writing ASP.NET webforms applications. Links are GETs, buttons are POSTs and it all happens automatically. With Asp.NET MVC, and other MVC frameworks like Rails, the http method used is more obvious and developers are begining to care about which they use.

The problem is that GET requests tell visitors to your site, together with search engines, client-side web optimizers and other automatic tools, that it's safe to make the request. Which is a problem if your checkout button causes a GET. To quote Dave Thomas, paraphrasing Tim Berners-Lee, "Use GET requests to retrieve info from the server, and use POST requests to request a change of state on the server".

To help me correctly control which HTTP methods are used to access my controller actions I created an ActionFilterAttribute. ActionFilters provide a declarative way to access the executing context immediately prior to, and immediately following, the execution of an action. they're an excellent way to introduce aspect oriented programming to an asp.net mvc application. To use my action filter you attribute a controller action like this:
AllowedHttpMethods(AllowedMethods= new HttpMethods[] {HttpMethods.POST})]
public void Save()
{ ... }

The code for the Action Filter inherits from ActionFilterAttribute and overrides the OnActionExecuting event.
public class AllowedHttpMethodsAttribute : ActionFilterAttribute
    {
        public HttpMethods[] AllowedMethods { get; set; }

        public override void OnActionExecuting(FilterExecutingContext filterContext)
        {
            int count = AllowedMethods.Count(m => m.ToString().Equals(filterContext.HttpContext.Request.HttpMethod));
            if (count == 0) throw new Exception("Invalid http method: " + filterContext.HttpContext.Request.HttpMethod);
        }
    }

    public enum HttpMethods
    {
        GET,POST
    }


By adding the AllowedHttpMethods attribute to all of my controller actions I can assure that http methods are used correctly.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Generate URLs with ASP.NET MVC

clock February 4, 2016 20:38 by author Peter

I have been operating with ASP.NET MVC for some time and yet I still had trouble making an attempt to get a URL in a view. URL generation is particularly important for ASP.NET MVC as a result of it uses a routing engine to map URLs to code. If we hard code a URL then we lose the ability to later vary our routing scheme. I have found 2 ways that currently (ASP.NET MVC preview 2) work to generate URLs in a view. the first uses the GetVirtualPath method and seems overly complicated - thus I wrapped it in a global helper:

public static string GenerateUrl(HttpContext context, RouteValueDictionary routeValues)
    {
        return RouteTable.Routes.GetVirtualPath(
            new RequestContext(new HttpContextWrapper2(context), new RouteData()),
            routeValues).ToString();
    }


But then I found that I could achieve a similar result additional simply using UrlHelper, accessible via the URL property of the view.
// link to a controller
Url.Action("Home");

// link to an action
Url.Action("Home", "Index");

// link to an action and send parameters
Url.Action("Edit", "Product", new RouteValueDictionary(new { id = p.Id }));


Or, if you want the url for a hyperlink you can get that in one step using the ActionLink method on the Html property:
Html.ActionLink<HomeController>(c => c.Index(),"Home")

So I no longer see a need for my GenerateUrl method and have removed it from my helper. All of this would be much easier if there was some documentation. Im sure there is a better way so if you can think of an improvement please leave it in the comments.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in