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 Core 1.0 Hosting - ASPHostPortal.com :: How To Configure your ASP.​NET Core 1.0 Application

clock June 14, 2016 20:26 by author Armend

The Web.Config is gone and the AppSettings are gone with ASP.NET Core 1.0. How do we configure our ASP.NET Core Application now? With the Web.Config, also the config transform feature is gone. How do we configure a ASP.NET Core Application for specific deployment environments?

Configuring

Unfortunately a newly started ASP.NET Core Application doesn't include a complete configuration as a sample. This makes the jump-start a little difficult. The new Configuration is quite better than the old one and it would make sense to add some settings by default. Anyway, lets start by creating a new Project.
Open the Startup.cs and take a look at the controller. There's already something like a configuration setup. This is exactly what the newly created application needs to run.

public Startup(IHostingEnvironment env)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables();
    if (env.IsDevelopment())
    {
        // This will push telemetry data through Application Insights
        // pipeline faster, allowing you to view results immediately.
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    Configuration = builder.Build();
}

But in the most cases you need much more configuration. This code creates a ConfigurationBuilder and adds a appsettigns.json and environment variables to the ConfigurationBuilder. In development mode, it also adds ApplicationInsights settings.
If you take a look into the appsettings.json, you'll only find a ApplicationInsights key and some logging specific settings (In case you chose a individual authentication you'll also

see a connection string):
{
  "ApplicationInsights": {
    "InstrumentationKey": ""
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Where do we need to store our custom application settings?
We can use this appsettings.json or any other JSON file to store our settings. Let's use the existing one to add a new section called AppSettings:

{
...
    "AppSettings" : {
        "ApplicationTitle" : "My Application Title",
        "TopItemsOnStart" : 10,
        "ShowEditLink" : true
    }
}

This looks nice, but how do we read this settings?

In the Startup.cs the Configuration is already built and we could use it like this:

var configurationSection = Configuration.GetSection("AppSettings");
var title = configurationSection.Get<string>("ApplicationTitle");
var topItmes = configurationSection.Get<int>("TopItemsOnStart");
var showLink = configurationSection.Get<bool>("ShowEditLink");
We can also provide a default value in case that item doesn't exist or in case it is null
var topItmes = configurationSection.Get<int>("TopItemsOnStart", 15);

To use it everywhere we need to register the IConfigurationRoot to the dependency injection container:

services.AddInstance<IConfigurationRoot>(Configuration);

But this seems not to be a really useful way to provide the application settings to our application. And it looks almost similar as in the previous ASP.NET Versions. But the new configuration is pretty much better. In previous versions we created a settings facade to encapsulate the settings, to not access the configuration directly and to get typed settings.
No we just need to create a simple POCO to provide access to the settings globally inside the application:

public class AppSettings
{
    public string ApplicationTitle { get; set; }
    public int TopItemsOnStart { get; set; }
    public bool ShowEditLink { get; set; }
}

The properties of this class should match the keys in the configuration section. Is this done we are able to map the section to that AppSettings class:

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

This fills our AppSettings class with the values from the configuration section. This code also adds the settings to the IoC container and we are now able to use it everywhere in the application by requesting for the IOptions<AppSettings>:

public class HomeController : Controller
{
    private readonly AppSettings _settings
    public HomeController(IOptions<AppSettings> settings)
    {
        _settings = settings.Value;
    }
    public IActionResult Index()
    {
        ViewData["Message"] = _settings.ApplicationTitle;
        return View();
    }

Even directly in the view:

@inject IOptions<AppSettings> AppSettings
@{
    ViewData["Title"] = AppSettings.Value.ApplicationTitle;
}
<h2>@ViewData["Title"].</h2>
<ul>
    @for (var i = 0; i < AppSettings.Value.TopItemsOnStart; i++)
    {
        <li>
            <span>Item no. @i</span><br/>
            @if (AppSettings.Value.ShowEditLink) {
                <a asp-action="Edit" asp-controller="Home"
                   asp-route-id="@i">Edit</a>
            }
        </li>
    }
</ul>

With this approach, you are able to create as many configuration sections as you need and you are able to provide as many settings objects as you need to your application.
What do you think about it? Please let me know and drop a comment.

Environment specific configuration

Now we need to have differnt configurations per deployment environment. Let's assume we have a production, a staging and a development environment where we run our application. All this environments need another configuration, another connections string, mail settings, Azure access keys, whatever...
Let's go back to the Startup.cs to have a look into the constructor. We can use the IHostingEnvironment to load different appsettings.json files per environment. But we can do this in a pretty elegant way:

.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)

We can just load another JSON file with an environment specific name and with optional set to true. Let's say the appsettings.json contain the production and the default

  • settings and the appsettings.Staging.json contains the staging sepcific settings. It we are running in Staging mode, the second settings file will be loaded and the existing settings will be overridden by the new one. We just need to sepcify the settings we want to override.
  • Setting the flag optional to true means, the settings file doesn't need to exist. Whith this approatch you can commit some default setings to the source code repository and the top secret access keys and connections string, could be stored in an appsettings.Development.json, an appsettings.staging.json and an appsettings.Production.json on the buildserver or on the webserver directly.

Conclusion

As you can see, configuration in ASP.NET Core is pretty easy. You just need to know how to do it. Because it is not directly visible in a new project, it is a bit difficult to find the way to start.

 



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 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 = "[email protected]"  
                    },  
                    new UserViewModel   
                    {  
                        UserName = "User2", Email = "[email protected]"  
                    }  
                }  
            }  
        }  
    }  

 

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 Hosting - ASPHostPortal.com :: How to use Data Annotations Validation in ASP.NET 4.5

clock March 18, 2015 06:28 by author Mark

Data Annotations Validation in ASP.NET

This article explains how to use data annotations for validation in ASP.Net 4.5. So, let's proceed with the following
The effect of a custom validation message: Required, String Length, Data Type, Range, Compare and Regular Expression.

Creating a Registration Page

Create a new project using "File" -> "New" -> "Project..." then select web "ASP.NET Web Forms Application". Name it "DataAnnotationsValidation".
seelct New ASP.NET Project then select the template Empty and select Web Forms then click OK.
Next, create the code-behind as follows, displaying the validation errors to the users in the Registration.aspx.

Registration.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Registration.aspx.cs" Inherits="DataAnnotationsValidation.Registration" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>Employees Registration</title> 
    <link href="Content/bootstrap.min.css" rel="stylesheet" /> 
</head> 
<body> 
    <form id="form1" runat="server"> 
        <div class="container"> 
            <div class="well"> 
                <h1>Data Annotations  Validation in ASP .NET 4.5 </h1> 
            </div> 
            <div class=" panel panel-default"> 
                <div class="panel-heading"> 
                    <h3 class="panel-title">Employees Registration</h3> 
                </div> 
                <div class="panel-body"> 
                    <div class="text-center"> 
                    <asp:ValidationSummary ID="validationSummary" runat="server" ShowModelStateErrors="true" DisplayMode="List" ForeColor="Red"  /> 
                    </div> 
                        <div class="col-md-8"> 
                            <div class="form-group col-lg-12"> 
                                <label>First Name</label> 
                                <asp:TextBox ID="FirstName" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-12"> 
                                <label>Last Name</label> 
                                <asp:TextBox ID="LastName" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-12"> 
                                <label>User ID</label> 
                                <asp:TextBox ID="UserID" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Password </label> 
                                <asp:TextBox ID="Password" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Password Confirm </label> 
                                <asp:TextBox ID="PasswordConfirm" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Mobile </label> 
                                <asp:TextBox ID="Mobile" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Age </label> 
                                <asp:TextBox ID="Age" runat="server" class="form-control"></asp:TextBox> 
                            </div>                             
                            <div class="form-group col-lg-6"> 
                                <label>Email </label> 
                                <asp:TextBox ID="Email" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Email Confirm </label> 
                                <asp:TextBox ID="EmailConfirm" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>DOB </label> 
                                <asp:TextBox ID="Date" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Salary </label> 
                                <asp:TextBox ID="Total" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>City </label> 
                                <asp:TextBox ID="HomeCity" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Department </label> 
                                 
                                <asp:DropDownList ID="Department" runat="server" class="form-control"> 
                        <asp:ListItem Value="">Choose an Option</asp:ListItem>
                        <asp:ListItem Value="HR">HR</asp:ListItem> 
                        <asp:ListItem Value="Account">Account</asp:ListItem> 
                                    </asp:DropDownList> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <asp:Button ID="btnsubmit" runat="server" Text="submit" /> 
                            </div> 
                        </div>                     
                </div> 
                </div> 
            </div> 
    </form> 
</body> 
</html>

Create DataAnnotationsValidation.Models for Validation
Now, do something with Models then click Add -> Class.
Applying validation attributes to the Validation class

Validation.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web;   
    //using Namespace 
    using System.ComponentModel.DataAnnotations; 
    namespace DataAnnotationsValidation.Models 
    { 
        public class Validation 
        {         
            [Required] 
            [StringLength(120, MinimumLength = 3)] 
            public string FirstName { get; set; }  
            [Required] 
            [StringLength(120, MinimumLength = 3)] 
            public string LastName { get; set; } 
            [Required] 
            [StringLength(25, MinimumLength = 3)] 
            public string UserID { get; set; } 
            [Required] 
            [DataType(DataType.Password)] 
            public string Password { get; set; } 
            [Required] 
            [Compare("Password")] 
            public string PasswordConfirm { get; set; } 
            [Required] 
            [Range(18, 100, ErrorMessage = "Please enter an age between 18 and 50")] 
            public int Age { get; set; }   
            [Required]        
            [StringLength(10)] 
            public int Mobile { get; set; }           
            [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email doesn't look like a valid email address.")] 
            public string Email { get; set; }     
            [Compare("Email")] 
            public string EmailConfirm { get; set; }    
            [Range(typeof(decimal), "0.00", "15000.00")] 
            public decimal Total { get; set; }   
            [Required] 
            [DataType(DataType.Date)] 
            public DateTime Date { get; set; }       
            [Required] 
            public string HomeCity { get; set; }      
            [Required] 
            public string Department { get; set; }     
        } 
    } 

Next, create the code-behind as follows.

Registration.aspx.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.UI; 
    using System.Web.UI.WebControls;     
    //using Namespace Models 
    using System.Web.ModelBinding; 
    using DataAnnotationsValidation.Models;    
    namespace DataAnnotationsValidation 
    { 
        public partial class Registration : System.Web.UI.Page 
        { 
            protected void Page_Load(object sender, EventArgs e) 
            { 
                if (IsPostBack) 
                { 
                    Validation v = new Validation(); 
                    if (TryUpdateModel(v, new FormValueProvider(ModelBindingExecutionContext))) 
                    { 
                        ShowMessage(v.ToString());                     
                    } 
                } 
            } 
            /// <summary> 
            /// This function is used for show message. 
            /// </summary> 
            /// <param name="msg"></param> 
            void ShowMessage(string msg) 
            { 
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + msg + "');</script>");
            }     
        } 
    }

Now run the page, it will look like the following to use validation to check the input.

Best ASP.NET 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 4.5 Hosting - ASPHostPortal :: How to Drag Drop Elements in ASP.NET MVC 5 using HTML 5, Web API and jQuery

clock December 22, 2014 05:24 by author Mark

Providing rich web UI experiences like Charts, Editable tabular interface, offline capabilities, dragging-dropping data on the page etc. can be a challenging task. To implement these features, a developer must plan the application based upon different browsers capabilities. A couple of years ago, this was achievable with a lot of efforts using some complex JavaScript code.

As the web progressed, modern browsers has made it possible to take web development to the next level. To complement, there are several libraries like jQuery, Angular, DOJO, etc. that can provide new UI rich features to enhance your applications. But wouldn’t it be nicer if the HTML itself provides some of these cool features using markup?
HTML5 has been developed with the current and future browser development in mind. Apart from being backward compatible, HTML5 contains many new elements and APIs for adding Rich UX capabilities to the application. Drag-Drop is one such useful feature available in HTML5 that can be used for data management on the page.
In HTML 5, an element can be made draggable using draggable=true in the markup. To monitor the process of drag-drop, we need to make use of the following events: dragstart, drag, dragenter, dragleave, dragover, drop, dragend.
The process of implementation has the following elements:

  • The source element applied with attribute draggable=true.
  • The data payload which means the data to be dragged and dropped.
  • The target where the drop is made.

Drag-Drop in ASP.NET MVC 5 using HTML 5, Web API and jQuery

To implement the Drag-Drop application, we will be using the following technologies:
ASP.NET MVC 5
WEB API with Attribute Routing
jQuery

  • Step 1: Open Visual Studio 2013 (the application uses Ultimate with Update 3), and create an Empty MVC application.
  • Step 2: In the App_Data folder of the application add a new SQL Server database with the name ‘Application.mdf’ as below:

In this database, add a new table called ‘Products’ using the following script:
CREATE TABLE [dbo].[Products] (
    [ProductId]   INT          IDENTITY (1, 1) NOT NULL,
    [ProductName] VARCHAR (50) NOT NULL,
    [Quantity]    INT          NOT NULL,
    PRIMARY KEY CLUSTERED ([ProductId] ASC)
);

The above table will contain products which we will fetch in our View.

  • Step 3: In the Models folder, add a new EntityFramework with the name ApplicationEDMX. In the wizard that comes up, select the Application.mdf database and the Products table designed in the above step. After completing the wizard, the following table mapping gets displayed.

  • Step 4: In the controllers folder, add a new Empty WEB API Controller with the name ProductsAPIController. In this API controller add the following code:

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using A1_HTML5_DragDrop.Models;
namespace A1_HTML5_DragDrop.Controllers
{
    public class ProductsAPIController : ApiController
    {
        ApplicationEntities ctx;
 
        public ProductsAPIController()
        {
            ctx = new ApplicationEntities();
        }
 
        [Route("Products")]
        public IEnumerable<Product> GetProducts()
        {
            return ctx.Products.ToList();
        }
    }
}

The above code declares an object of ApplicationEntities, which got generated using EntityFramework. The GetProducts() returns a list of products. This method is applied with an Attribute Route ‘[Route(“Products”)]’ which will provide the URL to make call to this method using client-side framework (e.g. ajax method). You can read more on Attribute routing in my other article Practical Use of ASP.NET Web API Attribute Routing in an MVC application.

  • Step 5: In the controllers folder, add a new Empty MVC controller of the name ProductController. This controller class will generate an Index method. Scaffold a new Empty view from the Index method.
  • Step 6: Add the following markup in the Index view:

<table>
    <tr>
        <td>
            <h1>Product List</h1>
        </td>
        <td>
            <h1>Selected Products</h1>
        </td>
    </tr>
    <tr>
        <td>
            <div id="dvleft">
                <ul id="lstproducts">
                </ul>
            </div>
        </td>
        <td>
            <div id="dvright">
                <ul id="lstselectedproducts"></ul>
            </div>
        </td>
    </tr>
</table>

The above markup has a table with two rows. The first row shows headers for Product List and selected products. The second row contains <div>s containing list in it. The ‘lstproducts’ list will show the Products retrieved from the server. The ‘lstselectedproducts’ will show selected products by the end-user using Drag-Drop.
Add the following styles in the View (better to use a separate stylesheet but I will keep it here for readability):
<style type="text/css">
    table, td {
        background-color:azure;
     border:double;
    }
    #dvright,#dvleft {
        background-color:azure;
       height:200px;
       width:300px;
    }
</style>

  • Step 7: In the page add the following Script:

<script type="text/javascript">
    $(document).ready(function () {
        loadProducts();
        //Function to set events for Drag-Drop
        function setEvents() {
            var lstProducts = $('li');
            //Set Drag on Each 'li' in the list
                $.each(lstProducts, function (idx, val) {
                    $('li').on('dragstart', function (evt) {
                        evt.originalEvent.dataTransfer.setData("Text", evt.target.textContent);
                        evt.target.draggable = false;
                    });
                });
            //Set the Drop on the <div>
                $("#dvright").on('drop', function (evt) {
                    evt.preventDefault();
                    var data = evt.originalEvent.dataTransfer.getData("Text");
                    var lst = $("#lstselectedproducts");
                    var li = "<li>"+data+"</li>";
                    li.textContent = data;
                    lst.append(li);
                });
 
            //The dragover
                $("#dvright").on('dragover', function (evt) {
                    evt.preventDefault();
                });
        }
        ///Function to load products using call to WEB API
        function loadProducts() {
            var items="";
            $.ajax({
                url: "/Products",
                type: "GET"
            }).done(function (resp) {
                $.each(resp, function (idx, val) {
                    items += "<li draggable='true'>" + val.ProductName + "</li>";
                });
                $("#lstproducts").html(items);
                setEvents();
            }).error(function (err) {
                alert("Error! " + err.status);
            });
        }
    });
</script>

The script has the following specifications:

  • The function ‘loadProducts()’ makes an ajax call to WEB API. When the call is successful, the iteration is done through the response. This iteration adds the <li> tag in the ‘lstproducts’ list with the draggable attribute set to true.
  • The function ‘setEvents()’ performs the following two step operations:
  • subscribe to the ‘dragstart’ event for each <li> and set the data transfer with the ‘Text’ property. This is the text content of the <li> selected. Once any <li> is dragged, the drag on the same is disabled using evt.target.draggable =false; statement.
  • The <div> of id ‘dvright’ is subscribed to ‘drop’ event, it accepts the dragged Text. Once the text is accepted, it is set to the <li> which is dynamically appended in the list with id as ‘lstselectedproducts’.
  • Step 8: Run the application, the Products data gets loaded:

    Drag the Product from the ‘Product List’ and drop it in the ‘Selected Products’ as seen here:

    • The above Red Mark shows the Drag Action. Once the drop operation is over the result will be as seen here:

Conclusion:

The HTML 5 Native support for Drag-Drop provides an easy mechanism of handling Data as well as UI operations. Since the support is native to HTML 5, no additional library is required.



Classic ASP Hosting - ASPHostPortal.com :: Cropping picture using jQuery, Jcrop with ASPJpeg

clock October 23, 2014 06:15 by author Ben

As we know the assorted websites like Facebook, LinkedIn, Google and so forth., are utilizing Impression Cropping instrument when we incorporate a brand new picture. I found many ways to do that perform but lately I received Jcrop for image cropping. Jcrop will be the quick and simple way to include impression cropping performance for your net software with all the jQuery help.


Jcrop is simply a device which lets you crop image with reside preview. But, after the cropping picture, you have to create a new picture using the picked X-Axis, Y-Axis, Width and Height. I found several tricks to produce new photo through Method.Drawing.Image but I could not get this better to use cropping impression. So I decided to utilize ASPJpeg for making new picture.

ASPJpeg is a server part which will assist your ASP.Net apps with all their image-management wants. With ASPJpeg, you can create high-quality thumbnails, logo-stamp images, extract metadata details from images, crop, improve, rotate, convert, and much much more. But, listed here we are going to use for CROPPING image.

How to begin? (Jcrop Set up)

Add the following files into your project

  • jquery.min.js
  • jquery.Jcrop.js
  • jquery.Jcrop.css


Now we'd like to include above documents into our <head> segment and some fashion courses for HTML factors also as create features inside the webpage with all the OnChange and OnSelect event handler. These occasions are utilized to update existing selection of coordinates within the Concealed Fields.

<head runat="server">
<style type="text/css">
h2.panelTitle { font-size: 18px; margin-bottom: 5px; }
p.content { color: #5f5f61; width: 50%; }
div.imgCrop { width: 330px; float: left; }
div.imgPreview { width: 140px; float: left; margin-top: 40px; }
div.previewOverflow { width: 115px; height: 115px; overflow: hidden; }
div.previewText { color: #333; text-align: center; width: 115px; font-size: 14px; margin-top: 5px; }
div.clear { clear: both; height: 0; }
</style>
 
<link href="/_assets/js/jcrop/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
<script src="/_assets/js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/_assets/js/jcrop/jquery.Jcrop.js" type="text/javascript"></script>
 
<script type="text/javascript">
var imgWidth = 0;
var imgHeight = 0;
 
function getImageDimensions(w, h) {
imgWidth = w;
imgHeight = h;
}
 
// Initialize Jcrop
$(function() {
jQuery('#imgCrop').Jcrop({
    onSelect: storeCoords,
    onChange: storeCoords,
    minSize: [115, 115],
    setSelect: [0, 0, 115, 115],
    aspectRatio: 1
});
});
 
// Update every move of the cropping in the Hidden Fields and Live Preview
function storeCoords(c) {
  var rx = 115 / c.w;
  var ry = 115 / c.h;
 
  jQuery('#X1').val(c.x);
  jQuery('#Y1').val(c.y);
  jQuery('#X2').val(c.x2);
  jQuery('#Y2').val(c.y2);
  jQuery('#W').val(c.w);
  jQuery('#H').val(c.h);
 
  jQuery('#preview').css({
    width: Math.round(rx * imgWidth) + 'px',
    height: Math.round(ry * imgHeight) + 'px',
    marginLeft: '-' + Math.round(rx * c.x) + 'px',
    marginTop: '-' + Math.round(ry * c.y) + 'px'
  });
};
</script>
</head>


Add the following code in your <body> section


<body>
<form id="form1" runat="server">
  <div style="padding: 10px;">
    <!-- PANEL #1: Choose Upload File -->
    <asp:Panel runat="server" ID="step1">
      <h2 class="panelTitle"> Update a picture of yourself</h2>
      <asp:FileUpload ID="FileUpload1" runat="server" />
      &nbsp;
      <asp:Button runat="server" Text="Upload" ID="btnUpload" OnClick="btnUpload_Click" />
      <br />
      <asp:Label ID="lblError" runat="server" Visible="false" />
      <p class="content"> You can upload a JPG, GIF, or PNG file. (Do not upload pictures containing celebrities, nudity, artwork or copyrighted images.)</p>
    </asp:Panel>
 
    <!-- PANEL #2: Show the Image Corpping with Preview -->     
    <asp:Panel runat="server" ID="step2" Visible="false">
      <h2 class="panelTitle"> Crop this picture of yourself</h2>
      <p class="content"> You can drag the box to select the crop area, and use the handle to resize it.<br />
        <asp:LinkButton runat="server" ID="lbBackToUpload" Text="Back to upload" OnClick="lbBackToUpload_Click"></asp:LinkButton>
      </p>
      <div>
        <div class="imgCrop">
          <asp:Image ID="imgCrop" runat="server" />
        </div>
        <div class="imgPreview">
          <div class="previewOverflow">
            <asp:Image ID="preview" runat="server" />
          </div>
          <div class="previewText"> Preview</div>
        </div>
        <div class="clear"> </div>
      </div>
      <br />
      <asp:HiddenField ID="X1" runat="server" />
      <asp:HiddenField ID="Y1" runat="server" />
      <asp:HiddenField ID="X2" runat="server" />
      <asp:HiddenField ID="Y2" runat="server" />
      <asp:HiddenField ID="W" runat="server" />
      <asp:HiddenField ID="H" runat="server" />
      <asp:Button ID="btnCrop" runat="server" Text="Apply Changes" OnClick="btnCrop_Click" />
      &nbsp;
      <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
    </asp:Panel>
    <asp:Panel ID="pnlCropped" runat="server" Visible="false">
      <asp:Image ID="imgCropped" runat="server" />
    </asp:Panel>
  </div>
</form>
</body>


After added above snipts, we will work on the backend side. We have 5 methods to create on the backend side.
  • CancelCrop (Private Method)
  • btnUpload_Click
  • btnCrop_Click
  • btnCancel_Click
  • lbBackToUpload_Click

Add Reference of ASPJpeg

Ahead of the previously mentioned techniques we have to add ASPJpeg Reference into our Bin folder, follow the process to incorporate an ASPJpeg Reference File.

Step 1: Right click on the Bin Folder / Root Folder and select Add Reference


Step 2: Browse the AspJpeg.dll file from your Hard Drive and click OK to continue.


Lets have a look your added reference picture.


Lets have a look your added reference picture.

using System;
using System.IO;
using System.Web;
 
String tempPath = HttpContext.Current.Server.MapPath("uploads/temp/");
String savePath = HttpContext.Current.Server.MapPath("uploads/images/");
 
protected void btnUpload_Click(object sender, EventArgs e)
    {
        // Generate Random String
        String NewID = System.Guid.NewGuid().ToString("N").Substring(0, 10);
 
        // initialize variables
        String fileName = String.Empty;
        String fileExtension = String.Empty;
        Boolean fileOK = false;
        Boolean fileSaved = false;
 
        // Check: If file has been selected to upload
        if (FileUpload1.HasFile)
        {
            Session.Add("WorkingImage", FileUpload1.FileName);
            fileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
            String[] allowedExtensions = { ".jpg", "jpeg", ".png", ".gif" };
            for (int i = 0; i < allowedExtensions.Length; i++)
                if (fileExtension == allowedExtensions[i]) fileOK = true;
        }
 
        // Check: If fileOK variable is equest to true
        if (fileOK)
        {
            try
            {
                fileName = NewID + fileExtension;
                String tempLocation = tempPath + fileName;
                FileUpload1.PostedFile.SaveAs(tempLocation);
 
                ASPJPEGLib.IASPJpeg objJpeg = new ASPJPEGLib.ASPJpeg();
                objJpeg.Open(tempLocation);
                objJpeg.PreserveAspectRatio = 1;
 
                const int maxWidth = 300;
                if (objJpeg.OriginalWidth > objJpeg.OriginalHeight)
                {
                    objJpeg.Width = maxWidth;
                    objJpeg.Height = objJpeg.OriginalHeight * maxWidth / objJpeg.OriginalWidth;
                }
                else
                {
                    objJpeg.Height = maxWidth;
                    objJpeg.Width = objJpeg.OriginalWidth * maxWidth / objJpeg.OriginalHeight;
                }
 
                // Send generated image Width and Height to JavaScript for the Jcrop preview
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "getImageDimensions", "getImageDimensions(" + objJpeg.Width + "," + objJpeg.Height + ");", true);
 
                // Create new file with new width: 300
                objJpeg.Save(tempLocation);
 
                // Save Temprary Location and Filename into Session
                Session["TempLocation"] = tempLocation;
                Session["TempFileName"] = fileName;
                fileSaved = true;
            }
            catch (Exception ex)
            {
                lblError.Text = "File could not be uploaded." + ex.Message.ToString();
                lblError.Visible = true;
                fileSaved = false;
            }
        }
        else
        {
            lblError.Text = "Cannot accept files of this type.";
            lblError.Visible = true;
        }
 
        // Check: if fileSaved variable is equest to true
        if (fileSaved)
        {
            step1.Visible = false; // Panel #1: Disappear
            step2.Visible = true; // Panel #2: Appear
 
            // Fill the Origial Image and Preview with the below source
            imgCrop.ImageUrl = "~/uploads/temp/" + fileName;
            preview.ImageUrl = "~/uploads/temp/" + fileName;
        }
 
    }
 
    protected void btnCrop_Click(object sender, EventArgs e)
    {
        String newFileName = savePath + Session["TempFileName"];
 
        // Create instance for AspJpeg
        ASPJPEGLib.IASPJpeg objJpeg1 = new ASPJPEGLib.ASPJpeg();
 
        // Open file from temprary location
        objJpeg1.Open(Session["TempLocation"].ToString());
 
        // Set Quality: 80
        objJpeg1.Quality = 80;
 
        // Image Cropped with selected area
        objJpeg1.Crop(int.Parse(X1.Value), int.Parse(Y1.Value), int.Parse(X2.Value), int.Parse(Y2.Value));
 
        // Save file into uploads/images
        objJpeg1.Save(newFileName);
 
        step2.Visible = false; // Panel #2: Disappear
        pnlCropped.Visible = true; // Active Panel Cropped Image
 
        imgCropped.ImageUrl = "~/uploads/images/" + Session["TempFileName"];
 
        // Delete temprary file
        CancelCrop();
    }
 
    protected void lbBackToUpload_Click(object sender, EventArgs e)
    {
        CancelCrop();
 
        step1.Visible = true; // Panel appear #1
        step2.Visible = false; // Panel disappear #2
    }
 
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        CancelCrop();
 
        step1.Visible = true; // Panel appear #1
        step2.Visible = false; // Panel disappear #2
    }
 
    private void CancelCrop()
    {
        String tmpFileLocation = Session["TempLocation"].ToString();
 
        // Delete temprary files if exists
        if (File.Exists(tmpFileLocation))
            File.Delete(tmpFileLocation);
    }

Lastly, we've got finished the Jcrop Picture Cropping script. You'll be able to make use of your own FileUpload method for image uploading. I'm also impressed by a person who experienced developed great structural code. therefore, I followed him. Sorry to forgot reference website link.



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