Rails Flash Messages in MVC4

Hey everyone,

Coming from Rails I’d grown quite fond of flash messages. Unfortunately there isn’t a built in way of doing this in MVC4. Luckily, there’s a five minute solution posted on StackOverflow: http://stackoverflow.com/a/11809178/522859

Once implemented, it works just like in Rails:

this.Flash("We need you to login before you can edit anything.", FlashEnum.Warning);

Definitely worth checking out if you’ve got time, even more so if you’ve come over from Rails!

Sending Emails – MVC4 on GoDaddy

Hey everyone,

Just a really basic model that can be used to send emails on GoDaddy in MVC4.

The model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.ComponentModel.DataAnnotations;

namespace LL.Models
{
    public class Email
    {
        [Key]
        public int EmailId { get; set; }

        public string From { get; set; }
        public string To { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public DateTime Sent { get; set; }
        public string Status { get; set; }
        public string Log { get; set; }
        
        
        public void SendEmail()
        {
            MailMessage mail = new MailMessage();
            mail.To.Add(this.To);
            mail.From = new MailAddress(this.From);
            mail.Subject = this.Subject;
            mail.Body = Body;
            mail.IsBodyHtml = true;
            mail.Priority = MailPriority.Normal;
            
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "relay-hosting.secureserver.net";
            smtp.UseDefaultCredentials = true;
            smtp.Port = 25;
            smtp.EnableSsl = false;  

            try
            {
                smtp.Send(mail);
                this.Status = Fields.Status.Success;
            }
            catch(Exception e)
            {
                this.Log = e.Message;
            }

            this.Sent = DateTime.Now;
        }

        [NotMapped]
        public class Fields
        {
            public class From
            {
                public const String NoReply = "noreply@yoursite.com.au";
                public const String Support = "support@yoursite.com.au";
            }

            public class Status
            {
                public const String Success = "Success";
                public const String Error = "Error";
            }
        }

    }
}

Using it in a controller:

using LearnerLessons.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LL.Controllers
{
    public class TestController : Controller
    {
        private LLDBContext db = new LLDBContext();
        
        public String TestEmail(String content)
        {
            Email email = new Email() { To = "lls@live.com.au", From = Email.Fields.From.NoReply, Body = content, Subject = "Test" };
            email.SendEmail();

            db.Emails.Add(email);
            db.SaveChanges();

            return email.ToString();
        }
    }
}

Update:
For a quick tutorial on how to use Razor views as email templates, check out the following post: http://www.whatibroke.com/?p=983

Unable to add ‘Scripts/services/OrderService.js’ to the Web site. An unknown WinINet error has occurred (code 12113)

Hey everyone,

I ran into the following error while trying to publish via FTP to GoDaddy using Visual Studio 2013:

Unable to add ‘Scripts/services/OrderService.js’ to the Web site. An unknown WinINet error has occurred (code 12113)

While I wasn’t able to work out an exact cause it seems to have been triggered by my alternative Azure/TFS publishing profile. While attempting to publish to GoDaddy the Microsft login popped up. I closed it thinking that it shouldn’t be required. Logging back in seems to have resolved the issue.

The configuration section ‘customErrors’ cannot be read because it is missing a section declaration – Azure

Hey everyone,

The configuration section ‘customErrors’ cannot be read because it is missing a section declaration

I started receiving this error after I added the following elements to my Web.config file:

  
    
      
        
      
    
  

The problem turned out to be that the custom errors entry actually belongs under system.web. All you actually need to add it the <customErrors mode=”Off”/> part – just make sure it’s under system.web.



    
    

    
    
    
      
    
    
      
        
        
        
        
        
        
        
      
      
  

EF Generated Migrations Not Including New Model – Empty Up/Down

Hey everyone,

A quick issue I ran into today, my generated migrations weren’t detecting any of the models I’d added – only changes to existing models. Unfortunately the solution was so obvious that it didn’t even come up on Google.

I had forgotten to add the table to the DBContext file… Once this was done it all worked fine.

Configuring Custom Settings – PayPal C# SDK

Hey everyone,

I’ve been mucking around with the C# SDK for PayPal Adaptive Payments. Unfortunately the docs aren’t too great and the samples are a little confusing until you get your head around them.

One of the main issues I’ve had is working out how to configure payment request settings i.e. reverseAllparallelPaymentsOnError.

To do this, simple utilise the PayRequest class:

PayRequest requestPay = new PayRequest(envelopeRequest, "PAY", "http://localhost:53034/orders/cancel", "AUD", receiverList, "http://localhost:53034/orders/return");
requestPay.reverseAllParallelPaymentsOnError = true;

A project with an output type of class library cannot be started directly – MVC Project with Class Library

Hey everyone,

Just another quick post for fixing the following error in a multi-project solution:

A project with an output type of class library cannot be started directly

Simply right click on the project that you want to start and select “Set as StartUp Project”.

Source: http://stackoverflow.com/a/10004706/522859

There is already an open DataReader associated with this Command which must be closed first. – ASP.NET MVC

Hey everyone,

I ran into the following error this morning:

There is already an open DataReader associated with this Command which must be closed first.

It turns out there are a few causes for this. My issue was that I was attempting to open a result set while already iterating over another one.


 //Retrieve list of cart products and create list of suborders
 var cartProducts = db.CartProducts.Where(cartProduct => cartProduct.CartId == userOrder.CartId);

//Loop through each cart product
foreach(var cartProduct in cartProducts)
{
     //Retrieve suborder
     SubOrder subOrder = subOrders.Find(x => x.BusinessId == cartProduct.Product.BusinessId);

The solution to this was pretty easy thankfully. Simply add “ToList()” to the end of the initial request:


 //Retrieve list of cart products and create list of suborders
 var cartProducts = db.CartProducts.Where(cartProduct => cartProduct.CartId == userOrder.CartId).ToList();

An alternative solution is to modify your connection string in order to allow multiple result multiple result sets. Simply add the following to provider part:

MultipleActiveResultSets=true

Checkout these StackOverflow posts for more info:
http://stackoverflow.com/a/10498776/522859
http://stackoverflow.com/a/6064422/522859

Movies.mdf not in App_data Folder – MVC4 Tutorial

Hey everyone,

I’ve decided to take a look MVC4 (C#) and have just started the Movies tutorial. Unfortunately I ran into a bit of trouble with the database setup, for some reason mine wasn’t appearing in the app_data folder.

Apparently there are a few things you can try here:

Click Show All Files
This one is pretty simple, just click Show All Files
– Project > Show All Files

Refresh
Hit the refresh button
– Project > Refresh

Ensure that you’ve created a movie
You’ll need to make sure you’ve created a movie first. Apparently the database is not created until after a new row is inserted.

Final Solution, also the one that worked for me
The database wasn’t actually created under app_data, instead it was placed under: C:Program FilesMicrosoft SQL ServerMSSQL10_50.SQLEXPRESSMSSQLDATA

This StackOverflow post explains why: asp-net-retrieving-data-from-nowhere