Request for ConfigurationPermission failed while attempting to access configuration section ‘paypal’ – PayPal & GoDaddy

Hey everyone,

I ran into the following error today while working with PayPal on a GoDaddy hosted server:

Request for ConfigurationPermission failed while attempting to access configuration section ‘paypal’. To allow all callers to access the data for this section, set section attribute ‘requirePermission’ equal ‘false’ in the configuration file where this section is declared.

To fix it, all you need to do is add the requirePermission attribute to the section declaration. Note that this is not where it says paypal but under the configsections heading.


    
    

Rendering a View to a String – Email Templates in MVC4

Hey everyone,

This is just a short post showing how to render views as strings. I’ve used this as a quick way to generate email templates. The logic to render a view as a string is as follows:

public static string RenderRazorViewToString(Controller controller, string viewName, string content)
        {
            controller.ViewBag.Content = content;

            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);

                return sw.GetStringBuilder().ToString();
            }
        }

The Email Template: Views/Emails/DefaultTemplate

@{
    Layout = null;
}



    

    Easy Carts





    
    
@ViewBag.Content

In your controller:

public String TestEmail(String content)
        {
            Email email = new Email() {
                To = "lls@live.com.au",
                From = Email.Fields.From.NoReply,
                Body = content,
                Subject = "Test",
                TemplateName = @"~ViewsEmailsDefaultTemplate.cshtml",
                UseTemplate = true
            };
      
            email.SendEmail(this);
            
            db.Emails.Add(email);
            db.SaveChanges();

            return email.Body.ToString();
        }

If you looking to implement this with your emails, note that it builds on top of the email class we created back in this post: http://www.whatibroke.com/?p=963

If you’re just going to be using it directly within the controller, using the original code from over StackOverflow will probably be your best bet: http://stackoverflow.com/a/2759898/522859

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.

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

You must call the “WebSecurity.InitializeDatabaseConnection” method before you call any other method of the “WebSecurity” class. This call should be placed in an _AppStart.cshtml file in the root of your site. – MVC4

Hey everyone,

Just another small issue I ran into while attempting to retrieve a user’s ID:

You must call the “WebSecurity.InitializeDatabaseConnection” method before you call any other method of the “WebSecurity” class. This call should be placed in an _AppStart.cshtml file in the root of your site.

Thankfully the first Google result was pretty helpful: http://stackoverflow.com/a/15864133/522859

All you need to do is remove [InitializeSimpleMembership] from the top of the AccountController and then add the following line to App_Start/AuthConfig.cs

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);