Search Results for 'csharp'

Http 500 error when deploying .NET Framework 2.0 application on Windows Server 2012 and IIS 8.5

If you're getting a stock 500 error when attempting to run a legacy .NET application on a Windows Server 2012 instance on IIS 8.5, make sure your application pool ID is set up properly.

On IIS 8.5, the Application Pool Id is normally set to ApplicationPoolIdentity instead of NetworkService - here is how to change it:

Also, make sure that your Application Pool is referencing the .NET 2 framework and not the .NET 4 framework.

Wednesday, February 1, 2017 at 12:13 PM
into csharp code gotcha iis server

Why is System.Threading.Tasks.Task`1 [System.Threading.Tasks.VoidTaskResult]; appearing in my ASP.NET Core Razor Views?

Pretty simple really - you're not calling the correct method to render your partial views.

Instead of:

@Html.RenderPartialAsync("MyPartial", Model);

You need to use:

@await Html.PartialAsync("MyPartial", Model);

Simples :)

Sunday, January 8, 2017 at 11:48 AM
into csharp code gotcha

SelectListItems not appearing in the Edit view when Scaffolding Controllers and Views with MVC Core in Visual Studio 2015

When scaffolding Controllers and Views (for say, a simple CMS Admin functionality for a given Object), you may find that your Select dropdowns are not populated with any SelectListItems (in the form of <option> tags).

This is because there is a bug in the Visual Studio 2015 scaffolder which, while correctly implemented in the Create view, is not in the Edit view.

You will end up with:

<select asp-for="PropertyId" asp-items="ViewBag.MyItems" />

But what you need is:

<select asp-for="PropertyId" asp-items="ViewBag.MyItems"></select>

Easy to miss.

Saturday, January 7, 2017 at 3:08 PM
into csharp code gotcha

Implementing a PayPal Payment Button with ASP.NET WebForms

One of the biggest problems with ASP.NET WebForms development is the fact that every single page is wrapped in a form tag for the postback functionality, and you can't nest forms within other forms.

This causes issues when integrating features like PayPal buttons which are normally placed on the page as a simple form template, with the parameters specified as hidden input fields.

I recently worked on a project for a colleague who's client needed a nice form to be submitted to PayPal so that a gift certificate could be dispatched, and was tasked with making this work in ASP.NET WebForms.

Because I couldn't place another form on the page (such as the ones that they recommend on the PayPal developer website) I had to construct a URL based on the WebForms form, and then redirect to the PayPal server once the postback has been initialised.

Here's the code for a hosted button

protected void SendButton_Click(object sender, EventArgs e)
    if (Page.IsValid)
        StringBuilder ppHref = new StringBuilder();

        ppHref.Append("&hosted_button_id=[HOSTED BUTTON ID]);
        ppHref.Append("&on0=Voucher Amount");
        ppHref.Append("&os0=[PRE-DEFINED OPTION]");
        ppHref.Append("&on1=Name to send voucher");
        ppHref.Append("&os1=[RECIPIENT NAME]");
        ppHref.Append("&on2=Email to send voucher");
        ppHref.Append("&os2=[RECIPIENT EMAIL]");
        ppHref.Append("&on3=Personal Message");
        ppHref.Append("&os3=[YOUR MESSAGE HERE]");

        Response.Redirect(ppHref.ToString(), true); 

Worked a treat :)

Tuesday, December 15, 2015 at 7:33 PM
into paypal csharp code webforms

Let's Build - ASP.NET MVC 5 TodoList with Entity Framework and Identity

A simple ASP.NET MVC 5 application development tutorial using Entity Framework, Identity and SQL Server

How to force lowercase URLs in ASP.NET 5

One of the most annoying things about ASP.NET development is that the Routing components default to being in CamelCase so you end up with URLs like /About/Index instead of /about/index.

In terms of SEO, a URL is classed as distinct based on its case, so the first and second URL are treated as two pages even though they share the same content - this can have a detrimental effect on your page ranking in Google because it classes one of the URLs as duplicate content.

Besides, it's always nice to have consistency in a web app and since the rest of the world seems to default to lowercase (and it looks better) t's a good idea to make it the default setting for your application.

You can of course use redirects in IIS to automatically do this, but that usually involves a 301 redirect which can be fairly expensive if you have a high-traffic website.

Here's a simple solution that works for all generated URLs in ASP.NET Routing, for instance those generated using Tag Helpers, i.e.:

@Html.ActionLink("Home", "Index", "Click Me")

will output:

<a href="/home/index">Click Me</a>


Add the following to startup.cs in the ConfigureServices() method:

    services.ConfigureRouting(routeOptions =>
        routeOptions.LowercaseUrls = true;


Add the following to your RegisterRoutes() method in your RouteConfig Class

routes.LowercaseUrls = true;

I hope you find this useful!

Wednesday, November 18, 2015 at 2:23 AM
into csharp code seo

How to use Class Interfaces in C#

In this C# tutorial I attempt to explain the concept of Class Interfaces and Inheritance.

C# Class for Generating QR Codes using the Google Charts API

In this tutorial I will share a class I have produced which wraps around the Google Charts API to generate a QR code in C#

How to use Constructors and Deconstructors in C# Classes

Learn how to create Constructors for objects in C# using different parameter types, and how to perform actions when the objects are disposed of.

Unable to add 'Global.asax' to the Web site. An unknown WinINet error has occurred (code 12113).

When publishing - especially via FTP (people still use that?) - using Visual Studio, you may come across the error:

Connecting to Unable to add 'Global.asax' to the Web site. An unknown WinINet error has occurred (code 12113).

To solve it, you must simply add Visual Studio to your firewall exclusion list - the error is a result of the firewall blocking Visual Studio from accessing your FTP server.


Tuesday, June 9, 2015 at 8:43 AM
into csharp code

How to validate an e-mail address using C# and the MailObject Class

Find out how to validate an e-mail address using C# and the MailObject Class

How to get your public IP address using a web service in C#

How to get your public IP address from a web service into a C# Console Application

TimeSpanExtensions .ToFriendlyString()

This post details a nice little snippet I found on StackOverflow a while back called ToFriendlyString() which attaches to a TimeStamp object and outputs the interval in a nice friendly string format which is customisable, depending on how deep you want to go.

The Code


To use the code simply attach it to a TimeStamp object as follows:

DateTime now = DateTime.Now;
DateTime then = DateTime.Now.AddHours(24);
TimeSpan difference = then.Subtract(now);

Response.Write(difference.ToFriendlyString(1)); // will output "24 hours"
Response.Write(difference.ToFriendlyString(2)); // will output "24 hours, 0 minutes"
Response.Write(difference.ToFriendlyString(3)); // will output "24 hours, 0 minutes, 0 seconds";


Sunday, December 7, 2014 at 4:53 PM
into csharp code

Including a Day Suffix when formatting a Date in C#

One formatting option for the DateTime object in C# that is missing is the ability to display the correct suffix for a given date, as in 4th January - Usually the best you can hope for is something like 4 January which looks crap.

Here's a quick extension method I've written which will automatically calculate it for you and allow you to format the date as normal.

The Code


Call the code like this:

DateTime myDate = new DateTime(2000,1,1,0,0,0);
Debug.Print(myDate.ToStringWithSuffix("dd[$suffix] mmm yyyy"));

Job done :)




Saturday, July 5, 2014 at 11:17 PM
into csharp code

Custom Authentication Attributes in ASP.NET MVC

Here's a very simple attribute I set up to require custom authentication on a controller action. You can use attributes like this to execute code before a controller action is run, such as in this case to perform authentication to check if the user has access to this method (if you're using a custom authentication scheme).

The Code

Set up another class module in your project called RequiresAuthenticationAttribute.cs

This will give you the attribute:


That you can use to decorate your methods, i.e.

public ActionResult MySecureDashboard() {
    return View();

That's it!
Hope this helps

Wednesday, May 14, 2014 at 1:12 AM
into csharp code

301 Rewrite Rules can break MVC forms

If you use a 301 rewrite rule in IIS to ensure all of your URLs are lowercase (perhaps for SEO purposes), beware that you may end up with broken forms in your application.

Sometimes when I'm building an app in .NET MVC, I end up accidentally using CamelCase in my URLs (because I'm a very bad programmer). I might end up with a form declaration which looks like this:


This is because the Controllers themselves in the MVC project conform to the CamelCase pattern, i.e. ProcessingController ... 

If you're using IIS Express or similar when developing locally, you probably won't notice - it's only when you deploy to the Live environment that the poo will start to fly, because that is where the ReWrite rules exist.

The reason there is a problem is because the rewrite rule returns a GET request each time it's called. You may be calling /Processing/MyAction as a POST, but when it gets rewritten by the server, the form will actually attempt to post to /processing/myaction as a GET request. And your app will break.

The solution?

Ensure all of the request URLs in your application are entirely lowercase - in HTML, Javascript. CSS. This will stop the Rewrite Rule from firing, and your POST request will survive.

Monday, May 12, 2014 at 3:19 PM
into code csharp gotcha

PottyMouth - A Simple C# Swear Word Filter

I recently had a requirement on a client project that we should attempt to filter out any bad words or phrases from the public facing pages.  It had to be case insensitive and, as you've just read, able to filter out phrases instead of just individual words.

Here's a simple C# extension method to help you filter out bad words, then call the method on whatever text you'd like to clean up, like so:


Here's the code. It should simply become a new Extension method in the same vein as ".ToString()" is on any string object.

It works quite well, but I plan to add to it in the future to allow a whitelist of phrases which may or may not contain any of the objectional words or phrases. It would probably also be beneficial to have the list of words and phrases populated from a database or configuration file so that you can add new words without requiring a whole new application build to be compiled.

I hope this helps :)

You can fork this code on GitHub here:

Monday, October 14, 2013 at 12:34 AM
into code csharp

Incorporating common ViewData into multiple Controllers in ASPNET MVC without duplication

In this short tutorial I will show you how to make common ViewData information available to your Views in ASP.NET MVC, without having to duplicate ViewData[] variables in each seperate controller

During my learning phase of ASP.NET MVC, one of my bugbears was that when I wanted to display information from my database on multiple Views, I had to load that data in during the running of each Controller Action, and essentially duplicating code across multiple Controller Actions.

For instance, if I wanted a list of categories for my products on the Master Page, in each controller I might have something like:

ViewData["Categories"] = (from c in db.Categories 
    where c.isEnabled = true 
    orderby c.Title descending 
    select c);

If you imagine that code repeated throughout the perhaps 20 or 30 Controller Actions within the application, you can see the kind of problems you'd have maintaining it - it's a violation of the DRY (Don't Repeat Yourself) principle for starters.

The solution

Essentially the solution is very simple and involves creating a new abstract class of Controller called "GlobalController" (or XController, or whateverController you like) and placing the code in there instead of your actual controller.

When you create a controller normally, this is the code you use:
public class HomeController : Controller

The Code

Notice the "abstract" keyword in there, that's the only difference. The Viewdata is contained within the class Constructor - place your ViewData code in there with any values you need throughout the application.
Now, in your usual Controllers, you need to make them to inherit this GlobalController abstract class instead of the normal Controller class, so instead of using:

public class HomeController : Controller

You need to use:

public class HomeController : GlobalController

Now that you've done that, all of the ViewData set in GlobalController constructor will be available to your views.


Sunday, February 28, 2010 at 9:49 PM
into csharp code