ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.6 Hosting - ASPHostPortal :: How to Upgrade to ASP.NET 4.6 Projects?

clock November 9, 2015 21:59 by author Jervis

The updates in the .NET Framework provide many improvements, including support for new language features in c#, garbage collection, enhancements in cryptography support, feature toggles, new classes in the BCL and others. The RyuJIT compiler adds significant performance gains for 64bit applications, even those not originally targeting the 4.6, improves startup times and can reduce the memory footprint of your application.

While the explicit modification of your projects may not be required to gain some of the 4.6 benefits, there may be other organizational factors that lead you down that path. We’ll work through the mechanics of the upgrade to 4.6 in this post.

Upgrading Your ASP.NET Projects

Every project we create references a specific version of the .NET Framework. This has been true throughout the history of .NET, and though the way we will do it in the future will change with the new project system, the premise remains the same.

For now, you can simply open the properties tab for your project and change the target Framework.

You will be prompted to let you know that some changes may be required.

Now, if you were to try to build the Bootcamp project when you’re only partway through the upgrade, you’d see something similar to the following:

With a message that reads:

“The primary reference “x” could not be resolved because it was built against the “.NETFramework,Version=v4.6” framework. The is a higher version than the currently targeted framework “.NETFramework,Version=4.5.1”.”

You may run into this in other scenarios, as well, especially if you you have references to packages or libraries that get out of sync in your upgrade process. A project that takes on dependencies must be at (or higher than) the target framework of the compiled dependencies. To remedy this, we simply need to complete the upgrade process on the rest of the projects.

Why Upgrade?

Moving from 4.5.x to 4.6 is not a required step in our conversion to an MVC 6 project. In fact, MVC 6 indeed runs on a different framework altogether. To that end, any environment where you have 4.6 installed will “pull up” other assemblies because it is a drop-in replacement for pervious versions.

Perhaps your primary motivator to move to 4.6 is the perf bump in the runtime, or it might be the new language features (which only require a framework install, not a version bump in your target). But it also ensures we’re compatible with other projects in our organization, particularly when we consider the default target for new projects in VS 2015 is against 4.6. If we want to leverage these from other projects in our organization, we want to make sure that we’re not the lowest common denominator in the mix.



ASP.NET Hosting - ASPHostPortal.com :: How to Check Duplicate User Names In ASP.NET Web Pages Sites

clock October 5, 2015 11:39 by author Kenny

How to Check Duplicate User Names In ASP.NET Web Pages Sites

The Web Pages Starter Site template provides a useful starting point for developing a Razor Web Pages site that includes membership. But it doesn't include any mechanism for preventing duplicate user names. This article offers one solution to the problem that uses jQuery.

If you ask how to prevent duplicate user names in forums, one of the suggestions that is often put forward is to apply a unique constraint in the database column that holds the user name. Any attempt to submit a duplicate value will result in an exception being raised in the relevant database provider. You can catch this exception and show the user an appropriate message. This works but it's a fairly clunky solution. And many people feel that you should not use exceptions as a means to manage your business rules.

The solution featured in this article uses AJAX to query the database and to give the user immediate feedback when they enter their chosen user name. The AJAX call requests a page that exists purely to query the database to see if the selected user name is already in use. The solution also includes a server side chekc to ensure that users who have disabled JavaScript so not slip through the net. The solution requires a couple of amendments to the Register.cshtml file in the Starter Site, and the addition of 3 files. But first, the changes to the Register.cshtml page. The first change is in the inclusion of a JavaScript file called dupecheck.js.

@* Remove this section if you are using bundling *@
@section Scripts {
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/Scripts/dupecheck.js"></script>
}

And the second is the server side check to see if the username is in use:

if(Functions.IsDuplicate(email)){
    ModelState.AddError("email", "User name is already taken");
}

I placed this in the if(IsPost) section just after the initial variables that represent the submitted values (email, password and confirmPassword) are declared. The code calls a function named IsDuplicate. The function is declared in a file called Functions.cshtml which is placed in a folder called App_Code:

@functions {
    public static bool IsDuplicate(string username){
        var db = Database.Open("StarterSite");
        var commandText = @"SELECT COUNT(Email) FROM UserProfile WHERE Email = @0";
        return (int)db.QueryValue(commandText, username) > 0;
    }
}

Note that the name of the folder is important. The function returns a bool. The value of the bool is determined as a result if the SQL query which gets a count of the rows containing the provided user name. By default, the Starter Site uses a column called Email in the UserProfile table for the storage of user names. This function is also called in a separate file named DupeCheck.cshtml. This file is placed in the root of the site:

@{
    Layout = null;
    if(IsAjax){
        var username = Request["username"];
        var result = Functions.IsDuplicate(username);
        Json.Write(new { isDupe = result }, Response.Output);
    }
}

DupeCheck.cshtml is designed to work exclusively with AJAX. The code includes an instruction to nullify any layout pages that might have been set in a _PageStart file, and then it uses the IsAjax property to determine if the page has been requested via an AJAX call. If it has, it uses the IsDuplicate method to check the availability of the posted username and returns the result to the calling code. The result is an anonymous type that has one propery: isDupe, which is a boolean. The anonymous type is serialised to JSON by the Json helper.

The final part of the solution is the dupecheck.js file. This uses jQuery:

$(function () {
    $('#email').change(function () {
        $.post(
            '/DupeCheck',
            { username: $(this).val() },
            function (data) {
                var emailValidation = $('span[data-valmsg-for="email"]');
                if (data.isDupe) {
                    if (emailValidation.hasClass('field-validation-valid')) {
                        emailValidation.removeClass('field-validation-valid');
                        emailValidation.addClass('field-validation-error');
                        emailValidation.text('That name is already taken!');
                    }
                } else {
                    if (emailValidation.hasClass('field-validation-error')) {
                        emailValidation.removeClass('field-validation-error');
                        emailValidation.addClass('field-validation-valid');
                        emailValidation.text('');
                    }
                }
            },'json'
        );
    });
});

An event handler is attached to the change event of the user name input (which has an id if email in the Starter Site). The current value is posted to the DupeCheck.cshtml page via AJAX. The code above checks the response from the server to see if the value is a duplicate, and if it is, an appropriate error message is displayed to the user.

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Easy to Design Pie Chart and Donut Chart in ASP.NET

clock September 28, 2015 12:40 by author Kenny

Easy to Design Pie Chart and Donut Chart in ASP.NET

D3.js stands for Data-Driven Document. It is a JavaScript library using which we can manipulate documents based on data. The data can be fetched using multiple ways like Web Services, WCF Services, REST APIs or the relatively new Microsoft ASP.NET Web API amongst many others. Using D3, you can bind the data to the Document Object Model (DOM) and present that data with rich visualizations. D3 internally makes use of CSS, HTML and SVG capabilities to make your data presentable. It is powerful, fast and supports large datasets and dynamic behaviors for interactions and powerful and smooth animations.

D3.js provides easy and declarative selections of DOM nodes using W3C Selector APIs. D3 Selector APIs provides number of methods to manipulate nodes. For example –

  • Setting attributes and applying rich styles
  • Registering Event Listeners
  • You can add, remove and sort DOM nodes
  • You can change the HTML or the text contents of HTML elements
  • You can also have a direct selection/access to the DOM as each selection is an array of nodes

Likewise, we have various features of D3.js selectors which we can use to present data to our DOM nodes.

A simple selector example is the following:

var bodySelection = d3.select('body').style('background-color', 'blue');

In the above example, we are selecting body and changing its background color to blue. Another example would be as follows:

var divSelection = d3.selectAll('div').style('background-color', 'yellow');

In the above example, we are selecting all divs and changing its background color to yellow. If you are familiar with jQuery, the syntax looks similar to jQuery selectors or HTML5 Selectors.

D3 allows us to bind the data to the DOM elements and their attributes using a Data method which takes an array. For example:

d3.selectAll("div")
  .data([200,300,400,100])
  .style("height", function (data) { return data + "px"; });

In the above example, we are selecting all the div’s on the page and based on the index, the first value of an array will be passed to first div, second value to second div and so on.

In D3, you can also make use of Enter and Exit selector methods to create new nodes for incoming data, and remove outing nodes that are no longer used.

You can also apply transitions to nodes using D3. For example –

var area = d3.select('body')
            .append('svg')
            .attr('width', 500)
            .attr('height', 500);
 
var circle = area.append('rect')
                 .attr('width', 100)
                 .attr('height', 100)
                 .attr('fill', 'red');
 
circle.transition()
      .duration(2000)
      .delay(2000)
      .attr('width', 400)
      .each('start', function () {
            d3.select(this).attr('fill', 'green');})
      .transition()
      .duration(2000)
      .attr('height', 400)
      .transition()
      .duration(2000)
      .attr('width', 50)
      .transition()
      .duration(2000)
      .attr('height', 50)
      .each('end', function () {
            d3.select(this).attr('fill', 'blue'); });

In the above example, we are drawing a Rectangle and applying the transition to the same. Likewise, we can make use of various features of D3.js to present our data using rich visualizations.

A Quick overview of ASP.NET Web API

REST(REpresentational State Transfer) has emerged as the prominent way to create web services. By using REST we can build loose coupled services with data available on the web over HTTP protocol.

ASP.NET Web API is a platform for building RESTful applications. ASP.NET Web API is a framework using which we can build HTTP Services which can be called from a broad range of clients, browsers and mobile devices. ASP.NET Web API is the defacto standard of creating web services and replaces WCF.

When we think about exposing data on the web, we usually talk about four common operations which we use on a daily basis in our apps – CREATE, RETRIVE, UPDATE, DELETE.

We call these operations as CRUD operations. REST provides 4 basic HTTP verbs which we can map to our CRUD operations as described here - POST – CREATE, GET – RETRIVE, PUT – UPDATE, DELETE – DELETE.

By using REST, if you can connect to the web, any application can consume your data. When the data is pulled or pushed by using REST, the data is always serialized into or de-serialized from JSON or XML.

Setting up the application and ASP.NET Web API

To start designing the Pie chart and Donut chart, use the following tools and technologies:

  • Microsoft Visual Studio 2013 (Express or Professional)
  • Microsoft SQL Server 2012 (Express or Developer)
  • jQuery
  • D3.js
  • ASP.NET WEB API

Let’s first design the table where we can add our data. To design the table, open SQL Server Management Studio and write the following script:

CREATE TABLE [dbo].[CityPopulationTable](
    [CityID] [int] IDENTITY PRIMARY KEY,
    [CityName] [nvarchar](30) NULL,
    [Population] [int] NULL
)

Create an ASP.NET Web application by choosing Web Forms template. Then add the Entity Framework, jQuery and D3.js libraries into our web application using NuGet.

Once you add these libraries, right click on the Models folder in our Web application under Solution Explorer, and click on Add New Item. Choose Data  > ADO.NET Entity Data Model.

Using Entity Data Model Wizard, connect to our database and choose CityPopulationTable.

It’s time to implement the ASP.NET Web API into our project. Right click the web application and add a new folder with the name Controllers.

After adding the Web API, open Global.asax file and import two namespaces as shown here:

using System.Web.Http;
using System.Web.Routing;

Also add the following code to the Application_Start method –

GlobalConfiguration.Configure(WebApiConfig.Register);

The above line registers the Web API route in our web application. Now under App_Start folder, you will find WebApiConfig.cs file. Open this file and write the following code:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
 
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    var json = config.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
    json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    config.Formatters.Remove(config.Formatters.XmlFormatter);
}

In the above code, we are configuring Web API to make use of JSON formatter with camel casing, as most of the JavaScript developer will expect JSON output in Camel casing.

Now modify the Get method of our Web API controller as shown here:

public class PieChartController : ApiController
{
    NorthwindEntities dataContext = new NorthwindEntities();
    // GET api/piechart
    public IEnumerable<CityPopulationTable> Get()
    {
        return dataContext.CityPopulationTables.ToList();
    }
}

In the above code, we have created an object of our Entity Data model which will give access to the tables. Then we are returning an IEnumerable of our object CityPopulationTables.

Let us design our Pie chart and Donut chart using the Web API data shown in above:

Creating D3 Charts

Add a HTML page with the name ‘CityPolulationPieChart.html’. Once you add the page, we will reference the jQuery and D3.js file in the page:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Pie Chart Example</title>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/d3.js"></script>
</head>

We will make use of jQuery AJAX function to fetch the data from our Web API and display it in a Pie and Donut chart. Let’s add a DOM ready function into our <body> tag. In this function, we will first declare two arrays. First array will hold the data for our chart and the second array will hold the colors which we will use for our chart:

$(function () {
            var chartData = [];
            var colors = [];
});

In the next step, we will fetch the data from our Web API using jQuery $.ajax function. Add this code after our array declaration:

$.ajax({
        type: "GET",
        url: "api/PieChart",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            $.each(result, function (i,j) {
                chartData.push(j.population);
                var currentColor = '#' + Math.floor(Math.random() * j.population+5566656).toString(16);
                colors.push(currentColor);
            });
            console.log(chartData);}
        error: function (msg) {
            $("#result").text(msg);
        }
});

Note: Although I have used success and error here for devs using an older version of jQuery, these methods have been deprecated from jQuery 1.8. You should replace them with .done() and fail().

In the above code, we are using a GET request with the Web API URL and the type of data set to JSON. On successful completion of the request, we are running a loop using $.each() which will push the fetched data into our chartData array. We are also generating colors and adding them into our colors array.

Now it’s time to use the D3 selector. We will use D3 selector to select the body and will append the SVG element to the same by setting its height and width. Add this code after console.log function. The code is shown below –

var radius = 300;
var colorScale = d3.scale.ordinal().range(colors);
                    
var area = d3.select('body').append('svg')
             .attr('width', 1500)
             .attr('height', 1500);

Also note that we are using the scale function of D3 which allows us to set the ordinal scale with the range to set the scale’s output range. We have also added a variable called radius which is set to 300.

The next step is to group the elements and draw an arc into our SVG as shown in the following code:

var pieGroup = area.append('g').attr('transform', 'translate(300, 300)');
var arc = d3.svg.arc()
                .innerRadius(0)
                .outerRadius(radius);

In the above code, we are using radius variable as the outer radius and fixing the inner radius to 0. As the next step, use a pie layout available under D3. Then pass the chart data and append it to our group ‘g’. The code is shown below –

var pie = d3.layout.pie()
       .value(function (data) { return data; })
var arcs = pieGroup.selectAll('.arc')
       .data(pie(chartData))
       .enter()
       .append('g')
       .attr('class', 'arc');

Also observe, we are using D3 selector to select arc class added at the end, which will select all the elements which has a class arc. In the last step,  append the path and fill the color from our array. We will also display the population data as text to our pie chart. The code is shown below –

arcs.append('path')
    .attr('d', arc)
    .attr('fill', function (d) { return colorScale(d.data); });
 
arcs.append('text')
    .attr('transform', function (data) { return 'translate(' + arc.centroid(data) + ')'; })
    .attr('text-anchor', 'middle')
    .attr('font-size', '1em')
    .text(function (data) { return data.data; });

Donut Chart

Designing a Donut chart is very simple. Just change the inner radius to something higher than zero. I am making it 200. The code is as shown here:

var arc = d3.svg.arc()
        .innerRadius(200)
        .outerRadius(radius);

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in