Using manually the ASP.NET MVC’s client side validation infrastructure

Using manually the ASP.NET MVC’s client side validation infrastructure

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. ASP.NET MVC client side validation is based on the jQuery validation plugin. It can be said that MVC’s client-side validation is an opinionated version of how jQuery validation should work in an ASP.NET MVC project. Despite this, the underlying implementation is fully based on jQuery’s. In this blog post I’ll show you how you can take advantage of this.

mvc

ASP.NET MVC Client Side validation requirements

First, here’s the list of things you need to do to enable client-side validation in an ASP.NET MVC project Make sure your client side code is loading both:

  • jquery.validate.js
  • jquery.validate.unobtrusive.js

Make sure your web.config has the following keys in appSettings with the follwoing values:

These settings can be overridden in a controller, make sure that is not happening. For example this would turn off client side validation if executed inside a controller’s action:

The next requirement is that you use attributes from System.ComponentModel.DataAnnotations in the Model class that is used in view where you want client-side validation enabled.

For example, if we want the Email field to be a valid email, and make the password and email fields required we would create a model like this:

Finally, we have to use the HtmlHelpers that generate the correct markup for all of this to work, and they have to be inside a form, for example

Getting away with using Client Side validation without a model

The last two requirements are actually optional. It is possible to take advantage of client side validation without having to create a model class and annotate it, which can be useful if you only use a couple of parameters (such as in the Login example).

If you inspect the markup that the helpers generate you’ll see that it’s actually pretty simple:

It turns out that to enable client side validation without using the HtmlHelpers and a model you just have to add an input with data-val="true" and then data-val- followed by validation method that you want to apply (e.g. data-val-required), the value of which will be the error message presented to the user (e.g. data-val-required="This is the error message"). This works because the MVC’s “unobtrusive validation” works by looking for inputs that are annotated with data-val attributes.

The data-valmsg-for‘s value is the name (not the id) of the input it refers to, and data-valmsg-replace="true" just means that the default message should be replaced, for example you could have a default message for the email field:

This message would then be replaced by any validation error that occurs in the email field, for example “The email is required”. If data-valmsg-replace="false" then the original message will never be replaced. The only consequence of an error is that the span’s class is changed from field-validation-valid to field-validation-error (this happens irrespectively of the value of data-valmsg-replace="false").

Some validation methods have parameters, for example RegularExpression. The way these work is very similar, they just need additional data-val- for their parameters. If you want to validate a text field using a regular expression for 5 to 8 digits, it would look like this:

If you create the markup yourself you can get away without having to create a model for your view. Using the login example from above, your controller action for handling the user logging in could simply be:

You’d have to make any server-side checks on the parameters yourself though.

Here is the list of the System.ComponentModel.DataAnnotation attributes you can use, and their data-val counterparts:

  • Compare
    • data-val-equalto="Error message"
    • data-val-equalto-other="The name of the other field"
  • CreditCard
    • data-val-creditcard="Error message"
  • EmailAddress
    • data-val-email="Error message"
  • MaxLength
    • data-val-maxlength="Error message"
    • data-val-maxlength-max="Maximum length (e.g. 5)"
  • MinLength
    • data-val-minlength="Error message"
    • data-val-minlength-min="Minimum length (e.g. 2)"
  • Range
    • data-val-range="Error message"
    • data-val-range-max="Max value"
    • data-val-range-min="Min value"
  • RegularExpression
    • data-val-regex="Error message"
    • data-val-regex-pattern="The regular expression (e.g. ^[a-z]+$)"
  • Required
    • data-val-required="Error message"
  • StringLength
    • data-val-length="Error message"
    • data-val-length-max="Maximum number of characters"

There are also a few validation methods you can use that don’t seem to have a counterpart in System.ComponentModel.DataAnnotation. In fact you get a list of all the available client side validation methods by typing (for example in chrome) dev tools console: $.validator.unobtrusive.adapters. Here’s the list of the ones that don’t have a matching attribute: date, digits, number, url, length, remote, password.

Securing your ASP.NET MVC Application

Securing your ASP.NET MVC Application

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. Securing your ASP.NET MVC application ought to be priority number a single each time you begin a brand new net application. Employing the attributes Authorize and ValidateAntiForgeryToken in every single controller and action will be the only method to stay away from any safety holes. In this post I’ll show you the best way to secure your ASP.NET application by implementing the AuthorizeAttribute and ValidateAntiForgeryTokenAttribute classes.

The basics

In the extremely least, you need to add an [Authorize] attribute to every controller or controller Action in case you would like several of the controller actions to be accessible by anonymous users. As an example, you probably want ALL users to possess access for the login and register actions of one’s web application.

By decorating the HomeController using the Authorize attribute (notice I didn’t specify any user part) the application will avert any unauthenticated user from executing any in the actions in this controller.

The following is an instance of decorating a controller action with all the Authorize attribute, you desire to complete this if you only want to restrict access to a few of the actions in a controller instead of all actions.

Safeguarding against Cross-site request forgery attack (CSRF or XSRF)

The Authorize attribute delivers protection which is sufficient in most situations. Nonetheless, there’s security hole with this and therefore it opens your web application for a cross-site request forgery attack. By way of example, right after a user logs into your website the website will concern your browser an authentication token inside a cookie. Every single subsequent request, the browser sends the cookie back for the site to let the web site realize that you are authorized to take what ever action you are taking, so far every thing is very good.

Right here would be the issue with only using the Authorize attribute, let’s say that a user is logged in to your website and then they visit a spam web site by clicking on a hyperlink that points to one more web site which causes a kind post back to your site… this can be negative, your browser will send the authentication cookie to your website generating it seem as when the request came out of your website and initiated by an authenticated user when it genuinely didn’t.

The above situation is known as cross-site request forgery and can be avoided by adding the ValidateAntiForgeryToken attribute offered inside the .NET framework, this attribute is employed to detect regardless of whether a server request has been tampered with.

The initial step would be to add the ValidateAntiForgeryToken attribute to every single Post Action as follows:

The next step is to add the HtmlHelper strategy @Html.AntiForgeryToken() inside the type within your view.

The way the ValidateAntiForgeryToken attribute operates is by checking to view that the cookie and hidden kind field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException shown beneath:

“A essential anti-forgery token was not supplied or was invalid”

By adding the ValidateAntiForgeryToken for your controller actions your internet site will likely be prepared to stop CSRF/XSRF attacks.

Implementing Forms Authentication using Active Directory (AD)

Often times you might run across a project where you need to authenticate users of your website using Active Directory credentials, the good news is that you can use the existing “Account” controller to achieve this, only a few modifications are necessary.

When you create a new MVC Web Application project and choose the Internet Application template, the Account controller is added to the project, you can use this controller with AD to authenticate your users. For the Account controller to work with AD we need to remove all Actions but the following:

  • Logon()
  • Logon(LogOnModel model, string returnUrl)
  • LogOff()

Your Account controller should look like the following after you remove the unnecessary Actions such as ChangePassword, Register, etc.

After this, go ahead and clean up the AccountModel as well so the only model class left is the LogOnModel:

Lastly, add the following to the project’s web.config file:

as

How To Using Sessions and HttpContext in ASP.NET Core and MVC Core

How To Using Sessions and HttpContext in ASP.NET Core and MVC Core

CheapASPNETHostingReview.com | Best and cheap ASP.NET core 1.0 hosting. If you’re new to ASP.NET Core or MVC Core, you’ll find that sessions don’t work the way they used to. Here’s how to get up and running the new way.

Add Session NuGet Package

Add the Microsoft.AspNetCore.Session NuGet package to your project.

VERSION WARNING: As you’ll find with most Microsoft.* packages, you should make sure the versions all match. At RTM time as of writing, this means “1.0.0”.

Update startup.cs

Now that we have the Session nuget package installed, we can add sessions to the ASP.NET Core pipeline.

Open up startup.cs and add the AddSession() and AddDistributedMemoryCache() lines to the ConfigureServices(IServiceCollection services)

Next, we’ll tell ASP.NET Core to use a Memory Cache to store the session data. Add the UseSession() call below to the Configure(IApplicationBulider app, ...)

Where’s the Session variable gone?

Relax it’s still there, just not where you think it is. You can now find the session object by using HttpContext.Session. HttpContext is just the current HttpContext exposed to you by the Controller class.

If you’re not in a controller, you can still access the HttpContext by injecting IHttpContextAccessor.

Let’s go ahead and add sessions to our Home Controller:

You’ll see the Index() and About() methods making use of the Session object. It’s pretty easy here, just use one of the Set() methods to store your data and one of the Get() methods to retrieve it.

Just for fun, let’s inject the context into a random class:

Let’s break this down.

Firstly I’m setting up a private variable to hold the HttpContextAccessor. This is the way you get the HttpContext now.

Next I’m adding a convenience variable as a shortcut directly to the session. Notice the =>? That means we’re using an expression body, aka a shortcut to writing a one liner method that returns something.

Moving to the contructor you can see that I’m injecting the IHttpContextAccessor and assigning it to my private variable. If you’re not sure about this whole dependency injection thing, don’t worry, it’s not hard to get the hang of (especially constructor injection like I’m using here) and it will improve your code by forcing you to write it in a modular way.

But wait a minute, how do I store a complex object?

How do I store a complex object?

I’ve got you covered here too. Here’s a quick JSON storage extension to let you store complex objects nice and simple

Now you can store your complex objects like so:

and retrieve them just as easily:

Use a Redis or SQL Server Cache instead

Instead of using services.AddDistributedMemoryCache() which implements the default in-memory cache, you can use either of the following.

SQL Server
Firstly, install this nuget package:

  • "Microsoft.Extensions.Caching.SqlServer": "1.0.0"

Secondly, add the appropriate code snippet below:

Redis Cache
Unfortunately, the redis package does not support netcoreapp1.0 at the moment. You can still use this if you’re using net451 or higher.

"Microsoft.Extensions.Caching.Redis": "1.0.0"

Stay up to date

Even though we’ve reached RTM, you should still keep an eye on the ASP.NET Session Repository for any changes.

Best Practices Windows Cloud Server Security

Best Practices Windows Cloud Server Security

CheapASPNETHostingReview.com | Best and cheap Windows Cloud Server in Australia. While dedicated server solutions are the right choice for certain situations, clients are finding the benefits of cloud servers or, in many cases, a hybrid hosting solution to be the perfect fit for their hosting needs. With all this cloud talk, there are several technologies supported on Windows cloud servers that you may not have realized. These options can make the difference when configuring a cloud server solution that will best optimize your site or application.

enterprise-virtual-private-cloud


Firewalls, VPN & SSL in the Cloud

The best practices of leveraging Virtual Private Networks (VPN), Secure Sockets Layers (SSL) and Firewalls to protect sensitive information on a Windows Cloud Server are recommend and also supported just as they would be with a physical dedicated server. If you’re unsure as to what any of these are and why they are necessary, the following will serve as a summary of each and their benefits.

What is VPN?

Virtual Private Networking is a secure and controlled method of connecting remote networks and users for the purpose of dealing with sensitive information. When using a VPN, all data is encrypted at the source, sent securely to the destination, then decrypted at the destination – assuring that only the previously approved source and destination people or systems can access the data. This is often a necessary element to incorporate in your hosting solution if you are an eCommerce company accessing sensitive back-end data like credit cards or orders, require PCI compliance, or simply need to securely work with remote clients or coworkers regarding sensitive information. A VPN connection allows you to guarantee identity through point-to-point connections and user authentication. While Windows cloud servers are virtual, they retain all the same VPN encrypting capabilities as a dedicated server, giving you complete control over security and privacy of your data. (For more information on Virtual Private Networking.

What is an SSL Connection?

The Secure Socket Layer protocol (SSL) ensures secure transactions between Windows cloud servers and browsers. This is particularly important anytime sensitive information must be transmitted over the open Internet. For example, any sign-up process where personal information is needed, (credit card information, personal data, etc.) would justify use of an SSL connection. You can recognize the use of an SSL connection when you see an “S” included in the URL (https://).
While the technical breakdown of an SSL can be somewhat complicated, it’s important to understand the basic concept of an SSL connection and how important it is inmaintaining security with sensitive information.

What is a Firewall?

A firewall is a security solution designed to only allow safe and trusted connections to whatever it is set to protect. It does this by identifying several pieces of information for all incoming connections, thus blocking access to any unfamiliar or unauthorized sources looking to access that data. The difference between a firewall and an SSL connection is that SSL is used to ensure your sensitive information can be securely sent from a webpage to a server, while a firewall is designed to control direct access to the cloud server itself. A firewall can be used to lock down ports and allow only certain information to be accessible, while keeping other information secure.

Firewall in a Windows Cloud Server

In order to set up a firewall in a Windows cloud server configuration, various steps must be taken to optimize the firewall for the cloud – but depending on your hosting provider, these steps will be covered for you. Once these steps are taken, it is no different than a firewall configured for a dedicated physical server.
Note: In addition to base intrusion detection and firewall protection offered at our network core, our Windows Cloud Servers come with free built-in Windows Firewall service that can be used to lock down ports and restrict access with a focus on the specific needs of your server – assuring that only the ports needed are opened and only available to the users or systems that need the sensitive access.

Cloud Server Security Best Practices

The above security steps are important in and of themselves, but they also serve as a baseline for achieving PCI Compliance, something in which we at ASPHostPortal.com are well versed. So, whether you’re looking to sure up your security as a best practice, or find yourself needing to implement the above steps in accordance with the PCI Security Standard Council, Windows cloud server hosting offers all the tools available on a dedicated server configuration, but often with several added benefits.

Cheap Drupal Hosting SEO Tips To Rank Better On Google

Cheap Drupal Hosting SEO Tips To Rank Better On Google

CheapASPNETHostingReview.com | Cheap and reliable Drupal hosting. This is a post about Drupal, SEO, and Drupal & SEO. While some of this information is specific to Drupal, other parts are just general to SEO, but what makes the general parts related to Drupal is that, in most cases, Drupal development makes it much easier to implement search engine optimization when compared to similar content management systems I have used.

1. Keyword Research is a MUST

Know what keywords you should be using throughout your copy, in your title tags, URLs, meta tags, meta description, alt tags, internal links, and headers. The best way to do that is to use Google’s Keyword Tool, now Keyword Planner. Using the keyword planner you can see how frequently terms are being search per month (globally and locally), how competitive they are for ranking, and how much they cost to advertise on. Better still, the keyword planner will give you related keywords to what you typed in. This tool is a must to start with for good Drupal SEO, really any SEO for that matter.

2. Google Analytics & Google Webmaster Tools

Get these two tools, Google Analytics & Webmaster Tools hooked up and running data on your Drupal site ASAP, and better still, get them hooked up together. If you aren’t pulling this data from your website you’re going to be lost in terms of what is currently going on, creating difficulty in making confident decisions on what to do next when it comes to SEO. There are a bunch of tools out there that offer similar insight when it comes to this information, but if you want to know what Google is seeing when it comes to your site, why not go directly to the horse’s mouth.

3. Key Drupal SEO Modules To Get Installed

Drupal has several modules that every site should install. That is, if you’re looking to take advantage of what Drupal already has to offer, and if you care to get found online ‘organically’ through someone typing words other than your company’s name.

  • Alinks: Creates automatic links allowing users to associate defined text to links.
  • Content Optimizer: Helps to ensure content conforms to Drupal SEO best practices and provides analysis pages to ensure SEO best practices are followed.
  • Custom Breadcrumbs: Allows you to set up parametrized breadcrumb trails for any node type.
  • Global Redirect: After turning on clean URLs and Pathauto, it fixes some of the more common URL problems.
  • Google Analytics: Visitor tracking.
  • HTML Purifier: Fixes substandard HTML on content generated by users.
  • Link Checker: Checks for broken links.
  • Menu Attributes: Additional attribute specification for menu items such as id, name, class, style, and rel.
  • Metatag: Enables full control of meta tags on your site, nodes, categories, views, etc.
  • Mollom: Spam protection.
  • Page Title: Allows the page title to be set.
  • Pathauto: Based on the title of the page, this module autocreates an SEO-friendly URL.
  • Path Redirect: Creates proper redirects for URLs.
  • Read More Link: Creates customized, SEO-friendly read more links.
  • SEO Checklist: Checklist that provides admin shortcuts and download links to pretty much all the modules and tasks to perform SEO on a Drupal site.
  • SEO Compliance Checker: Checks for on page SEO compliance giving the user analysis when a node is saved or previewed.
  • Scheduler: Allows scheduling for the publishing of nodes.
  • Site Map: Creates a plain text version of the sitemap.
  • Site Verification: Verification assistance of site ownership for search engines.
  • Syndication: Centralization, through a web page, all RSS feeds generated by Drupal.
  • Taxonomy Title: Title setting for taxonomy pages.
  • URL List: Lists every URL on your Drupal-based website by creating a plain text sitemap.
  • XML Sitemap: Creates search engine readable, dynamic sitemap that is Sitemaps.org compliant.

4. Backlinks, Backlinks, Backlinks

9shutterstock_125340119

Don’t let Google fool you, even with the Penguin and Panda updates, backlinks still count pretty big. What those updates are trying to do is get rid of all the big time comment spam and professional profile builders out there by penalizing sites with an overwhelming amount of those types of links.

The key to backlink building is to make it look natural, by having a good mix of links built with just plain URLs, home page URLs, keyword anchor text, long tail keyword phrases and use of “similar” keyword type phrases. Go after links from sites of all Page Rank types and make sure the links reference not only your home page but also your inner pages. Don’t sweat the no-follow links to your site, because here is the thing: they are still links and get counted, maybe not as much as a followed link, but they are still getting picked up.

Go for credible links, and look at that this way: Appnovation is a Drupal development company so we would definitely want to get a link from Drupal.org pointing back out our site because that is basically telling Google that Drupal.org (the foremost authority on Drupal) considers Appnovation a Drupal development company.

Talking about backlinks can go on and on, but the keys are:

  • continuously do it;
  • make it look natural;
  • keep it as credible is possible; and,
  • have the links touch as many different parts of your site as you can.

5. Watch Your Competitors

Unless you have monopoly, you are going to have to keep up with the competition. Keep an eye on what they are doing both on-page and off, as well as monitor what they are ranking for and where they are ranking. Competitors can give you great ideas on what you should be doing on your pages to make sure your rank is improving.

6. Continuously Update

Sites can’t just be a static page that you build and push live to just sit there. Today you have to continuously create content for it. Although not just new web page after new web page, but content of all types like case studies, product reviews, client testimonials, whitepapers, eBooks, infographics, demos, portfolios, videos, communities, blogs, social sections, and so on. Keep you site as dynamic as possible and keep giving Google a reason to come back and crawl you to see what’s going on. Refresh your website with a complete redesign from time to time so that you can add more ways for people interact with it. Basically today’s websites have to be living, breathing entities that need consistent feeding and constant attention. Drupal is an ideal content management system (CMS) for this very purpose.

7. Make It Work Together

The key to all of it is being able to make it work together: the keywords, the tracking, the modules, the backlinks, the competitive research, and the continuous updating. Leaving out any of those is going put a pretty big dent in comprehensive Drupal SEO strategy. Each item above requires the other 6 to be involved, or at least taken into account, someway, somehow.

Bonus. A Word of Caution

Word to the wise: don’t ever put all your eggs in the SEO basket. Not too many people know what makes up the Google algorithm (I am guessing you probably don’t) let alone when Matt Cutts’ team (I am also guessing you don’t know Matt Cutts or anyone on his team either) is going to make another change that could affect what your site shows up for, or where, in the rankings.