European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 5 Hosting - HostForLIFE.eu :: Root Of ASP.NET 5

clock April 8, 2016 19:00 by author Anthony

Today we will discuss about the root of ASP.NET 5, which is WWWroot. When you take a closer look at the ASP.NET 5 project, you will see that there are many things which are carry forwarded like Model, View, Controller, clean separation of concerns and may more.

But, there are also some significant changes around ASP.NET 5. Now, the root of the website is no longer the root of the project. By default, root will be WWWroot folder. The idea behind this to maintain the clean separation between the files at the web-server retrieved and sent to the client and the files which contains the logic and configuration. Static files like JS, CSS, HTMLs can live in WWWroot folder.

15th

Now, lets suppose when i run the app and tried to see the image which i have placed in My Imgaes folder, then it will give me 404 error. On the other hand, if i go ahead and add the same folder in WWWroot folder and try to navigate the same then it will produce me the result.

18th

so, the point is all static files are served by root folder and logical stuffs served by project space as we initially saw, when i added controller in the controller’s folder and it took effect. One more thing you might have observed that there is no web.config file now in the solution. Also now there is no Global.asax file; however the same is replaced by startup.cs file. But, we’ll see this later. 1st let’s see project.json file. This file now manages many aspects of website.

19th

First thing which you will notice here that root folder is set to WWWroot here. So, this is the place which is telling website that this is the root folder. So begin the show from here. This you can change as well or rename if you like to. Now, this configuration file is in JSON format. This is also telling the ASP.NET runtime what dependencies project is going to need. In this new ASP.NET 5 system there is a new way to manage dependencies. No need to reference assemblies and store the lists of referenced assemblies in the project file. Instead we refer to nuget packages as dependencies and these dependencies are listed in our project.json file. Now, there are couple of reasons for this change. One reason is to simplify the dependency management. Another good reason for this is that ASP.NET is moving away from VS dependency. So, in future i can use any text editor to build the ASP.NET App.

Now, these dependencies can be both the ways. One way which we used already shown below in the screen shot.

20th

21th

Now, the UI of this also changed. Initially we used to have Modal window. Now, this is more like complete screen giving wider visibility. I can also see the installed templates like

22nd

Also, i still have the flexibility of different nuget source. 2nd Option is via project.json file. Let’s suppose i am planning to install some custom package. Then i can do like shown below as well

24th

However, whatever package you install; you can find its references under “References“. Below, in the screen shot you can see that there are two versions of runtime here. 1st one is the core version and 2nd one is the cloud optimized version.

25th

Let’s collapse the same and drill into it. Now, here dependency management system will keep your assemblies in nice tree structure. So, it nicely tells which package are dependent on which package.

27th

Now, as far as Framework and runtime is concerned as you can see below in the screen shot; i have both frameworks listed here.

28th

So, whenever i am building the solution i am building against both of these frameworks. By building against both i am actually ensuring that it will work well against both the frameworks. This also means whenever i am switching platform my code won’t break there.

But, let’s go ahead and break something here. You remember in the last segment i created one new controller with a notepad. Now, let’s modify the same and refresh the app.

29th

As you can see that it says that GetCallingAssembly() which is part of System.Reflection is not supported in the cloud optimized version. But, let’s suppose i overlooked this error and refresh the app.So, it actually produced me desired result.

31th

But, when i explicitly build the project and checked the output window, then it gave me below error message.

32nd

So, building with error but application is working fine with full blown CLR. Now, if you have decided that you don’t want CORE CLR version. so, you can just comment the Core CLR section in the project.json file as shown below in the screen shot.

33th

As soon as i commented the above section, below references got refreshed automatically.

34th

Now, when i build the app then it will build fine. But, suppose you want the other way means you would like to keep the cloud optimized version also and build should also succeed. For this scenario i need to refer the conditional build as shown below.

36th

 

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How To Prevent XSS Attacks in ASP.NET?

clock April 6, 2016 19:17 by author Anthony

In this article, I will explain about how to prevent XSS Attacks. XSS (Cross-Site Scripting) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. For sites that allow user input to be displayed in the browser, cross site scripting (XSS) attacks are a possibility that must be protected against.  These attacks are carried out by placing <script> tags pointing to malicious code in the public facing elements, which can be persisted elements such as comments or reviews, or more ephimeral examples such as query variables in the url.  The aim of these attacks varies, but some examples are stealing sensitive information (login credentials, personal data), forcing redirects, or just about anything else that can be accomplished with JavaScript.  These attackes can be prevented by encoding input. So instead of the literal string <script>bad script code</script>, it becomes &lt;script&gt;bad script code&lt;/script&gt;, and instead of running the code, it will simply display the text content of the script.

According to Microsoft, the primary purpose of the HttpUtility.HtmlEncode method is to ensure that ASP.NET output does not break HTML; it's purpose is not necessarily security.  However, the AntiXssEncoder class is primarily designed for security.  To this end, it uses a white-list approach rather than a black-list, only allowing known safe characters to remain unencoded.  The AntiXss method is slightly less performant, and will work in multiple languages.

It is possible to set the AntiXssEncoder as the default for your application, and this has gotten steadily easier.  Phil Haack wrote in 2010 about doing this using a the HttpEncoder abstract base class, and Jon Galloway wrote in 2011 about doing it with version 4.1 which already included an encoder, so it required little more than adding the assembly to the project and changing the web.config file.  Since AntiXss can now be had in NuGet, it's as simple as installing it and setting the httpRuntime encoderType property:

 <system.web>
    <httpRuntime targetFramework="4.5"
             encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary"/>
  </system.web>


HostForLIFE.eu ASP.NET 4.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET 5 Hosting - HostForLIFE.eu :: How to Use Entity Framework 7 To Persist Movie Data To a Database?

clock April 4, 2016 19:50 by author Anthony

Today I will explain about how to use entity framework 7 to presist movie data to a database. But before you start, you must add Entity Framework 7 NuGet packages to your project. Also make sure that your project.json file includes the following two dependencies (you’ll get Intellisense while entering the names of the packages and their versions).

"EntityFramework.SqlServer": "7.0.0-beta2",
"EntityFramework.Commands": "7.0.0-beta2",

 

After you complete this step, the Entity Framework packages should appear under References.

Creating the Model and DbContext

Next, we need to create our Movie model class. This class represents the entity that we want to store in the database. Add the following Movie.cs class to your Models folder:

namespace MovieAngularJSApp.Models
{
    public class Movie
    {
        public int Id { get; set; }
 
        public string Title { get; set; }
 
        public string Director { get; set; }
    }
}

We also need to create an Entity Framework DbContext class. We create this class when using Entity Framework 7 in exactly the same way as we created this class for previous versions of the Entity Framework.

using Microsoft.Data.Entity;
namespace MovieAngularJSApp.Models
{
    public class MoviesAppContext:DbContext
    {
 
        public DbSet<Movie> Movies { get; set; }
 
    }
}

Registering the Entity Framework Services
Now that we have our DbContext class, we need to register the DbContext with our application services. Modify your Startup.cs file so it contains the code for registering the Entity Framework in the code below:

using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Data.Entity;
using MovieAngularJSApp.Models;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
namespace MovieAngularJSApp
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            // Setup configuration sources.
            Configuration = new Configuration()
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();
        }
         public IConfiguration Configuration { get; set; }
         public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
 
            // Register Entity Framework
            services.AddEntityFramework(Configuration)
                .AddSqlServer()
                .AddDbContext<MoviesAppContext>();
        }
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
 
    }
}

The database connection string is loaded up from the Config.json file (notice the constructor in the Startup.cs file). Here is what the Config.json file looks like:

{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=MoviesDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    },
    "EntityFramework": {
        "MoviesAppContext": {
            "ConnectionStringKey": "Data:DefaultConnection:ConnectionString"
        }
    }
}

Updating the MoviesController

Because we registered our MoviesAppContext class as a service, we can take advantage of the built-in ASP.NET 5 Dependency Injection framework to use the MoviesAppContext in our MoviesController. Notice that the MoviesAppContext class is added to the MoviesController using constructor dependency injection in the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using MovieAngularJSApp.Models;
namespace MovieAngularJSApp.API.Controllers
{
    [Route("api/[controller]")]
    public class MoviesController : Controller
    {
        private readonly MoviesAppContext _dbContext;
 
        public MoviesController(MoviesAppContext dbContext)
        {
            _dbContext = dbContext;
        }
 
        [HttpGet]
        public IEnumerable<Movie> Get()
        {
            return _dbContext.Movies;
        }
        [HttpGet("{id:int}")]
        public IActionResult Get(int id)
        {
            var movie = _dbContext.Movies.FirstOrDefault(m => m.Id == id);
            if (movie == null) {
                return new HttpNotFoundResult();
            } else {
                return new ObjectResult(movie);
            }
        }
        [HttpPost]
        public IActionResult Post([FromBody]Movie movie)
        {
            if (movie.Id == 0)
            {
                _dbContext.Movies.Add(movie);
                _dbContext.SaveChanges();
                return new ObjectResult(movie);
            }
            else
            {
                var original = _dbContext.Movies.FirstOrDefault(m => m.Id == movie.Id);
                original.Title = movie.Title;
                original.Director = movie.Director;
                _dbContext.SaveChanges();
                return new ObjectResult(original);
            }
        }
        [HttpDelete("{id:int}")]
        public IActionResult Delete(int id)
        {
            var movie = _dbContext.Movies.FirstOrDefault(m => m.Id == id);
            _dbContext.Movies.Remove(movie);
            _dbContext.SaveChanges();
            return new HttpStatusCodeResult(200);
        }
 
 
    }
}

Performing Database Migrations

After we complete all of the steps above, our application still won’t work. If we run the Movies app then we will get an error message about not being able to open the MoviesDatabase.

The Entity Framework 7 does not support database initializers. Instead, you are encouraged to use Database Migrations.There are two ways to use Migrations with ASP.NET 5: from a Command Prompt or from the NuGet Package Manager Console. I used the Command Prompt approach and I executed the following two commands from the same directory that contains my project.json file:

k ef migration add initial
k ef migration apply

KPrompt

After you execute the two ef commands above, a new database named MoviesDatabase will be created. You can see the new database by opening up the Visual Studio SQL Server Object Explorer:

SQLExplorer

Executing the ef commands above will also add a new Migrations folder to your project.

Migrations

You now should be able to run the Movies app successfully.

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How to Create a Database With Data Source Control in ASP.NET

clock March 29, 2016 21:10 by author Anthony

In this post we are going to talk about techniques for displaying data contained in the SQL Server database with ASP.NET. There are at least three ways commonly used to perform the data binding to server conrol in ASP.NET 4.5

Here are three ways:

  • Data Source Control (Declarative)
  • Code by Hand
  • Model Binding

but in this time I will explain how to create a database with the Data Source Control in ASP.NET 4.5


Web Config

Before going into the main discussion helps me informed beforehand that the connection string that is used to communicate with the database in ASP.NET contained in the configuration file "web.config". Here are the contents

file: Web.config


<?xml version="1.0"?>
<configuration>

<connectionStrings>
<add name="learn_webConnectionString" connectionString="Data Source=SOFT-ENGINEER;Initial Catalog=learning_web;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>


Database Design

The database used in this post only use one of the table is very simple with the name "Category"

Data Source Control

Data Source Control in ASP.NET 4.5 used as a link between the database with controls for displaying data. Using this approach means that we do is get the data in a declarative rather than programmatic. To be more explicit, the following is a sample code

file: default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TryingWebForm.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Data Source Control</title>

</head>
<body>

<form id="form1" runat="server">

<div>

<p>The Declarative Way</p>

<asp:SqlDataSource ID="sdsCategory" runat="server" ConnectionString="<%$ ConnectionStrings:trying_webConnectionString %>"

SelectCommand="SELECT [id], [name_category] FROM [Category]"/>

<asp:GridView ID="gvCategoryDeclarative" runat="server" DataSourceID="sdsCategory" />

</div>

</form>

</body>

</html>

As seen in the above code, control "SqlDataSource" requires a connection string and a query command to be executed. In magic this control will connect to the database and execute commands query and the result was thrown into "GridView" by filling property "DataSourceID" with the Id of control SqlDataSource concerned. The image below is the result

 

HostForLIFE.eu ASP.NET 4.5 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in