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 Hosting - ASPHostPortal.com :: Creating Default User Roles in ASP.NET MVC

clock February 28, 2017 05:00 by author Armend

ASP.NET MVC 5 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more.


In this article, We'll look into how to create default user roles in ASP.NET MVC 5. Let's begin by establishing where the user role is assigned, and that is the registration stage. In the default template, you have the AccountController that contains a Register action. The default implementation looks like this:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
            WebSecurity.Login(model.UserName, model.Password);
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}


What's missing here is the role assignment, so let's add that. Right after the CreateUserAndAccount call, we can check whether a specific role exists, and if it is - add the registered user to it. In case the role is new, create it.

if (!Roles.RoleExists("Standard"))
    Roles.CreateRole("Standard");
Roles.AddUserToRole(model.UserName, "Standard");


Here I am working with a role called Standard, but obviously you can use another identifier for it. If you open the database that is carrying the app data, you will notice that there are two new tables introduced in the existing context - Roles and UsersInRoles.

As the data skeleton is established, you can now limit content access based on roles. In views, you could use the Authorize attribute:

[Authorize(Roles = "Admin")]

Or you could check for the role directly:


@if (Roles.GetRolesForUser().Contains("Admin"))
{
}

That's the tutorial How to create Default User Roles in ASP.NET MVC 5, for more information about ASP.NET MVC 5 Hosting please feel free to visit ASPHostPortal.com.

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 Hosting - ASPHostPortal.com :: 7 Tips for Developing a Secure ASP.NET Web Application

clock December 13, 2016 04:52 by author Armend

7 Tips for Developing a Secure ASP.NET Web Application

As the usage of the internet and the number of web applications over the internet have gone exponentially high there are bad people who continuously work around the clock to hack them. It may be for personal gain or just as an amateur act. Despite the intention of the bad guy the damage caused to the organization hosting the site or its users should be taken into account. As a professional web application developer it is a must to be aware of the best practices to follow in order to make the application more secure. In this article I will be listing and explaining my top 7 tips for developing a secure asp.net application.

Don’t Let Your Users be Victims of Click Jacking

Have you ever thought about someone framing your website onto theirs, making your users to be the victims of click jacking? Yes, the attackers can load your website onto their site in an iframe. They can then skillfully place their transparent controls over your website and fetch the PII information, user credentials, make them perform an unwanted task like exposing their financial information, etc.
In order to prevent that you will have to use a frame busting technique. The following script will not allow your website to be iframed. This can be placed in your master pages.

  •     <script type="text/javascript" language="javascript">
  •         //Check if the top location is same as the current location
  •         if (top.location.hostname != self.location.hostname) {
  •             //If not then set the top to you current
  •             top.location.href = self.location.href;
  •         }
  •     </script>
  • In addition to the above script don’t forget to add the following header, which informs the browser to DENY framing of this website. This is supported in all major browsers except IE versions less than 8.
    The header should be added in the global.asax application start event.

    1. protected void Application_Start(object sender, EventArgs e)
    2. {
    3.             HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
    4. }
    5.  

     

    In addition to the above script don’t forget to add the following header, which informs the browser to DENY framing of this website. This is supported in all major browsers except IE versions less than 8.
    The header should be added in the global.asax application start event.

    1. protected void Application_Start(object sender, EventArgs e)
    2. {
    3.             HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
    4. }
    5.  

     

    White List the Request URL

    Though we have many techniques to perform the security preventions inside the application it is most important to prevent the bad data from being entered into your website at the first place. Most attacks happen through the query string values passed through the URL. It is a best security practice to define a common place like an HttpModule to white list the URL, i.e. sanitize the entire URL with a set of white listed characters and drop all the bad ones. It means you will not encourage any other characters apart from a white listed set defined in your application.
    It is important for you to know that black listing is not a foolproof mechanism and it can be broken by the hackers easily.

    Practice of Encoding the Data

    While processing and sending, the data in the response that is fetched from outside the trust boundary should always be encoded. The type of encoding may differ based on the usage of the non-trusted data. For example perform an HtmlEncode for the data that is sent to the client page.

    Label1.Text = Server.HtmlEncode(Request.QueryString["BadValue"]);

     

    Encoding the data will make the XSS scripts inactive and prevent them from being executed. Microsoft has provided the AntiXss library, which provides more sophisticated encoding methods including the JavascriptEncode.

    Using Cookies

    As a web developer you should take utmost care while using cookies, which may open a back door for the hackers to get into your applications. Following are the best practices while using a cookie to store information.
    1. Is your website is hosted under SSL? Then be sure to mark your cookies as secure. This will make them available only in the SSL transmissions.

    1. HttpCookie cookie = new HttpCookie("MySecureCookie");
    2. cookie.Value = "This is a PII information";
    3. cookie.Secure = true;

     

    If your website is not SSL enabled then always encrypt the values using a strong encryption mechanism like AES 256 and then store them in the cookies.

    Secure the Service Calls (WCF / Web Service)

    Are you exposing WCF services through basicHttpBinding? Then think again because the messages transmitted over will be plain text and any intruder will be able to trap the requests and even simulate them easily. Use wsHttpBinding, which will transport the messages in an encrypted format, which makes the life of the intruder hard.
    Though you make lots of protections for your WCF or web services it is a best practice to host the services under an SSL layer.
    Never Deploy the Application with debug=”true”
    It is strongly recommended not to deploy your applications in the production environment with compilation debug=”true” in your web.config. This will result in a big nightmare for performance and security of the application.
    This may leak too much information for the attackers, for example the stack trace in the event of an unhandled exception and the debug trace information. Such exposure of the internals will be good bucks for the attackers.

  • <system.web>
  •         <compilation debug="false" targetFramework="4.0" />
  •     </system.web>
  • Thinking About Turning Off ViewStateMAC?

    Turning off ViewStateMAC will create a security loophole in your asp.net application if you are using Viewstate on your web pages. The intruders will easily be able to intercept, read the 64 bit encoded values and modify them to do some bad things to your website. Having it turned on ensures that the viewstate values are not only encoded but also a cryptographic hash is performed using a secret key.

    1. <pages enableViewStateMac="true"></pages>

     

    I hope this article is useful for the developers who thrive at making their asp.net application an absolutely impossible place for the hackers to deal with.

    Happy reading!

    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 Hosting - ASPHostPortal.com :: Dependency Injection In ASP.NET Core

    clock June 28, 2016 20:19 by author Armend

    This article explains the dependency injection feature available out of the box in ASP.NET core (ASP.NET 5). It will also cover some of the basics of dependency injection so that everyone can get the most out this article.

    What is dependency Injection

    Dependency Injection is the process of “injecting” the “dependency” whenever the dependency is requested by a client, where the dependency may be another service which the client (requester) may have no means of knowing how to create.

    As an analogy, imagine a person (client) going to office carrying his lunch cooked by himself. In this scenario, the person has a “dependency” on food. But he had to know how to cook his food. But honestly, not everyone (client) knows to cook, but people do need food (dependency). This is where restaurants play the role of dependency Injection. They can supply food (“inject dependency”) to the people (client) without the person (client) needing to know how to cook.

    This is also called as Inversion of control. Since the control for creation of the service has been passed from the requester to another entity which takes care of creating the dependencies needed by a class to perform its tasks. The entity which takes care of creating these requested dependencies and injecting them automatically to the client is known as the DI (dependency Injection) container.

    Dependency Injection in ASP.NET Core

    Ok, enough said about what dependency injection is. I am sure most of you knew it. If not, this is a great feature to know and a great tool to add to your tool belt! Let us now look at how to implement dependency injection out of the box in ASP.NET core.
    ASP.NET core applications can leverage built in framework support for implementing dependency injection. It has support for the following types of lifetimes for configured services (injected dependencies).

    •     Transient – A new instance of the service is created each time it is requested. It can be used for stateless and light weight services.
    •     Scoped – A single instance is created once per request.
    •     Singleton – Created only once the first time they are requested.

    Now for some code!

    Use case

    Implement a UniqueKeyProvider service. For demonstrating the lifetimes, we will create three differently named interfaces (one for each type of lifetime) for UniqueKeyprovider, all inheriting from the same parent interface having a single property, UniqueKey.
    Also, to further illustrate the scoped and singleton lifetime, we will create another service, SomeService, which will have a dependency on all the three different UniqueKeyProvider services (the three different lifetime services).

    1. Service Interface definition

    Please note the three differently named interfaces, one for demonstrating each type of lifetime. 

    namespace DependencyInjectionASPNetCore.Services 
        { 
            public interface IUniqueKeyProvider 
            { 
                Guid UniqueKey 
                { 
                    get; 
                    set; 
                } 
            } 
            public interface ITransientUniqueKeyProvider: IUniqueKeyProvider 
            {} 
            public interface IScopedUniqueKeyProvider: IUniqueKeyProvider 
            {} 
            public interface ISingletonUniqueKeyProvider: IUniqueKeyProvider 
            {} 
        } 

    2. Service Class definition

        namespace DependencyInjectionASPNetCore.Services 
        { 
            public class UniqueKeyProvider: ITransientUniqueKeyProvider, 
            ISingletonUniqueKeyProvider, 
            IScopedUniqueKeyProvider 
            { 
                public Guid UniqueKey 
                { 
                    get; 
                    set; 
                } 
                public UniqueKeyProvider(Guid uniqueKey) 
                { 
                    UniqueKey = uniqueKey; 
                } 
            } 
        } 

    3. Registering the services in the startup.cs

    Now register your services in the startup.cs file. This is the step where you are actually configuring your dependency injection container. You are basically instructing your dependency injection container that if the user requests for the service, ITransientUniqueKeyProvider, then please provide with a transient scoped instance of UniqueKeyProviderclass and similarly for the other services.
    You need to register your services in the ConfigureServices method in the startup.cs file. Please refer to the code below for registration,

       

        services.AddTransient<ITransientUniqueKeyProvider>(provider =>newUniqueKeyProvider(Guid.NewGuid())); 
        services.AddScoped<IScopedUniqueKeyProvider>(provider =>newUniqueKeyProvider(Guid.NewGuid())); 
        services.AddSingleton<ISingletonUniqueKeyProvider>(provider =>newUniqueKeyProvider(Guid.NewGuid())); 
        services.AddTransient<ISomeService, SomeService>();
     

    Note that I am also registering another service, ISomeServicewhich I am just using for demo purposes for showing the nature of transient and singleton lifetime. Also note that SomeService implementation requires dependency on the three Unique Key providers, which will be injected through dependency injection.Implementation of ISomeservice provided below,

    4. IsomeService and Someservice Implementation

        public class ISomeService 
        { 
            ITransientUniqueKeyProvider TransientUniquekeyProvider 
            { 
                get; 
                set; 
            } 
            IScopedUniqueKeyProvider ScopedUniquekeyProvider 
            { 
                get; 
                set; 
            } 
            ISingletonUniqueKeyProvider SingletonUniquekeyProvider 
            { 
                get; 
                set; 
            } 
        } 
        public class SomeService: ISomeService 
        { 
            public ITransientUniqueKeyProvider TransientUniquekeyProvider 
            { 
                get; 
                set; 
            } 
            public IScopedUniqueKeyProvider ScopedUniquekeyProvider 
            { 
                get; 
                set; 
            } 
            public ISingletonUniqueKeyProvider SingletonUniquekeyProvider 
            { 
                get; 
                set; 
            } 
            public SomeService(ITransientUniqueKeyProvider transientprovider, 
                IScopedUniqueKeyProvider scopedprovider, 
                ISingletonUniqueKeyProvider singletonprovider) 
            { 
                TransientUniquekeyProvider = transientprovider; 
                ScopedUniquekeyProvider = scopedprovider; 
                SingletonUniquekeyProvider = singletonprovider; 
            } 
        } 

    Now it is time to wrap it all up and test it through a controller. I am using the Home controller’s Index action. Please refer to the below code from the controller and view.

    5. Home Controller

        public class HomeController: Controller 
        {  
            private ITransientUniqueKeyProvider _transientUniquekeyProvider; 
            private IScopedUniqueKeyProvider _scopedUniquekeyProvider; 
            private ISingletonUniqueKeyProvider _singletonUniquekeyProvider; 
            private ISomeService _someserviceProvider; 
            public HomeController(ITransientUniqueKeyProvider transientprovider, 
                IScopedUniqueKeyProvider scopedprovider, 
                ISingletonUniqueKeyProvider singletonprovider, ISomeService someserviceprovider) 
            { 
                _transientUniquekeyProvider = transientprovider; 
                _scopedUniquekeyProvider = scopedprovider; 
                _singletonUniquekeyProvider = singletonprovider; 
                _someserviceProvider = someserviceprovider; 
            } 
            public IActionResult Index() 
            { 
                ViewBag.transientID = _transientUniquekeyProvider.UniqueKey; 
                ViewBag.scopedID = _scopedUniquekeyProvider.UniqueKey; 
                ViewBag.singletonID = _singletonUniquekeyProvider.UniqueKey; 
                ViewBag.someServiceProvider = _someserviceProvider; 
                return View(); 
            } 
        } 

    Note the constructor which takes in the dependencies. So when the request comes to this page, the framework notes that it needs an implementation for these services. It checks the DI container and finds the registration, and based on that the valid instance is passed to the constructor. The same happens in case of the ISomeService dependency which the controller’s constructor needs.

    6. Index View

    In the view file, we are just displaying the values that we set in the view bag. Results provided in the next section.

    <div style="margin-top:35px"> 
    lt;pstyle="font-weight:bold;text-decoration:underline"> 
    These are the values that were injected into the home controller 
    </p> 
    <p> 
        Transient value of Guid: @ViewBag.transientID 
    </p> 
    <p> 
        Scoped value of Guid: @ViewBag.scopedID 
    </p> 
    <p> 
        Singleton value of Guid: @ViewBag.singletonID 
    </p> 
    </div> 
     
    <div> 
        <p style="font-weight:bold;text-decoration:underline"> 
     
            These are the values that were injected into Someservice Implementation 
            </p> 
            <p> 
                Transient value of Guid: @ViewBag.someServiceProvider.TransientUniquekeyProvider.UniqueKey 
            </p> 
            <p> 
                Scoped value of Guid: @ViewBag.someServiceProvider.ScopedUniquekeyProvider.UniqueKey 
            </p> 
            <p> 
                Singleton value of Guid: @ViewBag.someServiceProvider.SingletonUniquekeyProvider.UniqueKey 
            </p> 
    </div>

    I really hope it was useful and fun. Happy coding!

     



    ASP.NET Hosting - ASPHostPortal.com :: How to Publishing an ASP.NET 5 Project to a Local IIS Server

    clock June 16, 2016 17:45 by author Armend

    In this post we will show you how to publishing an ASP.NET 5 project to a local IIS server. Recently I deployed a new ASP.NET 5 web application to a local IIS server. Though there are several online resources available about deployment, I encountered some problems that were difficult to diagnose and fix. In this post I will talk about the general deployment process and the steps I followed for a successful deployment.

    ASP.NET 5 applications are meant to be cross-platform. Included in this cross-platform effort is the development of a new, cross-platform web server, named Kestrel. The Kestrel web server can be activated from the command line and can be used on any operating system.
    Of course, ASP.NET 5 applications can still be hosted in IIS. But even in this case, the underlying web server will still be Kestrel. The role of IIS is greatly minimized.
    In this post we will be deploying a web application using Kestrel as a web host first. Afterwards, we will be deploying to IIS.

    Deployment to Kestrel

    Let's say that we have an existing ASP.NET 5 application. We can publish the application from the command line. First, navigate to the root web folder of the application (the folder where the project.json file is in). Then, type in the following command:

    dnu publish --runtime active -o ..\publish

    What this will do is create a new folder named 'publish' alongside the root web folder. Inside this 'publish' folder , there will be three subfolders: 'approot', 'logs', and 'wwwroot'. The 'approot' folder will contain the source files and packages needed by the application. The 'logs' folder will contain any logs that the application emits. The 'wwwroot' folder will contain javascript, html, css files, etc. as well as the web.config file.
    Now we can start the Kestrel web server. First, navigate to the 'approot' folder. There will be a file named web.cmd. Start it by typing 'web' from the command line or double-clicking on it from a windows explorer window.

    You might notice that a lot of text appears on the command line as soon as the command is run. This is especially true when there are Entity Framework migrations involved. Among the sea of text, the URL of the localhost web server will be displayed, and will look something like this:

    Hosting Environment: Production
    Now listening on: http://localhost:5000
    Application started. Press Ctrl+C to shut down.

    Once we find this text, we can just navigate to the appropriate URL using a browser. There we should see the web app up and running.
    Congratulations, we have just deployed our ASP.NET 5 web application!
    Deployment to IIS
    Once we successfully launch the app through Kestrel, we can go for deploying in IIS. We need to do a few things for it to work properly.

    • Use an application pool with No Managed Code as the .NET CLR Version.
    • Create a Login in SQL Server with the login name as IIS APPPOOL\{apppoolname}. This Login should have access to whatever database the web application will use.
    • Create access rights to the 'wwwroot' folder for the user group IIS_IUSRS.

    In addition, if we are going to put the application inside IIS Default Web Site and use a virtual directory, we need to modify the Startup.cs to handle this.
    The first step is to rename the Configure method to something else, for example Configure1.
    Then, we need to create a new Configure method. This would have the same signature as the original Configure method. The implementation would look something like this:

    public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.Map("/virtualdirectoryname", (app1) => this.Configure1(app1, env, loggerFactory));
    }

    So we see that this new Configure method just calls the Configure1 method, taking into account the virtual directory name.
    Once all of these are in place, we can go ahead and deploy to IIS using the usual process. We can add a new application in IIS Default Web Site and use the application pool we created earlier (using No Managed Code). The physical path should point to the 'wwwroot' location. The alias should be the same as the one we put in the Configure method in Startup.cs.
    Afterwards, just browse to the website and it should all be good!

    Conclusion

    Although the concept of deployment stayed the same, the process and tools involved for deploying ASP.NET 5 applications has changed. In this post we took a look at how to deploy to the Kestrel web server, then later to IIS. Though it might seem like a long process, most of the steps should only be performed the first time around. Subsequent deployments should be faster and more straightforward.



    ASP.NET Hosting - ASPHostPortal.com :: 9 Mistakes to be Avoided by .NET Developer

    clock June 6, 2016 23:50 by author Dan

    Admit it! We all make mistakes. None of our codes starts working at strike one. We make typos, forget signing off or, as it happens with most of us, overlook the testing phase, especially when it comes to ASP.net development. To err is human. So, making mistakes is just another human phenomenon. What counts is how you tackle your errors and how you devise ways to avoid them in the ventures to come. Here's a compilation of some of the most common testing mistakes that developers often commit while catering to outsource .Net development needs. Let's take a look.

    XSS Security Issues: The look and feel of your UI and of course, its maintenance lies in your hands. Ensure that all user-input fields are well-customized so that no JavaScript or HTML that a user enters can rummage your web page.

    Universal Localization: As a usual norm, as you begin developing a new feature, you keep all the text in hard code as there are probabilities of certain changes during the course of development. As soon as the project team approves the feature, you localize the text. However, at times you tend to forget localizations of the entire text. You remember to hard code, but when it comes to localization you tend to sign off without doing the same. Probably this checklist reminds us to localize before we sign off the next time.

    .Net Behaves Well with IE 6 and 7 and Firefox: Test leads often report of cross-browser compatibility issues that crop up from time to time. Most of these issues usually encompass small twigs like usual IE 6 issues or minor problems relating to positioning of elements. We are dedicatedly focusing on IE version 6 and 7 and Mozilla Firefox for two reasons. Firstly, if your web page works well in these three browsers, it will function well on Opera and Safari as well. Secondly, over 98% of the visitors access your site through these browsers.

    Reuse Code as and when required: This law is applicable across all programming platforms and ASP.Net is no exception. Separate server and user-control elements enable specialization of code so that it can be used at other places as well.

    Commenting on the Code: There are no two-ways to this. Always document your code well and comment upon the right places, so that it is easier for other developers to pick up from where you left.

    Extended Text doesn't Mean Broken Design: As a matter of fact, names usually don't extend beyond 50 characters, but what if some user inputs a name containing 300 or even more characters. Obviously, in that case the UI will be disrupted. In this case you have two options- either codes your interface to accept long text inputs or put a limit on the length of text users can input.

    Write Units When Possible: Unit testing for your website can be a tedious job especially if you are not using ASP.Net MVC framework for the same. However, pulling the code-behind logic into different components that can be placed in the library can enable you to test the units. Instead of dealing with HttpHandlers using .ashx files, placing them in separate libraries is a good option.

    Peer Verification before Testing: Before signing off any newly added feature and sending it across to the test team, you usually pass it through peer verification. As the name suggests, in peer verification, one of your colleagues tests the application feature you have just developed and tries to find flaws in it. This allows you to identify errors easily and also simplifies the process for the testing team. When schedules are really tight, we often forget to ask for peer verification and it definitely shows at the end.

    Expected functioning of Enter-key: When you are using webforms in ASP.Net, the enter-key often starts functioning weirdly. In this case, you can either set default buttons on the Panel webcontrol or from code-behind.

    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 hosting -ASPHostPortal.com :: Top 10 Tips You Shall Know on Choosing ASP.NET Hosting

    clock April 22, 2016 20:34 by author Armend

    Top 10 Tips You Shall Know on Choosing ASP.NET Hosting

    Being devoted into ASP.NET development and ASP.NET website hosting for a couple of years, we know the secrets hidden in the ASP.NET hosting advertisement and how difficult to find a trusted and cost effective ASP.NET hosting provider. Thus, we would like to show you the top 10 tips on choosing ASP.NET hosting providers before starting with our topic.

    1. MS SQL Server database edition and limitation. The latest version of MSSQL 2012 are preferred.
    2. .NET Framework versions. Does it support the version used for your website?
    3. ASP.NET MVC versions. Does it support the version used for your website if you’re using ASP.NET MVC technology?
    4. Does it provide the dedicated application pool so that you won’t be affected by your neighbors?
    5. How long the IIS is set to recycle your website – usually 30 minutes at least is required.
    6. What’s the maximum dedicated memory allowed for the ASP.NET websites?
    7. The hosting provider needs to have the rich experiences and knowledge of how to ensure the high-quality ASP.NET hosting. Besides, it is great that they have got plenty of positive feedbacks from real customers and have been trusted and recommended by a lot of authorities, communities and hosting review sites.
    8. The ASP.NET hosting needs to ensure a high level of hosting reliability with at least 99.9% uptime. Note that this can be achieved with the utilization of cutting-edge data centers, solid server machines and no overselling practice. In addition, some confident web hosts even claim to give you some compensations if they fail to meet their promised uptime track record.
    9. The hosting speed is also pretty essential. After all, your readers can be frustrating if they find it takes a long time for accessing your website. In this case, you need to figure out that whether your web host can ensure the peak performance with no more than 3 seconds for page loading and 400 ms for the server response.
    10. The web host needs to ensure the all-time-rounded technical support to assist you 24 hours a day and 7 days a week. Also, their support staffs need to have the rich knowledge about ASP.NET hosting and related applications.

    General Knowledge about ASP.NET

    ASP.NET is the server-side online application framework coming with the open source nature. It is designed with the purpose of web development and dynamic webpages production mainly. In addition, developed by Microsoft, ASP.NET has been used by a lot of programmers for the creation of complicated websites, online applications and add-on services.
    In fact, ASP.NET has been released since January 2002, which is the successor to the Active Server Pages technology of Microsoft. As it is built based on the Common Language Runtime, developers and programmers can write the ASP.NET code with the help of .NET language.

     



    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 Hosting - ASPHostPortal.com :: Easy Steps to Make 2 DateTime objects difference in milliseconds

    clock September 11, 2015 06:43 by author Dan

    DateTime difference in Milliseconds

    The following asp.net c# example source code demonstrate us how can we get difference in milliseconds between two datetime objects. in this source code, we created a datetime type variable by DateTime.Now property that holds a value that represent the current system date and time. now we initialize a new datatime variable with a value that is two minutes greater than previous datetime variable.

    after initializing two datetime variables, we create a timespan object by subtract two datetime object. at last we convert the timespan object into milliseconds. the converted milliseconds is the difference between two datetime objects.

    DateTime.Now property gets a datetime object that represent current date and time on web server. DateTime.Subtract() method subtract two datetime objects and return a timespan object. TimeSpan represents a time interval.

    datetime-difference-in-milliseconds.aspx

    <%@ Page Language="C#" AutoEventWireup="true"%>
       
    <!DOCTYPE html>     
    <script runat="server">
        protected void Button1_Click(object sender, System.EventArgs e)
        {
            //initialize a datetime variable with current datetime
            DateTime now = DateTime.Now;

            Label1.Text = "now : " + now.ToString();

            //add 2 minutes to current time
            DateTime dateAfter2Minutes = now.AddMinutes(2);

            TimeSpan ts = dateAfter2Minutes - now;
            //total milliseconds difference between two datetime object
            int milliseconds = (int)ts.TotalMilliseconds;
          
            Label1.Text += "<br ><br />after two minutes: ";
            Label1.Text += dateAfter2Minutes.ToString();

            Label1.Text += "<br ><br />smillieconds difference between to datetime object : ";
            Label1.Text += milliseconds;
        }
    </script>     
         
    <html xmlns="http://www.w3.org/1999/xhtml">     
    <head id="Head1" runat="server">     
        <title>c# example - datetime difference in milliseconds</title>     
    </head>     
    <body>     
        <form id="form1" runat="server">     
        <div>     
            <h2 style="color:MidnightBlue; font-style:italic;">     
                c# example - datetime difference in milliseconds
            </h2>     
            <hr width="550" align="left" color="Gainsboro" />     
            <asp:Label      
                ID="Label1"      
                runat="server"     
                Font-Size="Large"   
                Font-Names="Comic Sans MS"
                >     
            </asp:Label>     
            <br /><br />   
            <asp:Button      
                ID="Button1"      
                runat="server"      
                Text="get milliseconds difference between two datetime"     
                OnClick="Button1_Click"   
                Height="40"     
                Font-Bold="true"     
                />     
        </div>     
        </form>     
    </body>     
    </html>

    the above image describe this example code better. this output screenshot display that at first line we created a DateTime variable. second line we created another datetime object by adding two minutes with first datetime object. final line shows the difference of two datetime objects in milliseconds. one second equal to one thousand milliseconds.

    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.  



    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