a developer's notes – a semi-technical web development BLOG

May 15, 2015

Have Visual Studio build your MVC Views to check for errors.

Filed under: ASP.NET MVC — Duy Nguyen @ 5:41 pm
Tags: , , , ,

Step 1

Unload Project – Right click on project in solution explorer, select Unload Project.
Step 2

Edit Project – Right click and select ‘Edit Project and project XML will load in the editor window.
Step 3

Find false in Project XML file and change this to true.
Step 4

Save the Project XML file.
Step 5

Reload Project – Right click on the project and select ‘Reload Project’.

Now when Project compiles, views will also be compiled.

Advertisements

February 13, 2015

The request was aborted: Could not create SSL/TLS secure channel

Filed under: ASP.NET,C# — Duy Nguyen @ 10:14 am
Tags: , , , , , ,

We had some trouble with posting data with a System.Net.WebClient request. We notice that it was sporadic and couldn’t figure it out. What we found out was that some calls had SecurityProtocolType.Ssl3 and other calls didn’t specify SecurityProtocolType.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

SecurityProtocolType is a static class, and what ended up happening was when one call changed the SSL type, it would affect other areas of the application. We had to explicitly set the protocol type in each request.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // or Ssl3

September 9, 2014

MVC PartialView() VS View()

Filed under: ASP.NET MVC — Duy Nguyen @ 10:36 am
Tags: , , , , ,

Use PartialViews when you want to return a view that does that need the layout.

return PartialView()

Use Views when you need to return a view that supports the layout file.

return View()

A good blog post about it can be found here.
http://completedevelopment.blogspot.com/2014/01/is-there-really-no-difference-between.html

August 28, 2014

Custom Error Pages in MVC 4

Filed under: Uncategorized — Duy Nguyen @ 11:52 am
Tags: , , , , , ,

Default solution: Use MVC HandleErrorAttribute

 

In MVC, by default, you will have in your Global.ascx, under Application_Start()

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

And in RegisterGlobalFilters, you will have…

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{
      filters.Add(new HandleErrorAttribute()); 
}

In your web.config, if you turn on custom errors like this…

<system.web>
    <!--<customErrors mode="On"></customErrors>-->
    <customErrors mode="On" defaultRedirect="myCustompage.html?"></customErrors>
</system.web>

customErrors mode=”On” = will turn on the default ~/Views/Shared/Error.cshtml view. (If you’re using IE, be sure to uncheck “Friendly Http Errors.” It works good but if you navigate to http://localhost/404, you will get the default yellow error screen unless you specify defaultRedirect=”myCustompage.htm”. Only then, will the application handle an internal application AND 404s, 500s, etc.

 Note: I’ve read lots of issues trying to preserve the error status code or the original stack trace

 

Alternative solution: Use Application_Error

 

You can also go the Application_Error route but will not have a backup error page if there is an error rendering the error page.

See this great blog post.
http://thirteendaysaweek.com/2012/09/25/custom-error-page-with-asp-net-mvc-4/

 

Some good other reads:

http://www.devcurry.com/2012/06/aspnet-mvc-handling-exceptions-and-404.html

http://colinmackay.co.uk/2011/05/02/custom-error-pages-and-error-handling-in-asp-net-mvc-3-2/

August 21, 2014

“The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”

I keep on getting this error in Visual Studio when trying to connect to a new Secured SSL site.

“The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”

After I installed the certificate, I was able to continue working.

Note: Also, check if Fiddler is running. It may cause issues on SSL connections.

August 5, 2014

How to Redirect user or execute Controller Action in a Custom MVC Filter

Filed under: ASP.NET MVC,C# — Duy Nguyen @ 12:41 pm
Tags: , , , , ,

MVC Filter

    public class MyFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // The controller will be the controller you add the filter to. Or some base controller
            var controller = filterContext.Controller as YourController;

            // Execute controller action from filter. 
            controller.SomeControllerMethod();

            // Redirect to controller action
            filterContext.Result = new RedirectToRouteResult( new System.Web.Routing.RouteValueDictionary
            {
                {"controller", "mycontroller"},    
                {"action", "myaction"},
                {"querystring", "?hello=true"}
            });

            // Redirect to external url
            filterContext.Result = new RedirectResult(url);
        }
    }

March 21, 2014

Using jquery.validate.unobtrusive with jquery.maskedinput

Use a regular expression validator with your view model property. This regex will match “(999) 999-9999” and anything after. The input will be restricted with jquery.maskedinput to only accept valid numbers. Whether the user enters an extension or not, the regex will still get validated. We only need to valid the minimum required phone number.

Using the Data Annotation on your view model will allow the client side unobtrusive validation to work when the user enters in a phone number with the optional extension.

View Model property

[Required]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^([(][0-9]{3}[)][ ][0-9]{3}[-][0-9]{4})(.*)$", ErrorMessage = "Phone number busted.")]
[DisplayName("Contact Phone Number")]
public string ContactPhoneNumber { get; set; }

In your view

<div>
	@Html.EditorFor(x => x.ContactPhoneNumber)
	@Html.ValidationMessageFor(x => x.ContactPhoneNumber)
</div>

Script:

if ($("input[type=tel").length > 0) {
	$("input[type=tel").mask("(999) 999-9999? ext.9999", { placeholder: " " });

	// @Html.EditorFor is used to render any inputs that need the html 5 type attributes.
	// But @Html.EditorFor, won't allow you to add a css class, so we do it here.
	$('input[type=text],input[type=tel],input[type=datetime],input[type=date],input[type=number],input[type=password],textarea,input[type=email],input[type=url],input[type=zip]').each(function (idx, item) {
		if (!$(item).hasClass('form-control')) //class only for Bootstrap styling
			$(item).addClass('form-control');
	});

}

March 8, 2014

Jquery Validation Unobtrusive with ASP.NET MVC

Filed under: Javascript / JQuery — Duy Nguyen @ 2:46 pm
Tags: , , , , ,

Things to remember:

1. Input controls must be wrapped within a form
2. For validation messages to appear, you must have a validation message property for each input.

@Html.TextBoxFor(x => x.MyTextBox)
@Html.ValidationMessageFor(x => x.YourProperty)

3. If you want the validation message to appear immediately upon page load, you have to run this jquery method:

$('form').valid();

4. You can customize your validation message style with these css classes that you can override:

.field-validation-error span{
     color: red;
}

//Adds an asterisk before the message
.field-validation-error span:before{
     content: "*";
}

input.input-validation-error{
     border: 1px solid red;
}

Checkbox returning “true,false” from FormCollection.

Filed under: ASP.NET MVC — Duy Nguyen @ 10:46 am
Tags: , , , , , , , , , ,

If you try Request.Form[“checkbox0”], you’ll get the value “true,false” .

Just check this:

form[key].Contains("true"); //some said chrome returns "on"

Or

You could simplify your code doing this:

var strArray = collection["YourCheckboxName"];
char[] delimiterChars = {‘,’};
string[] checkedvalue = strArray.Split(delimiterChars);
var returnValue = checkedValue.Length > 1;

If the checkbox is checked, then the array will contain 2 values, if not, only one.

February 26, 2014

Getting started with MvcSiteMapProvider with ASP.NET MVC

Filed under: ASP.NET MVC — Duy Nguyen @ 12:54 pm
Tags: , , , , ,

Here is a great site to get started with MvcSiteMapProvider. MvcSiteMapProvider provides a simple and easy way to add breadcrumb support to your MVC site.
http://maartenba.github.io/MvcSiteMapProvider/getting-started.html

Some tutorial links:
http://edspencer.me.uk/2011/02/10/mvc-sitemap-provider-tutorial/
http://edspencer.me.uk/2011/09/20/mvc-sitemap-provider-tutorial-2-breadcrumbs/

Note: There is a NuGet package for

    MvcSiteMapProvider MVC 4
    MvcSiteMapProvider MVC 4 Core (core library if you need to reference the library from a non MVC project such as a class library.)
    MvcSiteMapProvider MVC 5
    MvcSiteMapProvider MVC 5 Core (core library if you need to reference the library from a non MVC project such as a class library.)

Note:
If you get an error “does not contain a definition for ‘MvcSiteMap'”in the Razor view with this line…

@Html.MvcSiteMap().SiteMapPath()

Add in this using statement:

@using MvcSiteMapProvider.Web.Html;
Next Page »

Blog at WordPress.com.