jQuery Tooltip Validation Using Twitter Bootstrap

jQuery Tooltip Validation Using Twitter Bootstrap

CheapASPNETHostingReview.com | Generally, we use a jQuery unobtrusive validation plugin in ASP.NET MVC Applications.We are going to discuss the following topics in this article:

  1. Disadvantages of jQuery unobtrusive validation in MVC.
  2. jQuery tooltip validation

There are some disadvantages of using this plugin. When using the jQuery unobtrusive validation plugin, it creates a span tag to display error messages. If you have, for example, a horizontal form on top of the other controls, then this behavior might not be working for you, since they will break the page layout. It was the case for me and as such, I decided to change the default behavior of the jQuery unobtrusive validation library and instead of using a span to show the error message, I decided to use a tooltip. I am going to show you how I achieved this, using a tooltip with the help of a bootstrap.

Before going to the tooltip validation, first look at the traditional jQuery unobtrusive example.

The following is an example of an application of unobtrusive validation.

validation

When I click the Register button, the error message comes, as shown below:

click on Register button

If I increase the length of the error message, the layout will be broken like this. In the same way, when I place the same length error message below, the Textbox controls come as shown in the screenshot. The same layout-change problem occurs. Hence, this is a bad idea of using a default behavior of the  jQuery Unobtrusive validation plugin. I replaced the error type with a tooltip. It won’t change the layout structure.

Now the jQuery tooltip validation article begins from here,

jQuery tooltip validation using Twitter Bootstrap

Step 1

Create ASP.NET MVC Application.

  1. Create Application with MVC template.

Create a application

2. Add the following files.

add files

3. Create HomeController.cs.

Right click->Controllers folder->Add->Controller->name it as HomeController.cs.

add controller

4. Add Index Method to the Controller.

5. Add View to Index Action method.

Right click->Index Method->Add View->click OK.

Add view

Index view is created.

6. Now, replace the Index.cshtml code with the code given below:

Step 2

Add the script for the validation,

  1. Add myscript.js to the script folder.

    myscript.js

Step 3

Add styles for the error display.

Now run the Application and you will get the Window as shown below:

Enter details

Without entering anything into the fields, just click on the Register button and see what happens.

Register

Restore Database Scema on DNN

Restore Database Scema on DNN

CheapASPNETHostingReview.comDotnetnuke standard installs using the dbo as the default user. Some hosts however, like shared hosting service providers, do not allow you to use dbo. So in this case you have to install Dotnetnuke using your assigned username. This should work without any problems. But in case you have an existing website which was installed using the dbo user and you would like to migrate it to a hosting provider that does not allow dbo you have a problem.

DNN-title-banner

The easiest way to migrate a Dotnetnuke website is by backing up the entire web and the database and restore it to the new environment. This will work fine only if your new environment allows dbo. If it does not you will find that when restoring the database all objects will have been assigned to your username and not to dbo and your web will not run.

To resolve this issue you can follow the steps outlined below after which your web will run without any problems. As this procedure requires changes to the databse please be sure to have a backup of your database and website. Note: This procedure is for a SQL server 2005 database!

Step 1:
Open your web.config file and look for “owner”. Change the owner from dbo to your database username. 
Open your web.config file and look for “owner”. Change the owner from dbo to your database username.

Step 2:
In Microsoft SQL Server management studio select all stored procedures that DO NOT have aspnet in their name, rightclick and select “script as create to new query editor window”. 
In Microsoft SQL Server management studio select all stored procedures that DO NOT have aspnet in their name, rightclick and select “script as create to new query editor window”.

This will create a script for all the selected stored procedures.

Step 3:
Where it says “new owner” below you should change it for your database username! 
Where it says “new owner” below you should change it for your database username!

  • In the just created script search and replace “create procedure” with “alter procedure”
  • Search and replace “create procedure” with “alter procedure” (Note! with 2 spaces!)
  • Search and replace “[dbo]” with “[new owner]”
  • Search and replace “dbo.” with “new owner.”
  • Execute the script

Step 4:
In Microsoft SQL Server management studio select all stored views that DO NOT have aspnet in their name, rightclick and select “script as create to new query editor window”. 
In Microsoft SQL Server management studio select all stored views that DO NOT have aspnet in their name, rightclick and select “script as create to new query editor window”.

Step 5:

  • Search and replace “[dbo]” with “[new owner]”
  • Search and replace “dbo.” with “new owner.”
  • Search and replace “create view” with “alter view”
  • Search and replace “new owner.GetListParentKey” width “dbo.GetListParentKey”
  • Execute the script

Step 6:

  • Go to “functions” “Scalar-valued functions”
  • rightclick and select “script as create to new query editor window” for function “fn_GetVersion”
  • Search and replace “dbo.” with “new owner.” (including the “.”!)
  • Execute script

Step 7:

Open a new query window and paste the following script:

Search and replace [USERNAME] for your database username and execute the script.

Step 8:
Refresh your database manager window and you should now see that all AspNet tables and storedprocedures belong to the dbo user/schema. Open your website in your browser. Your website should now load as normal.

Tips To Secure your ASP.NET MVC Application

Tips To Secure your ASP.NET MVC Application

CheapASPNETHostingReview.com | Best and cheap ASP.NET 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:

1ed

Using DataAnnotations and Localization in ASP.NET Core MVC

Using DataAnnotations and Localization in ASP.NET Core MVC

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core MVC hosting. This article shows how ASP.NET Core localization can be used together with data annotations. The data annotations are used to decorate the data model, and when HTTP POST/PUT (also PATCH) Requests are sent with model errors, the error message is returned localized in the request culture.

Localization Setup

In the Startup class, the AddDataAnnotationsLocalization is added in the ConfigureServices method.

Now a model class can be created and the data annotations can be used. The Length property in this example has a range attribute, with an ErrorMessageResourceName and an ErrorMessageResourceType property set. The ErrorMessageResourceType is used to define the resource itself using the type and the ErrorMessageResourceName is used to define the resource identifier. Only the Length property has localized error messages implemented.

Now a MVC 6 controller can be created which uses the model class. This controller implements POST and PUT action methods, which uses the ModelState to validate the request. If the model is invalid, the error message is returned with a localized value.

Now the POST method can be called in Fiddler or Postman. Underneath is an example of a HTTP POST Request using the it-CH culture. The length property is outside the range and will return an model state error.

Localization can be used in data annotations like previous versions of MVC or Web API and provides a simple way of validating your data inputs.

How to Turn off Asp.net Custom Errors in Web.config

How to Turn off Asp.net Custom Errors in Web.config

CheapASPNETHostingReview.com | Best and cheap ASP.NET Hosting. Some times after hosting web application on the server, we get unexpected error as shown in the below fig. But we did get the detailed message for the unexpected errror. In this article, I would like to share how can we get detailed message for the unexpected error.

disableerror

This type of unexpected error may occurs on local or remote server. In asp.net, we can find the exact error message by setting mode=”Off” with in customErrors tag in web.config of our application. This is the way by which we can find out the exact error in our web application

When we set the customErrors mode=”Off” then we can easily track the error in the application as shown in the fig.

disableerror1

In Asp.net, there are three error modes to trace an error. These modes decide whether or not an error message is displayed. RemoteOnly mode is default mode for displaying error messages.

  1. Off Mode

    This mode is responsible for displaying error mesage on local and remote server in case of an error.

  2. On Mode

    This mode is responsible for displaying custom error page with message on local and remote server in case of an error. By using this mode, we can show our own custom error messages page for specific errors on local and remote server.

  3. RemoteOnly

    This mode is responsible for displaying error mesage on remote server only in case of an error. By using this mode, we can show our own custom error messages page for specific errors on remote server only.

I hope you will enjoy these tricks while programming with Asp.Net. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Tag Helper Component in ASP.NET Core 2.0

Tag Helper Component in ASP.NET Core 2.0

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core 2.0 hosting. How to dynamically write HTML using Tag Helper Components in ASP.NET Core 2.0 ? In this post we will discuss about Tag helper component in ASP.NET Core 2.0

Create an empty project and add a controller:

Add a view:

Add a Tag Helper Component:

Update the Startup class, inject the component class to service container:

Run and observe the page generated (view source or developer tools in browser):

meta

Note that the two meta tags were dynamically generated by the Tag Helper Component.

Discussion

ASP.NET Core 2.0 has introduced “Tag Helper Components” that improve and complement Tag Helpers by giving developers capability to use Dependency Injection with them.

The way this works is that:

  1. We create a Tag Helper to target existing or new (i.e. custom) HTML elements.
  2. We then create a class that inherits from TagHelperComponent and override its Process() method to append HTML content to the Tag Helper’s HTML element.
  3. We then inject this class into the service container, which is executed at runtime.

In case you’re wondering if the solution above is missing a Tag Helper for head HTML element, it’s not. ASP.NET Core team has provided us with two built-in Tag Helpers, one targets head and the other targets the body element: HeadTagHelper and BodyTagHelper

In the solution above our Tag Helper Component is adding few meta tags to the head element. This could be used, for instance, by a blogging engine to output them for search engine optimisation.

I’ve hard-coded entries but of course using Dependency Injection we can inject a service that could retrieve these from a database:

Another possible use-case for a Tag Helper Component, that targets head or body, is to dynamically inject scripts/styles e.g.:

There is an interesting application of this for JavaScript logging

Custom Tag Helpers & Components

We can use these components for custom Tag Helpers too. Let’s say we want to target all the footer elements and inject current time (or visitors count, logo, copyright etc.). We can first create a Tag Helper to target a footer element:

Note: the base class is the new TagHelperComponentTagHelper and not the TagHelper used for non-component scenarios.

Now we can create a Tag Helper Component that targets this Tag Helper:

How To Logging with Microsoft.NET

How To Logging with Microsoft.NET

CheapASPNETHostingReview.com | Best and cheap ASP.NET Hosting. Through this article, we will explain in depth logging in .NET applications. We will explain this through two steps:

  1. Introduction to System.Diagnostics (prebuilt logging namespace in .NET)
  2. Introduction to Log4net

I. System.Diagnostics Namespace

The System.Diagnostics namespace provides classes that allow you to interact with system processes, event logs, and performance counters, Classes like EventLog which provides functionality to write to event logs, read event log entries, and create and delete event logs and event sources on the network. TraceSource which also provides a set of methods and properties that enable applications to trace the execution of code and associate trace messages with their source. In this paragraph, we will implement a tracing/Logging library based on the TraceSource Class. This library enable users to:

  • trace different scenarios inside applications [StartStopErrorInformationCriticalWarning]
  • The Trace destination is configurable, it can be a file, it can be a console application and it supports also sending Log Message by mail.

To do so, this logging utility contains:

  • Interface called Logger.cs
  • Interface called ILogger.cs
  • Enumeration called LogType which presents the destination of trace messages

The class that implements the interface ILogger.cs:

Now let’s see how to configure the library through the configuration file. The configuration file will determine:

  1. The name of the source
  2. The type of destination message [a text file, a console file, etc…]
  3. The trace option output, in our case, the output of any trace containing this message
    • The type of trace [information, Error, warning, etc…]
    • Date Time of the trace
    • Thread ID
    • Process ID
    • TimeStamp

Testing the library:

Console_Display

If we want to customize the destination of trace messages, for example, display the trace message in a file system, we just add a ‘TextWriterTraceListener‘ to the configuration file:

Displaying trace messages in Bloc Notes.

TextListener

  1. You can customize the tracing output’s target by adding or removing TraceListener instances to or from the collection stored in the TraceSource.Listeners property. By default, trace output is produced using an instance of the DefaultTraceListener class. The preceding configuration file example demonstrates removing the DefaultTraceListener and adding a TextWriterTraceListener/ConsoleTraceListener to produce the trace output for the trace source.

    As a Microsoft developer, I have always been more comfortable when implementing my own libraries based on .NET prebuilt namespaces because I want to have absolute control on my source code, but I have seen many projects using Logging with third party libraries, for example, Log4Net. In the next paragraph, we will learn how to integrate this library into our applications.

II. Logging with Log4NET

The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. Log4net is a port of the log4j framework to Microsoft.NET platform. To integrate this library, you must use nuget package manager.

3_-_Add_Log4net_through_nuget

Like the TraceSource class, Log4net library enables the developer to customize message tracing (changing the log destinations and the format of messages). We will write two scenarios:

  • Default Configuration [Console Configuration]

4-_Default_Log4Net_configuration

  • Using custom configuration [saving messages into a text file].

XML Configuration file

Displaying trace messages in Bloc Notes.

5-FileAppender

Summary

Log4net is a port of Log4j to the .NET universe, Log4j is a popular logging framework and that’s why log4net has rapidly grown. The class System.Diagnostics.TraceSource provides high performance logging and tracing for applications but both use nearly the same mechanism.

I hope that you appreciated my effort. Thank you for viewing my blog post, try to download the source code and do not hesitate to leave your questions.

ASP.NET Core Angular Visual Studio 2017 Templates

ASP.NET Core Angular Visual Studio 2017 Templates

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core hosting. The latest tooling in Visual Studio 2017 for .NET Core is pretty good. However, it seemed like built-in templates are a bit lacking. Fortunately, the dotnet sdk, and subsequently the CLI, have libraries available for various Single Page Application framework quick starts.

With the latest version of VS2017 installed, you should have the dotnet core SDK version 1.0.3 installed.

The “dotnet –info” command can be used to confirm SDK version.

ffa

To get started with “dotnet new” (new being the command to create new projects), the SPA templates for Angular and other various frameworks can be utilized after installing this package:

This will run for a bit and install various dependencies. After installation is complete, the available templates can be viewed by running “dotnet new” by itself.

ffa1

The template I’m interested in is the Angular one, of course. By using this template, you get a nice base starting point for an Angular application. Some of the niceties are having the build process already configured for bundling, minification, and various dependencies already configured.

ffa12

Webpack, TypeScript, and other things appear already configured when the project is opened in VS2017.

ffa121

Running the project for the first time can take a bit of time since all of the npm packages and such are pulled down. But, the template does have a few little niceties and is a fully working Angular project. The “Hello, world!” view has some nice information about the template and details some parts of the technology used in the template.

ffa1211

This is a pretty handy template. It supports SEO optimization and Server-side Rendering (SSR). The build process is completely handled by NPM, Webpack and .NET.

One caveat I ran into immediately was in the upgrade process. The template uses Angular 2.x. You can drop to a console and update to Angular 4.x like this:

However, that breaks the application/template entirely. That’s a bit concerning to me. I’d rather drop back to using my previous Angular 2.x template and update it to use VS2017 rather than dealing with a build process that is somewhat fragile.

It is possible to clone it, update the npm packages, run webpack, and have it working. I’m still playing around with it, but may have some code snippets to share soon. At some point, I’d like to have my plunker demos moved over to a standard template that can easily be deployed to Azure or another cloud hosting service.

Using Web.Config customErrors for ASP.NET

Using Web.Config customErrors for ASP.NET

CheapASPNETHostingReview.com | Best and cheap ASSP.NET Hosting. The ASP.NET framework provides built-in settings to control how to respond when an application error occurs. This functionality is part of the Web.Config customErrors section.

Configuration Options for Web.Config <customErrors>

Like most web.config settings, customErrors can be configured within the Machine.config, root web.config or your application web.config file. Usually, it is set per application.

CustomErrors supports the following modes:

  • On – If defaultRedirect is specified, they will see that content. Otherwise the default error screen with fewer details.
  • Off – Detailed error details will be shown to the user. (the “yellow screen of death screen”)
  • RemoteOnly – Default value. Detailed errors only are shown to local users. Remote users receive custom error screens or fewer details.

Example configuration:

How to View Full ASP.NET Error Details, Disabling Custom Errors

If your application is throwing errors, but you cannot see the full error message, you can disable customErrors.

web-config-customerrors-10799

To do this, you will want to set customErrors mode to “Off” as shown below. Be careful though as this could expose sensitive information shown in error messages as well as detailed stack traces.

Other Ways to View ASP.NET Exceptions

There are other ways to track, find, and view application errors besides the ASP.NET yellow screen of death. Ideally, your application should be logging all of your errors to a log file and error monitoring service. You can also check Windows Event Viewer, and you may be able to see your exceptions. Although, be warned that exceptions are rate limited to Event Viewer and it does not record all of them.

How to Log All Application Errors

Depending on your type of application, there are potentially multiple ways to do this. If your application has a Global.asax file, you can subscribe to unhandled exceptions as shown below:

How to View All Application Exceptions With Retrace

Retrace provides code-level performance monitoring for your application. Part of that includes collecting all application exceptions. Retrace can collect unhandled exceptions, exceptions explicitly logged to it, or every single exception ever is thrown (first chance exceptions).

To make the most of your application errors, you should use an error monitoring service, like Retrace. Benefits of an error monitoring service:

  1. Real-time alerts – know immediately when a new error happens
  2. Centralized repository – one place your team can access everything
  3. Error rates – quickly identify large spikes in error rates
  4. Improve productivity – find root cause of problems much faster

How to Running Sitefinity from a Docker Container

How to Running Sitefinity from a Docker Container

CheapASPNETHostingReview.com | Best and cheap Sitefinity Hosting. Since Microsoft announced support for containers in the next version of Windows Server (Windows Server 2016) I’ve been eager to find out if we can run Sitefinity from a container on that OS. The short answer is yes, we can containerize Sitefinity applications and run them on container hosts. This blog post will cover a proof of concept that shows Sitefinity can be containerized and is is influenced by this guide on running Docker containers:

dc SitefinityLogo_woTagline_RGB-1024x433

Prerequisites

  • Sitefinity project connected to a database. For this setup, I have chosen SQL Azure database
  • Windows Container Host running Windows Server 2016 Core. For the purposes of this demo I will be using a VM created on Azure with the Windows Server 2016 Core with Containers Tech Preview 4 image

Let’s roll up our sleeves

If you will be using a container host on Azure, create it and you are ready to go. If you have decided to explore this locally.  The Azure container host image comes with Docker pre-installed so you will have some base images to start from. In the command line run the following command:

Creating Docker container image

For the sake of simplicity we will create the image by running a new container and then committing the changes applied to it in a new image. To create a new Docker container and instantiate a new Powershell session, run the following command:

Once the container is instantiated and our Powershell session has started we need to configure the container to host our Sitefinity website. To achieve this we will use Powershell DSC to install all necessary Windows features and configure our website in IIS. I have prepared a sample DSC configuration and configuration data in this GitHub repo: sf-cntnr-poc. The dsc/sfwebapp.ps1 file contains the necessary configuration and dsc/sfwebapp-data.psd1 contains the variables (Windows feature, URL from which to download the website, etc.). Since I am working in Azure and I do not have access to my local computer, I have zipped my website and uploaded it to Azure Blob. This will serve as the source of my website. If you are using the same approach edit the dsc/sfwebapp-data.psd1 file to point it to the proper URL:

Once you make the necessary changes to those files to reflect your setup you can upload them to Azure blob as well so that they can be downloaded on the Docker container. The DSC configuration uses some community modules to set up our website, so before we apply the configuration we need to download those modules. In the Powershell session of your Docker container run the following commands to install the modules:

Once this is done let’s get the DSC configuration and data files from our blob:

At this point we are ready to configure our container with everything necessary to host a Sitefinity website. First let’s prepare the DSC configuration

And finally run the DSC configuration:

Now get a cup of coffee and wait for the configuration changes to be applied. After the configuration is applied the container will be ready to run a Sitefinity site, however, we need to take care of some firewall settings so that requests can reach the IIS in the container. So let’s exit the container and capture our image:

Opening ports on the firewall

When the commit command is ready you will be able to see your new Docker image in the images list. What is left now is to open the necessary firewall ports, expose port 80 from the Azure management portal, and run our new container. First, to make sure that the Windows firewall is allowing port 80, run the following Powershell command:

Running your containerized site

After you create the necessary endpoint in the Azure management portal all you are left to do is to run the container using the following command:

When the container is ready, the site will be accessed by the outside world using the domain name assigned to the Azure VM, e.g. http://sfcntnr1.cloudapp.net/.