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 :: How To Using DataAnnotations and Localization in ASP.NET Core MVC

clock March 14, 2017 05:54 by author Armend

Using DataAnnotations and Localization in ASP.NET Core MVC

This article shows how ASP.NET Core localization can be used together with data annotations. The data annotations are used to decorate the data model, and when HTTP POST/PUT (also PATCH) Requests are sent with model errors, the error message is returned localized in the request culture.

Localization Setup

In the Startup class, the AddDataAnnotationsLocalization is added in the ConfigureServices method.   

services.AddMvc()
   AddViewLocalization()
   AddDataAnnotationsLocalization();

Now a model class can be created and the data annotations can be used. The Length property in this example has a range attribute, with an ErrorMessageResourceName and an ErrorMessageResourceType property set. The ErrorMessageResourceType is used to define the resource itself using the type and the ErrorMessageResourceName is used to define the resource identifier. Only the Length property has localized error messages implemented.

using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Globalization;
using AspNet5Localization.Controllers;
using Microsoft.Extensions.Localization;  
namespace AspNet5Localization.Model
{
    public class Box
    {
        public long Id { get; set;
        public double Height { get; set;
        public double Width { get; set; }
        [Required(ErrorMessage = "BoxLengthRequired")]
        [Range(1.0, 100.0, ErrorMessage = "BoxLengthRange")]
        public double Length { get; set; }
    }
}

Now a MVC 6 controller can be created which uses the model class. This controller implements POST and PUT action methods, which uses the ModelState to validate the request. If the model is invalid, the error message is returned with a localized value.

using AspNet5Localization.Model;
using Microsoft.AspNetCore.Mvc;
namespace AspNet5Localization.Controllers
{
    [Route("api/[controller]")]
    public class BoxesController : Controller
    {
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            if (id == 0)
            {
                return NotFound(id);
            }
            return Ok(new Box() { Id = id, Height = 10, Length = 10, Width=10 });
        }
 
        /// <summary>
        /// http://localhost:5000/api/boxes?culture=it-CH
        /// Content-Type: application/json
        ///
        /// { "Id":7,"Height":10,"Width":10,"Length":1000}
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post([FromBody]Box box)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            else
            {          
                string url = Url.RouteUrl("api/boxes", new { id = 11111 },
                    Request.Scheme, Request.Host.ToUriComponent());
 
                return Created(url, box);
            }
        }
 
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody]Box box)
        {
            if(id == 0)
            {
                return NotFound(box);
            }
 
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            else
            {
                return Ok(box);
            }
        }
 
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            if (id == 0)
            {
                return NotFound(id);
            }
 
            return new NoContentResult();
        }
    }
}

Now the POST method can be called in Fiddler or Postman. Underneath is an example of a HTTP POST Request using the it-CH culture. The length property is outside the range and will return an model state error.

http://localhost:5000/api/boxes?culture=it-CH
User-Agent: Fiddler
Host: localhost:5000
Content-Length: 46
Content-Type: application/json
{ "Id":7,"Height":10,"Width":10,"Length":1000}
HTTP Response with a it-CH localized error message:
HTTP/1.1 400 Bad Request
Date: Sat, 24 Oct 2015 17:15:28 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
{"Length":["The box length should be between 1 and a 100 it-CH"]}

Localization can be used in data annotations like previous versions of MVC or Web API and provides a simple way of validating your data inputs.

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 :: Improve Performance of an ASP.NET Website

clock March 7, 2017 04:49 by author Armend

Improve Performance of an ASP.NET Website

In this tip, we will look at various aspects of improving the performance of ASP.NET web applications.
Performance is an important aspect of the modern day web application development. Here are some tips that you can consider while making a better performing website.

1. Upgrade Your ASP.NET Framework

Check your .NET framework. If you can upgrade your site to use .NET 4.5, then it has some great performance optimizations. .NET 4.5 has a new Garbage Collector which can handle large heap sizes (i.e., tens of gigabytes). Some other improvements are Multi-core JIT compilation improvements, and ASP.NET App Suspension. These optimizations do not require code changes.

2. Caching

Use output caching – Use output caching for regularly used views or pages which have no dynamic updates. The easiest way to implement cache on MVC view is to add an [OutputCache] attribute to either an individual controller action or an entire controller class. Here is a controller action Index() that will be cached for 15 seconds.

[OutputCache(Duration = 15, VaryByParam = "None")]
public ActionResult Index(string Id)
{
}

Use Data caching - Reduces the database or the disk I/O by caching the regularly used data to in-memory cache. This avoids repeated queries for data, and it can improve performance and scalability. In addition, caching makes data available when the data source is temporarily unavailable. The .NET Framework provides classes that enable you to use caching facilities in ASP.NET applications. These classes are defined in the System.Runtime.Caching namespace.

3. Always keep CSS and JavaScript External

Never add any JavaScript or inline style information within the views. That would regenerate the view each time and you would miss out on the benefits of the Caching. Hence always keep JS and CSS as separate files and add them as links in the view.

4. File Compression

There are often requests to the web server with lot of static content. These contents can be compressed thereby reducing the bandwidth on requests. The following setting is only available in II7 and later.

configuration> 
    <system.webServer>   
        <urlCompression doStaticCompression="true" doDynamicCompression="true" /> 
    </system.webServer>

The urlCompression name sounds strange but it is not really the compressing of URLs. It means compressing or gzipping the content that is sent to the browser. By setting to true/enabling, you can gzip content sent to the browser while saving lots of bandwidth.

5. Bundling and Minification

The custom CSS files and the JavaScript files should be bundled into a single large file (reduces the number of HTTP requests) and also minified (reduces the size of the data transferred over the wire).

6. CDN (Content Delivery Network)

All the 3rd party JavaScript files such as JQuery, Knockout should always use the CDN instead of the web application server. CDN Servers are dedicated to deliver the static content and is always faster than your own host. There is a very high probability that the client (browser) would have already cached the JavaScript as part of other web application since most of them use the same CDN URL.

7. Control Image Requests

There are couple of ways to do this. 

Image sprite - With image sprite, you can combine multiple different images into a single large image. Then use CSS to reposition those images within the site.
Base64 Data URIs - With this option, you would never make any requests to the server to obtain any images.

8. Script Rendering Order

Move the script tags <script> to the very bottom of the page. The reason this is important is because during the rendering, when the browser comes across a <script> tag, it stops to process the script and then moves ahead. If you put the script tags at the bottom of the page, the page/HTML will render faster and the scripts can execute after the DOM elements have loaded. Sometimes moving the script to the bottom of the page is not possible as some DOM elements or CSS may depend on these scripts, so they can be rendered. In such cases, you could move those scripts further up the page.

There are some other ways:

  • 1.defer attribute

Hide Copy Code

<script src="some.js" defer>
</script>

Using the defer attribute, you can specify the script not to run until the page has been fully loaded.

  • 2.async attribute

<script src="some.js" async>
</script>

Using the async tag, the scripts will be run asynchronously, as soon as it is available.

9. Removing Default HTTP Modules in ASP.NET

ASP.NET has many http modules waiting for request to be processed and would go through the entire pipeline even if it’s not configured for your application.
All the default modules will be added in the machine.config place in“$WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG” directory. One could improve the performance by removing those modules which you wouldn’t require.

10. Compile in Release Mode

Always set the build configuration to release mode for the website.

In this tip, we looked at some of the approaches that you can take to make optimized and better performing web sites. This included, reducing number of requests to the server, changes to the .NET framework, and compressing techniques.

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



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