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 5 Hosting - ASPHostPortal :: SEO For ASP.NET Web Sites

clock December 16, 2015 00:36 by author Kenny

SEO For ASP.NET Web Sites

One of the main sources of audience for these internet applications are the Search Engines like Google, Bing, Yahoo etc. Hence, the end application should not only handle your business problems efficiently but also follow some simple rules so that it yields good results in internet arena. This article, will list some of the simple guidelines which you need to consider if your Asp.Net application is an internet site.

1.    Add descriptive and unique Page Title for every page

Every page in your website should have a unique and descriptive page title that can describe what the page offers. You can set the Page Title either declaratively or in the code behind file. Refer below,

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" Title="My Home Page"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

In code behind,

Page.Title = "My Home Page";

2.    Links should be hyperlinks, no linkbutton or javascript navigation for crawlable links

Make sure all your links in your page are hyperlinks. Search engines can crawl a page only if it is linked through a hyper link (anchor tag). Javascript navigations are not search engine friendly since search engines will not understand it.

3.    Use javascript navigation for site related pages that have no search values

Page rank is distributed across the links on your page. Some of the internal website pages like About us, disclaimer, Registration, login, contact us, user profile pages can be navigated through javascript so that the page rank are not distributed to them. Doing like this will make rest of the crawlable content links benefited.

4.    Add Meta Keyword and Description tag for every page

Add Meta keyword and Meta description tag with relevant contents. Search engines will use these tags to understand what the page offers. You can dynamically set the meta tags from codebehind file using the below code,

HtmlHead head = (HtmlHead)Page.Header;

 HtmlMeta metasearch1 = new HtmlMeta();

 HtmlMeta metasearch2 = new HtmlMeta();  

 metasearch1.Name = "descriptions";

 metasearch1.Content = "my personal site";

 head.Controls.Add(metasearch1);

 metasearch2.Name = "keywords";

 metasearch2.Content = "ASP.Net,C#,SQL";

 head.Controls.Add(metasearch2);

The above code will add the below Meta tags to output html.

<meta name="descriptions" content="my personal site" />

<meta name="keywords" content="ASP.Net,C#,SQL" />

In ASP.Net 4.0, Microsoft added 2 new properties on the Page directive (Page object) that lets you to define the Meta keywords and Description declaratively and dynamically from codebehind.

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" MetaKeywords="asp.net,C#" MetaDescription="This is an asp.net site that hosts asp.net tutorials" CodeFile="Default.aspx.cs" Inherits="_Default" %>

In codebehind,

protected void Page_Load(object sender, EventArgs e)

    {

        Page.MetaKeywords = "asp.net,C#";

        Page.MetaDescription = "This is an asp.net site that hosts asp.net tutorials.";

    }

The similar can thing can be achieved in previous versions of .Net Framework by using a custom BasePage class.

5.    Make descriptive urls

Make your website URL descriptive. URL’s that has lots of query string values, numeric ids are not descriptive. It will provide enough information what the page offers. For example, http://www.example.com/products.aspx?catid=C91E9918-BEC3-4DAA-A54B-0EC7E874245E is not descriptive as http://www.example.com/Windows-Hosting

Apart from other parameters, search engines will also consider the website url to match your page for a searched keyword.



ASP.NET Hosting - ASPHostPortal.com : How to Migrating From ASP.NET Web API 2 to MVC 6

clock October 13, 2015 08:54 by author Kenny

How to Migrating From ASP.NET Web API 2 to MVC 6

If you create a new MVC 6 project from the default starter template, it will contain the following code in the Startup class, under ConfigureServices method:

 // Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
 // You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
 // services.AddWebApiConventions();

This pretty much explains it all – the Compatibility Shim is included in an external package, Microsoft.AspNet.Mvc.WebApiCompatShim and by default is switched off for new MVC projects. Once added and enabled, you can also have a look at the UseMvc method, under Configure. This is where central Web API routes can be defined:

      app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}/{id?}",
                defaults: new { controller = "Home", action = "Index" });
            // Uncomment the following line to add a route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        });

Inheriting from ApiController

Since the base class for Web API controllers was not Controller but ApiController, the shim introduces a type of the same name into MVC 6.

While it is obviously not 100% identical to the ApiController from Web API, it contains the majority of public proeprties and methods that you might have gotten used to – the Request property, the User property or a bunch of IHttpActionResult helpers.

Returning HttpResponseMessage

The shim introduces the ability to work with HttpResponseMessage in MVC 6 projects. How is this achieved? First of all, the Microsoft.AspNet.WebApi.Client package is referenced, and that brings in the familiar types – HttpResponseMessage and HttpRequestMessage.

On top of that, an extra formatter is injected into your application – HttpResponseMessageOutputFormatter. This allows you to return HttpResponseMessage from your actions, just like you were used to doing in Web API projects!

How does it work under the hood? Remember, in Web API, returning an instance of HttpResponseMessage bypassed content negotiation and simply forwarded the instance all the way to the hosting layer, which was responsible to convert it to a response that was relevant for a given host.

In the case of MVC 6, the new formatter will grab your HttpResponseMessage and copy its headers and contents onto the Microsoft.AspNet.Http.HttpResponse which is the new abstraction for HTTP response in ASP.NET 5.

As a result such type of an action as the one shown below, is possible in MVC 6, and as a consequence it should be much simpler to migrate your Web API 2 projects.

public HttpResponseMessage Post()
{
    return new HttpResponseMessage(HttpSattusCode.NoContent);
}

Binding HttpRequestMessage

In Web API it was possible to bind HttpRequestMessage in your actions. For example this was easily doable:

    [Route("test/{id:int}")]
    public string Get(int id, HttpRequestMessage req)
    {
        return id + " " + req.RequestUri;
    }
    [Route("testA")]
    public async Task<TestItem> Post(HttpRequestMessage req)
    {
        return await req.Content.ReadAsAsync<TestItem>();
    }

The shim introduces an HttpRequestMessageModelBinder which allows the same thing to be done under MVC 6. As a result, if you relied on HttpRequestMessage binding in Web API, your code will migrate to MVC 6 fine.

How does it work? The shim will use an intermediary type, HttpRequestMessageFeature, to create an instance of HttpRequestMessage from the ASP.NET 5 HttpContext.

HttpRequestMessage extensions

Since it was very common in the Web API world to use HttpResponseMessage as an action return type, there was a need for a mechanism that allowed easy creation of its instances. This was typically achieved by using the extension methods on the HttpRequestMessage, as they would perform content negotiation for you.

HttpError

If you use/used the CreateErrorResponse method mentioned above, you will end up relying on the HttpError class which is another ghost of the Web API past rejuvenated by the compatibility shim.

HttpError was traditionally used by Web API to serve up error information to the client in a (kind of) standardized way. It contained properties such as ModelState, MessageDetail or StackTrace.

It was used by not just the CreateErrorResponse extension method but also by a bunch of IHttpActionResults – InvalidModelStateResult, ExceptionResult and BadRequestErrorMessageResult. As a result, HttpError is back to facilitate all of these types.

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 :: 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.



ASP.NET MVC 6 Hosting - ASPHostPortal :: Remote Validation in ASP.NET MVC

clock August 24, 2015 08:07 by author Kenny

Remote Validation in ASP.NET MVC

ASP.NET is an open-source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup. Remote validation is used to make server calls to validate data without posting the entire form to the server when server side validation is preferable to client side.  It's all done set up model and controller which is pretty neat. 

Using the Code

To implement remote validation in an application we have two scenarios, one is without an additional parameter and the other is with an additional parameter. First we create an example without an additional parameter. In this example we check whether a username exists or not. If the username exists then that means the input user name is not valid. We create a view model class "UserViewModel" under the Models folder and that code is:

using System.Web.Mvc;  
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        public string UserName   
        {  
            get;  
            set;  
        }  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  
}

 

Now we create a static data source, in other words we create a static list of UserViewModel in which we could check whether a username exists or not. You can also use the database rather than a static list. The following code snippet is for StaticData.

using RemoteValidation.Models;  
using System.Collections.Generic;  
 
namespace RemoteValidation.Code   
{  
    public static class StaticData   
    {  
        public static List < UserViewModel > UserList   
        {  
            get {  
                return new List < UserViewModel >   
                {  
                    new UserViewModel   
                    {  
                        UserName = "User1", Email = "user1@web.com"  
                    },  
                    new UserViewModel   
                    {  
                        UserName = "User2", Email = "user2@web.com"  
                    }  
                }  
            }  
        }  
    }  

 

Now we create a controller "ValidationController" in which we create an action method to check whether a user name exists or not and return a result as a JSON format. If the username exists then it returns false so that the validation is implemented on the input field. The following code snippet shows ValidationController under the Controllers folder.

using RemoteValidation.Code;  
using System.Linq;  
using System.Web.Mvc;  
 
namespace RemoteValidation.Controllers   
{  
    public class ValidationController: Controller   
    {  
        [HttpGet]  
        public JsonResult IsUserNameExist(string userName)   
        {  
            bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower())).FirstOrDefault() != null;  
            return Json(!isExist, JsonRequestBehavior.AllowGet);  
        }  
    }  
}

 

Now we add remote validation on the UserName of the UserViewModel property as in the following code snippet.

using System.Web.Mvc;  
 
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        [Remote("IsUserNameExist", "Validation", ErrorMessage = "User name already exist")]  
        public string UserName   
        {  
            get;  
            set;  
        }  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  

 

As in the preceding code snippet, the IsUserNameExist is a method of ValidationController that is called on the blur of an input field using a GET request. Now we create UserController under the Controllers folder to render a view on the UI.

using RemoteValidation.Models;  
using System.Web.Mvc;  
 
namespace RemoteValidation.Controllers   
{  
    public class UserController: Controller   
    {  
        [HttpGet]  
        public ActionResult AddUser()   
        {  
            UserViewModel model = new UserViewModel();  
            return View(model);  
        }  
    }  

Now we add jquery.validate.js and jquery.validate.unobtrusive.js to the project and create a bundle as in the following code snippet.

using System.Web.Optimization;  
 
namespace RemoteValidation.App_Start   
{  
    public class BundleConfig   
    {  
        public static void RegisterBundles(BundleCollection bundles)   
        {  
            bundles.Add(new StyleBundle("~/Content/css").Include(  
                "~/Content/css/bootstrap.css",  
                "~/Content/css/font-awesome.css",  
                "~/Content/css/site.css"));  
 
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
                "~/Scripts/jquery-{version}.js"));  
 
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
                "~/Scripts/jquery.validate*"));  
        }  
    }  

Thereafter we add the following keys in the web.config file.

<add key="ClientValidationEnabled" value="true" />   
<add key="UnobtrusiveJavaScriptEnabled" value="true" />  
 
 

Thereafter we create a view for the AddUser action method. The following code snippet is for the AddUser view.

@model RemoteValidation.Models.UserViewModel  
 
< div class = "panel panel-primary" > < div class = "panel-heading panel-head" > Add User < /div>    
    <div class="panel-body">    
        @using (Html.BeginForm())    
        {    
            <div class="form-horizontal">    
                <div class="form-group">    
                    @Html.LabelFor(model => model.UserName, new { @class = "col-lg-2 control-label" })    
                    <div class="col-lg-9">    
                        @Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })    
                        @Html.ValidationMessageFor(model => model.UserName)    
                    </div > < /div>    
                <div class="form-group">    
                    @Html.LabelFor(model => model.Email, new { @class = "col-lg-2 control-label" })    
                    <div class="col-lg-9">    
                        @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })    
                        @Html.ValidationMessageFor(model => model.Email)    
                    </div > < /div>                    
                <div class="form-group">    
                    <div class="col-lg-9"></div > < div class = "col-lg-3" > < button class = "btn btn-success"  
                     id = "btnSubmit"  
                     type = "submit" > Submit < /button>    
                    </div >
               < /div>    
            </div >  
} < /div>    
</div >   
@section scripts   
{  
    @Scripts.Render("~/bundles/jqueryval")  

Let's run the application and put values into the user name field to execute the remote validation as in the following image.

Figure 1: Remote validation on user name


Now we move to another option, we pass an additional parameter in the remote validation. We pass both the user name and email as a parameter and check whether the username and email combination exist or not on the email input. That's why we add one more method in ValidationController as in the following code snippet for it.

[HttpGet]  
public JsonResult IsUserExist(string email, string userName)   
{  
    bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower()) && u.Email.ToLowerInvariant().Equals(email.ToLower())).FirstOrDefault() != null;  
    return Json(!isExist, JsonRequestBehavior.AllowGet);  

Now we call this method on the Email property of UserViewModel as in the following code snippet.

using System.Web.Mvc;  
 
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        [Remote("IsUserNameExist", "Validation", ErrorMessage = "User name already exist")]  
        public string UserName   
        {  
            get;  
            set;  
        }  
        [Remote("IsUserExist", "Validation", ErrorMessage = "User already exist", AdditionalFields = "UserName")]  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  
}

As in the preceding code snippet, we are passing an additional field using AdditionalFields in Remote. If we must pass more than one parameter then these will be comma-separated. Now run the application and the result will be as shown in the following image.  



ASP.NET 4.5.2 Hosting - ASPHostPortal.com to Launch New Data Center in Paris

clock November 10, 2014 10:44 by author Kenny

ASPHostPortal.com to Launch New Data Center in Paris, France on November 2014

ASPHostPortal is known for credible and unswerving web hosting solutions. Apart from the reliability of the ASPHostPortal Uptime, which features 99.9 per cent average uptime, ASPHostPortal also offers outstanding data center which reflects ASPHostPortal high speed and high performance hosting package.  Recently, ASPHostPortal.com launch its new data center in Paris, France on 9th November 2014 with room for more than 10,000 physical servers, and allowing customers’ to meet their France data residency requirements.

The new facility will provide customers and their end users with ASPHostPortal.com services that meet in-country data residency requirements. It will also complement the existing ASPHostPortal.com Amsterdam data center and London data center, to provide European customers redundancy options within the region. The Paris data center will offer the full range of ASPHostPortal.com web hosting infrastructure services, including bare metal servers, virtual servers, storage and networking.

ASPHostPortal offers the perfect combination of affordability and reliability.  They have an excellent uptime history with several months this year boasting more than 99.9% average uptime.  Their hosting package reflects speed and performance.  Their data center can take much of the credit for such superb services. The new data center will allow customers to replicate or integrate data between Paris, London and Amsterdam data centers with high transfer speeds and unmetered bandwidth (at no charge) between facilities.

“With ASPHostPortal, choosing the data center location is a free feature and option to all customers. The customer simply chooses US, Europe, Asia or Australia. It's simple, intuitive and convenient. The option is free, and there will never be any other cost to the user associated with this option,” said Dean Thomas, Manager at ASPHostPortal.co

Clients who have any questions about the feature and the option that is most suitable for their purposes should feel free to contact ASPHostPortal through their 24/7/365 customer support team. ASPHostPortal will help you choose the right option that will best suit your needs.

For more information about new data center in France, please visit http://asphostportal.com/Hosting-Data-Center-France.

About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and SharePoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal.com strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: How to Bind Pages in ASP.NET

clock September 29, 2014 12:31 by author Kenny

How to Bind Pages in ASP.NET

ASP.NET is a unified Web development model that includes the services necessary for you to build enterprise-class Web applications with a minimum of coding. ASP.NET is part of the .NET Framework, and when coding ASP.NET applications you have access to classes in the .NET Framework. You can code your applications in any language compatible with the common language runtime (CLR), including Microsoft Visual Basic and C#. These languages enable you to develop ASP.NET applications that benefit from the common language runtime, type safety, inheritance, and so on.

If you are familiar with classic ASP, the declarative data binding syntax introduced in ASP.NET will be familiar to you even though the functionality is vastly different. Data binding expressions are the code you see between <%# and %> characters in an ASPX file. The expressions allow you to easily bind controls to data sources, as well as properties, expressions, and results from method calls exposed by the page. While this feature is easy to use, it often causes some confusion about what is allowed and whether it should be employed.

Data binding basics

Data binding expressions link ASP.NET page properties, server control properties, and data sources when the page's DataBind method is called. You can place data binding expressions on the value side of an attribute/value pair in the opening tag of a server control or anywhere in the page. All data binding expressions, regardless of where you place them, must be contained between <%# and %> characters.

When used with data controls (like Repeater, DataGrid, and so forth), the expression parameter is usually a column name from the data source. However, as long as it returns a value, any valid expression may be used. Likewise, the same syntax may be used outside list controls. This includes displaying values on the page or populating control attributes.

Container.DataItem is a runtime alias for the DataItem bound to a specific item. It maps to an individual item from the data source—like one row from a database query or an individual element from an array. The actual data type for the DataItem is determined by the data source. So, if you're dealing with an array of integers, the DataItem will be an integer.

The following list provides a quick review of the VB.NET syntax for various scenarios:

<%# Container.DataItem %>--An array of string values is returned.
<%# Container.DataItem("expression") %>--The specific field from a DataView container is returned.

<%# Container.DataItem.PropertyName %>--The specific string property value of data source is returned.
<%# CStr(Container.DataItem.PropertyName) %>--Returns a property value converted to its string representation.

When you're using C#, the syntax is a bit different. The following list includes the corresponding C# code for each line in the previous list. Notice the basic syntax is the same, but it changes when property values are returned and converted to the appropriate data type.

<%# Container.DataItem %>
<%# ((DataRowView)Container.DataItem)["PropertyName"] %>
<%# ((ObjectType)Container.DataItem).PropertyName %>
<%# ((ObjectType)Container.DataItem).PropertyName.ToString() %>

Syntax is consistent when working with page level properties and methods. The syntax remains the same as long as string values are returned. The following list provides some examples:

<%# propertyName %>--The value for a page level property is returned.
<asp:ListBox id="lstValues" datasource='<%# propertyName %>' runat="server">--The value retrieved from the page level property (array, collection of objects, etc.) is bound to the data control.

<%# (objectName.PropertyName) %>--The value of the page level object property is displayed.
<%# MethodName() %>--The value returned from the page method is displayed.

You may use individual values (albeit properties, method return values, and so forth) on a page using the following syntax:
<%= Value %>

Using the Contain.DataItem object can be tedious, since you must be aware of the data type and convert it accordingly for use. Microsoft does provide the DataBinder class to further simplify development.

Working with DataBinder

Microsoft documentation (on MSDN) states the DataBinder class uses reflection to parse and evaluate a data binding expression against an object at runtime. This method allows RAD designers, such as Visual Studio .NET, to easily generate and parse data binding syntax. This method can also be used declaratively on a Web form's page to simplify casting from one type to another.

You can use the Eval method of the DataBinder class to make .NET do the heavy lifting when using data values in an ASP.NET page. The Eval method accepts the previously covered Container.DataItem object; it works hard to figure out the details of the field identified in the expression and displays it accordingly. It has the following syntax:

DataBinder.Eval(Container.DataItem, "field name", "optional formatting")

The DataBinder.Eval approach is great as it pushes work to the system. On the other hand, you should use it with caution, since time and resources are consumed as the system locates the element and determines its object/data type.

Plenty of options

Data binding makes it relatively simple to include data in ASP.NET pages. There are various data binding options available, which include: binding the data to a control and allowing it to decide how it is presented, or choosing declarative data binding to control presentation within the ASP.NET page. In the end, it comes down to your preference, but it is great to have options.

Best and Cheap ASP.NET Hosting

Are you looking for best and cheap ASP.NET Hosting? Look no further, ASPHostPortal.com is your ASP.NET hosting home! Start your ASP.NET hosting with only $1.00/month. All of our .NET hosting plan comes with 30 days money back guarantee, so you can try our service with no risk. Why wait longer?



nopCommerce Hosting with ASPHostPortal.com :: Easy to Install nopCommerce Hosting on IIS

clock September 25, 2014 11:31 by author Kenny

What is nopCommerce?

nopCommerce is an open source e-commerce solution that is ASP.NET MVC 5.0 based with a MS SQL 2008 (or higher) backend database. nopCommerce is available for free. A solution with comprehensive features that is easy to use for new online businesses, yet powerful enough for the most demanding ecommerce expert.

Why You Should Use nopCommerce?

nopCommerce is new but very popular open source e-commerce solution. nopCommerce is available for free. A solution with comprehensive features that is easy to use for new online businesses, yet powerful enough for the most demanding e-commerce expert. nopCommerce is a secure, scalable and extendable e-commerce platform.

How to Install nopCommerce on IIS?

  • In this tutorial we will cover the process of setting up the nopcommerce( free asp.net shopping cart) solutions using IIS on localhost.
  • Start IIS. To start IIS click on Start->Control Panel->Administrative Tools ->Internet Information Services(IIS) Manager.
  • If IIS is not installed on your PC then follow this tutorial steps to install nop commerce on localhost Install IIS on Windows 7.
  • Download nopCommerce from here if not downloaded already http://www.nopcommerce.com/downloads.aspx. You can download nopcommerce with no source or with source code.
  • Here I have downloaded nopCommerce with no source code.
  • Unzip the downloaded file. Copy the content of the unzipped folder.
  • Use the control panel to create a MS SQL Server database, to hold the nopCommerce data.
  • Begin configuring nopCommerce, by visiting your web site or temporary URL.
  • It may take sever minutes for the initial page load.
  • Enter the MS SQL Server database details into the nopCommerce configuration and setup the database.
  • Enter a user name and password for the site administrator, and then complete the install.
  • The nopCommerce install should now be complete. Visit your web site or temp URL to view the site.

Advantages of nopCommerce

  • Here are some of the advantages that nopCommerce brings to the table when making your E-Commerce decision:
  • It’s FREE! This helps bring down the cost whether you’re building it yourself or having some developers make it for you.
  • It’s Open Source which means that you can expect a lot of customization options and community support.
  • It’s extremely flexible!
  • You’re going to need help. Unless you’re a website developer, you’ll likely need help setting everything up properly and learning how to maintain it. This is why nopCommerce is very popular with Website development agencies.

Best nopCommerce Hosting

Are you looking for best nopCommerce hosting? ASPHostPortal is the answer. ASPHostPortal.com provides full trust web hosting services for your nopCommerce 3.4 site. Full service and fully accountable, we expertly manage your hosting.

  • Uptime & Support Guarantees
    We are so confident in our hosting services we will not only provide you with a 30 days money back guarantee, but also we give you a 99.9% uptime guarantee.
  • Dedicated Application Pool
    With us, your site will be hosted using isolated application pool in order to meet maximum security standard and reliability.
  • Security
    We employ best in breed firewalls and perimeter network protection.


ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: Responsive Layout Using Bootstrap in ASP.NET

clock September 22, 2014 13:29 by author Kenny

ASP.NET Responsive Layout using Bootstrap

In this article we will explain about how to design responsive layout using bootstrap in your ASP.NET site. ASP.NET is an open source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services.

ASP.NET Responsive Layout:

Responsive Web design is the approach that suggests that design and development should respond to the user's behavior and environment based on screen size, platform and orientation. The practice consists of a mix of flexible grids and layouts, images and an intelligent use of CSS media queries.

Why You Need Responsive Web Design?

Every people open website on mobile device, tablet device and desktop on different-different size that time our website layout is not good looking so web designer design the different-different website for different-different devices for good look and feel website so that process is very time taken. So reduce that process invent to “Responsive Layout” word.

Pillar of Responsive Layout:

1. Fluid Grids:

The general practice in web design is to employ fixed width layouts. It means that the page and its constituent elements have a fixed size and width and positioned around the center. Liquid layouts offer us a greater advantage with the increasing number of devices with web access. A liquid layout expands with the page.

2. Flexible Images:

Web page text is fluid by default: as the browser window narrows, text reflows to occupy the remaining space. Images are not naturally fluid: they remain the same size and orientation at all configurations of the viewport, and will be cropped if they become too large for their container. This creates a problem when displaying images in a mobile browser: because they remain at their native size, images may be cut off or displayed out-of-scale compared to the surrounding text content as the browser narrows.

3. Media Queries:

Fluid grid layouts are very important for responsive web development, but there are other issues to consider. If the width of the device becomes too narrow, like in a small mobile phone, the website design can fall apart. This is where media queries come in. These media queries are based in CSS3 and allow us to not only target the particular device classes but physical characteristics of the device which is rendering the web site.

Add these four files:

<link href="~/Content/bootstrap-3.1.1-dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/blog.css" rel="stylesheet" />
<script src="~/scripts/jquery-2.1.0.min.js"></script>
<script src="~/scripts/bootstrap-3.1.1-dist/js/bootstrap.min.js"></script>

Example:

Html Code

<header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" role="banner">
    <div class="container">
        <div class="navbar-header">
            <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            @Html.ActionLink("Brand", "Index", "Home", null, new { @class = "navbar-brand" })
        </div>
        <nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation">
            <ul class="nav navbar-nav">
                <li class="active">@Html.ActionLink("Home", "", "")</li>
                <li>@Html.ActionLink("Article", "", "")</li>
                <li>@Html.ActionLink("Blog", "", "")</li>
                <li>@Html.ActionLink("Forum", "", "")</li>
                <li>@Html.ActionLink("Interview", "", "")</li>
                <li class="dropdown">
                    <a class="dropdown-toggle" data-toggle="dropdown" href="#" id="themes">Themes <span class="caret"></span></a>
                    <ul class="dropdown-menu" aria-labelledby="themes">
                        <li><a href="../default/">Default</a></li>
                        <li class="divider"></li>
                        <li><a href="../david/">David</a></li>
                        <li><a href="../lily/">Lily</a></li>
                        <li><a href="../jasmine/">Jasmine</a></li>
                    </ul>
                </li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <li>@Html.ActionLink("Sign Up", "", "")</li>
                <li>@Html.ActionLink("Login", "", "")</li>
                <li>
                    <form class="navbar-form navbar-left" role="search">
                        <div class="form-group">
                            <input type="text" class="form-control" placeholder="Search">
                        </div>
                    </form>
                </li>
            </ul>
        </nav>
    </div>
</header>
<div class="container">
    <br />
    <br />
    <div class="row">
        <img src="~/Content/Images/Sample1.png" class="banner" />
    </div>
    <br />   
    <div class="row">
        <div class="col-md-4">
            <img src="~/Content/Images/mobile-devlopment.png" />
        </div>
        <div class="col-md-8">
            <p>

Web page text is fluid by default: as the browser window narrows, text reflows to occupy the remaining space. Images are not naturally fluid: they remain the same size and orientation at all configurations of the viewport, and will be cropped if they become too large for their container. This creates a problem when displaying images in a mobile browser: because they remain at their native size, images may be cut off or displayed out-of-scale compared to the surrounding text content as the browser narrows.

 </p>
        </div>
    </div>
    <br />
    <br />
    <div class="well">
        <div class="row">
            <div class="col-md-6">
                <label>First Name</label>
                <input type="text" />
            </div>
            <div class="col-md-6">
                <label>Last Name</label>
                <input type="text" />
            </div>
        </div>
        <br />
        <div class="row">
            <div class="col-md-6">
                <label>Email ID</label>
                <input type="text" />
            </div>
            <div class="col-md-6">
                <label>Country</label>
                <select>
                    <option>---Select---</option>
                    <option>USA</option>
                    <option>UK</option>
                    <option>Netherland</option>
                    <option>Hongkong</option>
                </select>
            </div>
        </div>
        <br />
        <div class="row">
            <div class="col-md-6">
                <label>State</label>

                <select>
                </select>
            </div>
            <div class="col-md-6">
                <label>City</label>
                <select>
               </select>
            </div>
        </div>
        <br />
        <div class="row">
            <div class="col-md-6">
                <label>Zip Code</label>
                <input type="text" />
            </div>
            <div class="col-md-6">
                <label>Contact No</label>
                <input type="text" />
            </div>
        </div>
        <br />
        <div class="row">
            <div class="col-md-12 text-right">
                <input type="button" value="Submit" class="btn btn-info" />
                <input type="button" value="Clear" class="btn btn-info" />
            </div>
        </div>
    </div>
    <br />
    <br />
</div>

Blog.css

Img
{
    width: auto;
    max-width: 100%;
}
.banner {
    width:100%;
    height:250px;

}
input[type='text'],select {
    width:100%;
    height:30px;
}
@media screen and (min-width: 100px) and (max-width:750px) {
    .banner {
        display:none;
    }
}



ASP.NET 4.5.2 Hosting with ASPHostPortal :: How to Publish and Deploy an ASP.NET Application in IIS

clock September 16, 2014 12:08 by author Kenny

Simple Way to Publish and Deploy an ASP.NET Application in IIS

ASP.NET is an open source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. While Internet Information Services (IIS, formerly Internet Information Server) is an extensible web server created by Microsoft for use with Windows NT family. IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

In this post, we will describe you how to publish and deploy your ASP.NET application in IIS. Actually it is so simple thing, you can publish your web application to the File System and copy paste all the files to your server. After that, you can add a new website from IIS. If you are not sure what files you should include, it's better to choose 'All files in the project' from the Package/Publish Web. Otherwise choose 'Only files needed to run this application'. You can set this by right clicking on the web application in the solution explorer and choosing 'Package/Publish Settings'.

Right click on your project in the solution explorer and choose 'Publish'. From the dialog box, as the publish method, choose 'File System'. And choose some directory as the Target Location.

You can add the website by right clicking on the 'Sites' in IIS.

Then give a name to your site and select the Physical path from where you copied the site folder

Best and Cheap ASP.NET Hosting

Are you looking for best and cheap ASP.NET Hosting? Look no further, ASPHostPortal.com is your ASP.NET hosting home! Start your ASP.NET hosting with only $1.00/month. All of our .NET hosting plan comes with 30 days money back guarantee, so you can try our service with no risk. Why wait longer?



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