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 :: Using Microsoft Enterprise Library in ASP.NET

clock February 21, 2017 05:45 by author Armend

In this tutorial we will show you how to using Microsoft Enterprise Library is a collection of reusable software components used for  logging, validation, data access, exception handling etc.

Here I am describing how to use Microsoft Enterprise Library for data access.

Step 1: First download the project from
http://entlib.codeplex.com/ URL.
Step 2: Now extract the project to get

Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.ObjectBuilder.dll


And give reference in the Bin directory by Right click on Bin -> Add Reference -> then give the path of these 4 dlls. Then

Step 3: Modification in the web.config for Connection String.

<add name="ASPHostPortalConnection" providerName="System.Data.SqlClient" connectionString="DataSource=ASPHostPortalSQLEXPRESS;Initial Catalog=ASPHostPortal;User ID=sa;Password=admintest;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100"/>


Give the connection string as above where Datasource is your data source name, Initial Catalog is your database name and User ID and Password as in your sql server.

Step 4:

Now it is time to write the code.

Write the below 2 lines in the using block.

using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

Here I am writting some examples how to work on:

public DataTable Read()
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetStoredProcCommand("[Topics_Return]");
            DataSet dataSet = db.ExecuteDataSet(dbCommand);
            return dataSet.Tables[0];
        }
        catch
        {
            return null;
        }
    }


The above code is a sample that will return a dataset. Here Fewlines4bijuConnection is the connection name and Topics_Return is the stored procedure name that is nothing but a Select statement.
But if the stored procedure is taking parameter then the code will be like:

 public int Save()
    {
        Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
        DbCommand dbCommand = db.GetStoredProcCommand("Topics_Save");

        db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");
        db.AddInParameter(dbCommand, "@Description", DbType.AnsiString, "Here is the Descriptiont");      
        db.AddInParameter(dbCommand, "@PostedBy", DbType.Int32, 4);       
        db.AddOutParameter(dbCommand, "@Status", DbType.AnsiString, 255);
        try
        {
            db.ExecuteNonQuery(dbCommand);
            return Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));
        }
        catch
        {
            return 0;
        }
    }

As the code explained above ASPHostPortalConnection is the connection name and Topics_Save is the stored procedure name that is taking 3 (Subject,Description,PostedBy) input parameters and 1(Status) output parameter.

You may give values from textbox, I am here provideing sample values like  "Here is the subject", "Here is the Descriptiont" or you may give the UserID from session, I am here giving 4. The output parameter will give you a string as defined and the code to get the value is

int returnValue=Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));

you can pass input parameter as below

db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");

DbType.AnsiString since Subject is of string time, you can select different values like AnsiString, DateTime from the Enum as be the parameter type.

The above code describes if you are using any stored procedure.
Below is an example that shows how to use inline SQL statements.

public DataSet GetID(string title)
    {
       DataSet ds=new DataSet();

        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetSqlStringCommand("Select * FROM Topics where UserID=1 and
IsDeleted=0");          
            ds= db.ExecuteDataSet(dbCommand);
           return ds;         
        }
        catch
        {
            return ds;
        }
         return ds;
    }


Happy coding!!

 

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 Core - ASPHostPortal.com :: Centralized ASP.NET Core Logging in One Line of Code

clock February 14, 2017 05:32 by author Armend

Centralized ASP.NET Core Logging in One Line of Code

ASP.NET Core comes with some great built-in logging. Framework components such as Routing, MVC and EntityFramework have been updated to support structured logging throughout - for example, when MVC selects a controller and action it includes ActionName in a log event so that later, you can drill down easily to requests hitting a specific action. The framework also adds convenient properties like RequestId to log events by default, making it trivial to zoom in on just the events raised during handling of a particular HTTP request. Setting up truly great application logging in an ASP.NET app has never been easier.

Seq has had first-class support for ASP.NET Core apps through Serilog since the early beta releases.
Just recently, we've taken this a step further. On File > New Project precious time spent configuring libraries can really add up. We want Seq to be so simple to include that there's no reason to put it off until later. That's why we've created a new package, Seq.Extensions.Logging, that gets centralized logging configuration down to just one line of code.

Seq.Extensions.Logging

Here's all it takes to get a new ASP.NET Core app hooked up to Seq. First, add the package:

"dependencies": {
  "Seq.Extensions.Logging": "1.0.1"
}

Then in your Startup class's Configure() method, call AddSeq():

public void Configure(IApplicationBuilder app, 
                      IHostingEnvironment env,
                      ILoggerFactory loggerFactory)
{
    loggerFactory.AddSeq("http://localhost:5341");

The AddSeq() method supports a few more parameters including the logging level and API key if one is needed. It can also pull configuration from appsettings.json for simple deployment-time configuration.
Once the logger is configured, you will immediately see some events from the framework on each request. You can add logging to your own code by taking a dependency on Microsoft.Extensions.Logging's ILogger<T>:

class HomeController : Controller 
{
    readonly ILogger<HomeController> _log;

    public HomeController(ILogger<HomeController> log)
    {
        _log = log;
    }

    public IActionResult Index()
    {
        var secret = 42;
        _log.LogInformation("The secret number is {Secret}");
    }
}

Notice that ASP.NET Core logging has full support for message templates, meaning tokens like {Secret} in the log message will be translated into fully-searchable properties in Seq.

Under the hood

The API of Seq.Extensions.Logging is complete: you can comfortably use it all the way through to production without thinking about how any of it works under the hood. But, if you find you need more control over how log events are collected, or if you'd like to use more advanced Serilog features to enrich or filter events, it's easy to migrate over to Serilog.
Under the hood, the package wraps Serilog, the Serilog provider for Microsoft.Extensions.Logging, and the other bits and pieces of plumbing that make Seq and Serilog work together. Replacing AddSeq() with AddSerilog() is straightforward and mechanical, and all of your logging will continue working in exactly the same way.

Levelling up

There's a whole host of interesting details on ASP.NET Core's logging in the official documentation. Taking some time to learn how to use the API can make your application much easier to debug once it's out there in production.
Don't forget to Install-Package Seq.Extensions.Logging and AddSeq() next time you're starting out on ASP.NET Core!



ASP.NET Hosting - ASPHostPortal.com :: How To Securing your ASP.NET MVC Application

clock February 7, 2017 05:05 by author Armend

Securing your ASP.NET MVC application ought to be priority number a single each time you begin a brand new net application. Employing the attributes Authorize and ValidateAntiForgeryToken in every single controller and action will be the only method to stay away from any safety holes. In this post I’ll show you the best way to secure your ASP.NET application by implementing the AuthorizeAttribute and ValidateAntiForgeryTokenAttribute classes.

The basics

In the extremely least, you need to add an [Authorize] attribute to every controller or controller Action in case you would like several of the controller actions to be accessible by anonymous users. As an example, you probably want ALL users to possess access for the login and register actions of one's web application.

By decorating the HomeController using the Authorize attribute (notice I didn't specify any user part) the application will avert any unauthenticated user from executing any in the actions in this controller.

[Authorize]
public class HomeController : Controller
{
  //...
}

The following is an instance of decorating a controller action with all the Authorize attribute, you desire to complete this if you only want to restrict access to a few of the actions in a controller instead of all actions.

[Authorize]
public ActionResult Create()
{
  //...
}

Safeguarding against Cross-site request forgery attack (CSRF or XSRF)

The Authorize attribute delivers protection which is sufficient in most situations. Nonetheless, there's security hole with this and therefore it opens your web application for a cross-site request forgery attack. By way of example, right after a user logs into your website the website will concern your browser an authentication token inside a cookie. Every single subsequent request, the browser sends the cookie back for the site to let the web site realize that you are authorized to take what ever action you are taking, so far every thing is very good.

Right here would be the issue with only using the Authorize attribute, let’s say that a user is logged in to your website and then they visit a spam web site by clicking on a hyperlink that points to one more web site which causes a kind post back to your site… this can be negative, your browser will send the authentication cookie to your website generating it seem as when the request came out of your website and initiated by an authenticated user when it genuinely didn’t.

The above situation is known as cross-site request forgery and can be avoided by adding the ValidateAntiForgeryToken attribute offered inside the .NET framework, this attribute is employed to detect regardless of whether a server request has been tampered with.

The initial step would be to add the ValidateAntiForgeryToken attribute to every single Post Action as follows:

[HttpPost, Authorize, ValidateAntiForgeryToken]
public ActionResult Create()
{
  //...
}

The next step is to add the HtmlHelper strategy @Html.AntiForgeryToken() inside the type within your view.

The way the ValidateAntiForgeryToken attribute operates is by checking to view that the cookie and hidden kind field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException shown beneath:

“A essential anti-forgery token was not supplied or was invalid”

By adding the ValidateAntiForgeryToken for your controller actions your internet site will likely be prepared to stop CSRF/XSRF attacks.

Implementing Forms Authentication using Active Directory (AD)

Often times you might run across a project where you need to authenticate users of your website using Active Directory credentials, the good news is that you can use the existing “Account” controller to achieve this, only a few modifications are necessary.

When you create a new MVC Web Application project and choose the Internet Application template, the Account controller is added to the project, you can use this controller with AD to authenticate your users. For the Account controller to work with AD we need to remove all Actions but the following:

  • Logon()
  • Logon(LogOnModel model, string returnUrl)
  • LogOff()

Your Account controller should look like the following after you remove the unnecessary Actions such as ChangePassword, Register, etc.

public ActionResult LogOn()
        {
            return View();
        }
       
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect");
                }
            }

            // if we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

After this, go ahead and clean up the AccountModel as well so the only model class left is the LogOnModel:

public class LogOnModel
        {
            [Required]
            [Display(Name = "User name")]
            public string UserName { get; set; }
            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }
            [Display(Name = "Remember me?")]
            public string RememberMe { get; set; }
        }

Lastly, add the following to the project’s web.config file:

 

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 :: JavaScript style setTimeout and setInterval in C#

clock January 31, 2017 05:05 by author Armend

I found JavaScript setTimeout and setInterval functions quite handy for timer like functionality and some time wish I could use that in C# too. In an earlier post I create a C# like timer functionality in JavaScript. Now, I want to do opposite i.e. implement JavaScript setTimeout and setInterval like functionality in C#.
This is can be done very easily using Lamda expressions and Timer. Look at the below utility class -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DailyCoding.EasyTimer
{
    public static class EasyTimer
    {
        public static IDisposable SetInterval(Action method, int delayInMilliseconds)
        {
            System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
            timer.Elapsed += (source, e) =>
            {
                method();
            };

            timer.Enabled = true;
            timer.Start();

            // Returns a stop handle which can be used for stopping
            // the timer, if required
            return timer as IDisposable;
        }

        public static IDisposable SetTimeout(Action method, int delayInMilliseconds)
        {
            System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
            timer.Elapsed += (source, e) =>
            {
                method();
            };

            timer.AutoReset = false;
            timer.Enabled = true;
            timer.Start();

            // Returns a stop handle which can be used for stopping
            // the timer, if required
            return timer as IDisposable;
        }
    }
}

To use setTimeout this you can simply do -

EasyTimer.SetTimeout(() =>
{
    // --- You code here ---
    // This piece of code will once after 1000 ms delay

}, 1000);

The code will run after 1000 ms delay similarly like JavaScript setTimeout. The function also returns a handle. If you want clearTimeout like functionality, then the simply dispose off the handle.

var stopHandle = EasyTimer.SetTimeout(() =>
{
    // --- You code here ---
    // This piece of code will once after 1000 ms

}, 1000);


// In case you want to clear the timeout

stopHandle.Dispose();
Similarly you can use setInterval as -
EasyTimer.SetInterval(() =>
{
    // --- You code here ---
    // This piece of code will run after every 1000 ms

}, 1000);

and SetInterval also returns a stop handle which you can use for clearInterval like functionality. Just dispose off the handle -

var stopHandle = EasyTimer.SetInterval(() =>
    {
        // --- You code here ---
        // This piece of code will run after every 1000 ms
        // To stop the timer, just dispose off the stop handle

    }, 1000);


// In case you want to clear the interval
stopHandle.Dispose();

Best ASP.NET Core 1.0 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 :: Dynamically from code behind in asp.net using C#

clock January 24, 2017 11:50 by author Armend

In this example we explain that how to change CSS dynamically from code behind in asp.net using C#. or how to change CSS file programmatically in C# code(back end  code) in asp.net. Some time we have requirement like if user click on or check Lightweight button then Lightweight CSS is apply to the application for these user only same like if user checked or click on Professional button then Professional look is applied to the application for these user only these totally is dynamic and depend on user requirement.


So how to change or switch CSS file dynamically from code behind in asp.net using C#.

ChangeCSSFileDynamically.aspx:


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Dynamically change (switch) CSS file programmatically from code behind in ASP.Net</title>
    <link id="lnkCSS" runat="server" href="~/CSS/Lightweight.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="This is a Label" CssClass="label"></asp:Label>
    <hr />
    <asp:RadioButton ID="chkLightWeight" runat="server" GroupName="CSSTheme" AutoPostBack="true" Text="LightWeight"
        OnCheckedChanged="chkLightWeight_CheckedChanged1" />
    <asp:RadioButton ID="chkProfessional" runat="server" GroupName="CSSTheme" AutoPostBack="true" Text="Professional"
        OnCheckedChanged="chkProfessional_CheckedChanged1" />
    </form>
</body>
</html>

ChangeCSSFileDynamically.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class ChangeCSSFileDynamically : System.Web.UI.Page
    {

        protected void chkLightWeight_CheckedChanged1(object sender, EventArgs e)
        {
            lnkCSS.Attributes["href"] = "~/CSS/Lightweight.css";
        }

        protected void chkProfessional_CheckedChanged1(object sender, EventArgs e)
        {
            lnkCSS.Attributes["href"] = "~/CSS/Professional.css";
        }
    }
}

Lightweight.css:

body
{
    font-family:Times New Roman;
    font-size:10pt;
}
.label
{
    font-weight:bold;
    color:Purple;
}

Professional.css:

body
{
    font-family:Arial;
    font-size:bold;
}
.label
{
    font-weight:bold;
    color:yellow;
}

Best ASP.NET Core 1.0 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 :: Creating Help Desk Web Application using ASP.NET Core

clock January 17, 2017 05:28 by author Armend

Suppose you work for a small to midsize company that employs 50-100 workers. The Help Desk -- a subsidiary of the Information Services Division -- is in charge of trouble tickets regarding general PC issues such as email, viruses, network issues, etc. Initially, the Help Desk team stored this information in Excel spreadsheets, but as the company has grown, managing these spreadsheets has become tedious and time consuming.

The Help Desk has asked you to devise a more efficient solution that could be developed internally, saving the company money. As you start to think about it, the following requirements are apparent: fields for the submitter's first and last name, as well as their email address. You'll also need combo boxes for indicating ticket severity (low, medium, high), department, status (new, open, resolved), employee working on the issue, as well as an area for comments. Of all the solutions available, creating an internal help desk Web application with ASP.NET is relatively simple.

In the following article, we'll see how to implement these features in an ASP.NET help desk Web application using a database-driven approach,
Creating the JavaScript File
Because creating the JavaScript file is the easiest of the work left, we'll do this next. From the Solution Explorer, follow these steps:

Creating the Help Desk Class

Now that we have our data coming in, we need to be able to record a help desk ticket submission. We need to create an event handler in a class to handle it. Let's first create a help desk class by doing the following:

  •     Right click the project solution.
  •     Choose Add>New Item.
  •     In the Add New Item window, select Class.cs.
  •     In the name text field, type "HelpDesk" and then click Add.

Double click HelpDesk.cs from the Solution Explorer, which will show the empty class as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HelpDesk
{
    public class HelpDesk
    {
    }
}

We need to import three libraries as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace HelpDesk
{
    public class HelpDesk
    {
    }
}

The first library (System.Data) allows us to work with stored procedures in ADO.NET, the second (System.Configuration) allows us to reference a connection key from configuration file and the last (System.Data.SqlClient) one allows us to connect to SQL Server.


About ASPHostPortal.com:


ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: How to implement Windows authentication and authorization in ASP.NET

clock January 10, 2017 05:21 by author Armend

This step-by-step article describes how to implement Windows authentication and authorization in an ASP.NET application. To use the built in security of Windows and ASP.NET, implement Windows authentication and authorization on groups and users. To use Windows authentication, you must adjust settings in both Microsoft Internet Information Services (IIS) and the ASP.NET application Web.config file.

Requirements

  • Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows XP Professional
  • Microsoft .NET Framework
  • Microsoft Internet Information Services (IIS)
  • Microsoft Visual Studio .NET

Authentication and authorization

Windows authentication and Windows authorization are two terms that are frequently interchanged. However, they do not have the same meaning. Windows authentication permits the recipient to determine the user's identity. Windows authorization determines the resources to which a user may gain access.

Configure Web application for Windows authentication

To configure your Web application for Windows authentication, follow these steps:

  • Create an ASP.NET Web Application named ASPNETWinAuth. By default, theWebForm1.aspx file appears.
  • In the HTML view of WebForm1.aspx, replace the existing code with the following sample code:

    <%=User.Identity.Name%>

  • Click Start, point to Programs, point to Administrative tools, and then click Internet Information Services.
  • The Internet Information Services MMC appears. Expand Computer, and then expand a Web site that uses Windows authentication.
  • Click the ASPNETWinAuth Web site application.
  • On the Action menu, click Properties.
  • In Properties, click the Directory Security tab.
  • Under Anonymous access and authentication control, click Edit.
  • In Authentication Methods, click to select Integrated Windows authentication. Click to clear all other check boxes.
  • Click OK.
  • In Properties, click OK. The ASPNETWinAuth Web application is now configured to accept valid user accounts.

Configure the ASP.NET application

After you configure the IIS Web site for Integrated Windows Authentication, you must configure the ASP.NET application to recognize authenticated users. To do this, you must change the Web.config file. In the Web.config file, locate the <authentication> tag, and then set the mode attribute to Windows, as in the following example:

<authentication mode="Windows" />

Test authentication

To test your Windows authentication setting, follow these steps:

  • In Microsoft Internet Explorer, view the WebForm1.aspx page. This page is located in the Http://Localhost folder. For example:

    http://Localhost/ASPNETWinAuth/WebForm1.aspx

  • Because Integrated Windows Authentication uses the current Windows user information on the client computer for the authentication, it does not immediately prompt the user for a user name and password. However, if the authentication exchange cannot identify the user, a dialog box appears that prompts the user for a Windows user account user name and password.
  • Type a valid user name and password. When the page loads, your user name appears in the following format:

    Domain Name\User Name

Restrict access

In ASP.NET, you set authorization to the application by adding settings in the Web.config file. You can specify which users or groups are permitted to have access to what resources as follows:
To permit all users of an NT Group named Managers to have access to your resources, use the following code:

<configuration>
      <system.web>
        <authorization>
          <allow roles="domainname\Managers" />
          <deny users="*" />
        </authorization>
      </system.web>
    </configuration>

To permit only specific users to have access, use the following code:

<configuration>
      <system.web>
        <authorization>
          <allow users="domainname\user1,domainname\user2,domainname\user3" />
          <deny users="*" />
        </authorization>
      </system.web>
    </configuration>

Note You can specify multiple roles or users by using a comma separated list. Verify that you use the correct case when you specify the configuration file element and the associated attribute values. This code is case sensitive.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides our 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 2012. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows server 2012 Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Protect Web Pages Using .htaccess Files

clock January 8, 2017 13:47 by author Armend

A .htaccess file (pronounced ‘dot aitch tee access’ or simply ‘aitch tee access’) is aspecial configuration file used on web servers running the Apache httpd web server software. When someone visits a page that is sitting in a directory alongside, or in the same branch as, a .htaccess file then that configuration file will be loaded by the server and processed.

.htaccess files are used to reconfigure the web server without needing to restart it. These files can be used to enable or disable additional functionality and features, such as creating redirects, disabling directory listings and password protecting directories.

If you want to password protect some of your web pages, then you need to use a .htaccess file with a .htpasswd password file. This tutorial will tell you step-by-step what you need to do.


Step By Step Instructions
Let's suppose you want to restrict files in a directory called members to username memberone with password memberonepassword. Here's what to do:
1. Create a file called .htaccess in directory members that looks like this:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd
require valid-user


Notes
:

  • In the AuthUserFile line, replace USERNAME with your ftp username.
  • The .htaccess file must be an ASCII text document.
  • A .htaccess file can be created in any word processor but must be saved as text only.
  • IF you upload your .htaccess file via FTP, the FTP client must be set to ASCII mode for transfer.
  • For security reasons, the .htaccess file on the server cannot be seen in a directory listing. If you don't see it after uploading it, don't worry.
    Also note that AuthName can be anything you want. The AuthName field gives the Realm name for which the protection is provided. This name is usually given when a browser prompts for a password, and is also usually used by a browser in correlation with the URL to save the password information you enter so that it can authenticate automatically on the next challenge.

2. Use the htpasswd command, from your home directory, to create a password file called .htpasswd in your home directory:
SSH to your home directory. This is simply done by connecting with your SSH client and NOT entering any path, and NOT changing directories after connecting. After connecting to your home directory via SSH, enter:

# htpasswd -c .htpasswd memberone

Type the password -- memberonepassword -- twice as instructed.
3. That's the setup done. Now test by trying to access a file in the directory members; your browser should demand a username and password, and not give you access to the file if you don't enter memberone and memberonepassword.


Multiple Usernames/Passwords

If you want to give access to a directory to more than one username/password pair, follow the steps above to create the .htaccess file and to create the .htpasswd file with one user. Then, add additional users to the .htpasswd file by using the htpasswd command without the -c:

# htpasswd .htpasswd membertwo
New password:
Re-type new password:
Adding password for user membertwo


Changing Passwords

If you want to change the password for an existing user, simply issue the same command as when you added the user. You will then be prompted for a new password. For example, if the user membertwo already exists and you want to change the password, just SSH to your home directory and enter:

# htpasswd .htpasswd membertwo


Password Protecting Multiple Directories
If you want to password protect multiple directories, and allow all users access to all password protected directories, then all you need to do is put the same .htaccess file in each directory that you want to password protect.

However, if you want to password protect multiple directories, and only allow certain users access to each directory, then you can create a different password file (all in your home directory) for each password protected directory.

Let's say you have 3 different directories (members, admins, board) you want password protected, and each one has a different set of users that you want to allow access. Then just do the following:

Create three .htaccess files and put them in their appropriate directory:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.members
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.admins
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.board
require valid-user

Remember to replace USERNAME with your ftp username (in lower case).

Create three .htpasswd files in your home directory:

# htpasswd -c .htpasswd.members memberone
# htpasswd -c .htpasswd.admins adminone
# htpasswd -c .htpasswd.board boardmemberone

That's it. Now when you need to add a user to one of the directories, just issue the htpasswd command on the appropriate .htpasswd file.

 

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 :: Tips Create User Roles in ASP.NET MVC

clock December 20, 2016 04:54 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"))
{
}

 

Best ASP.NET MVC 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.

     



    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