Hosting Article

ByAlexia Pamelov

Tips Improve The Speed Of Your Sites With HTTP/2

CheapWindowsHosting.com | If you find that the Websites are taking too much time to load, your Server may not be using HTTP/2. If you want to do away with problems faced with the Website loading, you have to upgrade to HTTP/2. There are many problems with the previous versions such as HTTP 1 and HTTP 1.1. The loading times were relatively quite slow. You will find it frustrating, using it. You have to keep real patience for the sites to load fully.

Problems faced while using HTTP1.x

Following are the major problems that are faced with HTTP1.x

  • Text based
    The protocols that are used in HTTP 1.x are all text based. It is due to the fact; it was tried to make all the protocols readable by the humans. These give rise to many inefficiencies like white space and capitalization.
  • Single file transfer at a time
    The HTTP 1.x has the capacity to transfer only a single file at a time. This increases the time for the loading of the pages.
  • Problems in facing multiple requests
    The type of Web usage has gone for a complete change in the rent times. The Website sizes and the resources have also grown in number. Time taken for the loading of each resource takes longer than before.
  • Requires complex technical operations
    As, there are many numbers of connections, which are needed to be made; there is a heavy load on the Server. The combined time requirement for making connections becomes quite large.

How problems are overcome with HTTP/2

The use of HTTP/2 is very effective in the fast loading of the Websites.

Here are the ways in which the problems are solved.

  • Machine based
    The protocols are made in a manner that it would be understood by the machines and not human beings. It is no more text-based. It follows the binary code and more efficient for the Server functioning. Data transfer becomes much faster.
  • Several files can be sent together
    All the resources can be moved on a single connection. This makes the process faster.
  • Server sends the files needed by browser
    In the HTTP 1.x version, the Web Browser is responsible for asking the Server about the resource requirements. In the HTTP/2 version, the Server knows about the resources that are to be sent to the Server. This again hastens up the entire process.
  • Different types of optimizations
    HTTP packet header improves and other betterments are designed, which helps in the better data transfer process.

How to enable HTTP/2

There is not much trouble to be faced for the enabling of HTTP/2. It has to be done at the level of the Web Server. There are certain important Servers that have prior support for running HTTP/2 version. If you are having a self-owned Server, HTTP/2 libraries are required to be installed. If you are taking the hosting Services from a hosting company, you have to ask them for HTTP/2 version.

Better levels of security

When you change over your Server to HTTP/2, you can automatically enjoy a better security version. The privacy factor is also enhanced. This is due to the encryption of HTTP sites. If you are not sure of how to go about with this, you can ask your hosting company for the required guidance. It is not only the security issue. If you go for the HTTP/2, you will find the Websites are functioning in much better way. As the technology is making progress, you will benefit with availing the better advanced technology. The overall feel of the use of the Web will be enhanced and your business process, if done online can become faster.

ByAlexia Pamelov

Use SQL Server Sequence in Entity Framework Core to Create Primary Key

CheapWindowsHosting.com | Best and cheap Entity Framework core hosting. Entity Framework doesn’t support Sequence out of the box. However, there are ways to use it. But the good news is, Entity Framework Core supports Sequence out of the box.

So in this post, let’s find out how to use SQL Server Sequence in Entity Framework Core to create primary key.

Use SQL Server Sequence in Entity Framework Core

To begin with, a little info about Sequence. SEQUENCE was introduced in SQL Server 2012. Sequence is a user-defined object and it generates a sequence of numeric values according to the properties with which it is created. It is similar to Identity column, but there are many differences between them. Like,

  • The Sequence is used to generate database-wide sequential number, where identity column is tied to a table.
  • Sequence is not associated with a table. You can associate it with multiple tables.
  • It can be used in insert statement to insert identity values, it can also be used in T-SQL Scripts.

I suggest you to read this and this post to find out the difference between Identity and Sequence in SQL Server.

Now coming to our topic, let see how to use SQL Server Sequence in Entity Framework Core to create primary key. First, define the model. Here is code for the model class.

public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }    
}

EF Core by convention configures a property named Id or <type name>Id as the key of an entity. Note, “Microsoft.EntityFrameworkCore.SqlServer” nuget package needs to be included to use SQL Server with EF Core.

Now we need to create our DBContext. Add a new class file and name it SampleDBContext.cs and add following code.

public class SampleDBContext : DbContext
{
    public SampleDBContext()
    {
         Database.EnsureDeleted();
         Database.EnsureCreated();
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionbuilder)
    {
        string sConnString = @"Server=localhost;Database=EFSampleDB;Trusted_Connection=true;"
        optionbuilder.UseSqlServer(sConnString);
    }
 
   protected override void OnModelCreating(ModelBuilder modelbuilder)
   {
       modelbuilder.ForSqlServerHasSequence<int>("DBSequence")
                              .StartsAt(1000).IncrementsBy(2);
       modelbuilder.Entity<Category>()
          .Property(x => x.CategoryID)
          .HasDefaultValueSql("NEXT VALUE FOR DBSequence");
    }
 
    public DbSet<Category> Categories { get; set; }
}

 

  • The SampleDBContext() constructor is an implementation of database initializer DropCreateDatabaseAlways.
  • OnConfiguring() method is used for configuring the DBContext. Here we are saying that use SQL database and define the connection string to connect.
  • OnModelCreating method is used to define configuration for the model. The ForSqlServerHasSequence extension method is used for creating SQL Server Sequence. You need to supply the name of the sequence. Additionally, you can also configure start number and increment option. There is also a HasSequence extension method which is similar to ForSqlServerHasSequence. The reason for having these 2 different sets of method is, EF Core supports many database providers. And functionality for these providers are slightly different so you are able to specify a different behavior for the same property depending on the provider being used. Read this to find out more.
  • Once the sequence is defined, then we need to configure it for the model. As the primary key column is no more identity column, so while inserting EF needs to know the primary key column value. The HasDefaultValueSql extension method can be used to provide a default value for any column. So in this case, the default value we need to get it from the newly created sequence. The SQL Syntax to select next value from the sequence is,
SELECT NEXT VALUE FOR DBSequence
  • And same syntax we need to supply HasDefaultValueSql except “SELECT” keyword.

Now, lets add some data using the following code.

using (var dataContext = new SampleDBContext())
{
    dataContext.Categories.Add(new Category() { CategoryName = "Clothing" });
    dataContext.Categories.Add(new Category() { CategoryName = "Footwear" });
    dataContext.Categories.Add(new Category() { CategoryName = "Accessories" });
    dataContext.SaveChanges();
}

 Run the application. And you should see “EFSampleDB” created with Categories table and DBSequence sequence.

Use-SQL-Server-Sequence-in-Entity-Framework-Core-to-Create-Primary-Key

Following is the create script of Categories table,

CREATE TABLE [dbo].[Categories](
   [CategoryID] [int] NOT NULL DEFAULT (NEXT VALUE FOR [DBSequence]),
   [CategoryName] [nvarchar](max) NULL,
 CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED 
(
   [CategoryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

 And following is the create script of DBSequence,

CREATE SEQUENCE [dbo].[DBSequence] 
 AS [int]
 START WITH 1000
 INCREMENT BY 2
 MINVALUE -2147483648
 MAXVALUE 2147483647
 CACHE 
GO

 And following is the result of Select * from Categories query.

Use-SQ

That’s it. You can use sequence for any of your columns. EF Core also supports HiLo Pattern to generate keys and HiLo pattern also makes use of sequence

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

ByAlexia Pamelov

How To Develop a Joomla from Scratch

CheapWindowsHosting.com | Best and cheap Joomla hosting. Want a customized joomla template for the business requirements? It really is so easy to construct a template of one’s decision as an alternative to paying thousands for it. So lets commence now.

To produce a joomla template you may require at the least two files.

  1. templateDetails.xml which can be mainly configuration file containing info like autor name, e mail, template version, folders and file names and module names (we’ll discuss it leter).
  2. index.php which can be entry point for all pages
    These are standard files required to create a joomla template, but furthermore you will need some a lot more files to produce a beautiful and powerful template like css, images, language, javascript, html and so forth.

Now lets generate our xml file

<?xml version="1.0" encoding="utf-8"?>
 
<extension version="2.5" type="template" client="site">
<name>template_name</name>
<creationdate>29 January 2014</creationdate>
<author>write Your name here</author>
<authoremail>write your email here</authoremail>
<authorurl>your website url here</authorurl>
<copyright>Copyright here. All rights reserved.</copyright>
<license>License here</license>
<version>2.5.0</version>
<description>TPL_NAME_XML_DESCRIPTION</description>
<files>
<filename>index.html</filename>
<filename>index.php</filename>
<filename>templateDetails.xml</filename>
<filename>template_preview.png</filename>
<filename>template_thumbnail.png</filename>
<filename>favicon.ico</filename>
<filename>component.php</filename>
<filename>error.php</filename>
</files>
<positions>
<position>debug</position>
<position>top</position>
<position>position-2</position>
<position>position-3</position>
<position>position-4</position>
<position>position-5</position>
<position>position-6</position>
<position>banner</position>
<position>left-navigation</position>
<position>position-login</position>
<position>position-footer</position>
</positions>
</extension>

 As you can see further files are right here like index.html (just to avoid direct access of this folder) , template_preview.png and template_thumbnail.png to show in administrator panel. Here several positions are defined which we’ll use in our index.php file.

Your xml is prepared, now produce your index.php file.

<?php defined( '_JEXEC' ) or die( 'Restricted access' );?>
<!DOCTYPE html>
<html xml:lang="<!--?php echo $this--->language; ?>" lang="<!--?php echo $this--->language; ?>" >
<head>
<jdoc:include type="head" />
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/template_name/css/template.css" type="text/css">
</head>
<body>
<jdoc:include type="modules" name="top" />
<jdoc:include type="modules" name="banner" />
<jdoc:include type="modules" name="left-navigation" />
<jdoc:include type="component" />
<jdoc:include type="modules" name="footer" />
<jdoc:include type="modules" name="position-3" />
</body>
</html>

As you see we have included defined( ‘_JEXEC’ ) or die( ‘Restricted access’ );
just for security reasons to prevent direct access. is here to tell browsers and crawlers that its a html5 web page.

body{padding:0;margin:0;font-family:"arial";font-size:12px;color:#5d6060;background-color:#fff}
a{text-decoration:none;outline:0}
a:focus,a:active{outline:0}
img{border:0;outline:0}
.container{height:auto;width:1044px;margin-right:auto;margin-left:auto}
.container_sub{height:auto;width:1044px;float:left}
#header_main{height:auto;width:1044px;float:left}
#header{height:118px;width:1044px;float:left}
.header_top{height:auto;width:1044px;float:left}
#logo{height:75px;width:231px;float:left;margin-top:4px}

Your template is ready now but to perform with joomla you’ve got to upload it below templates folder. Following uploading it to templates folder log in for your joomla administrator and open extensions -> Templates manger. Right here you’ll not be able to see your template as you expected. This can be since it calls for one more step, to set up the template. Ok, visit Extensions -> Extension Manager then click Learn tab now click on discover icon around the top-right corner from the page. It’s going to search all of the extensions accessible inside your joomla installation, here you will be able to see your template name, select it and click on set up icon on the top-right corner of the page. This will likely install your template. Now you happen to be done. Go to Extensions-> Template manager , right here you’ll be able to see your installed template.

ByAlexia Pamelov

What Difference Between .NET Framework and .NET Core

CheapWindowsHosting.com | Best and cheap .Net core. hosting. What should you choose for your next application – .NET Framework or .NET Core? This was a question asked by a business owner in one of my advisory meetings, recently.

In this article, let’s compare these two platforms and see if we can come to a conclusion.
 
.NET Ecosystem

Let’s review the following .NET ecosystem architecture diagram, as of today.

DotNet-Architecture

As you can see from the above diagram, the .NET ecosystem has three major high-level components – .NET Framework, .NET Core, and Xamarin.

Xamarin is not a debate at all. When you want to build mobile (iOS, Android, and Windows Mobile) apps using C#, Xamarin is your only choice.
 
The .NET Framework supports Windows and Web applications. Today, you can use Windows Forms, WPF, and UWP to build Windows applications in .NET Framework. ASP.NET MVC is used to build Web applications in .NET Framework.
 
.NET Core is the new open-source and cross-platform framework to build applications for all operating system including Windows, Mac, and Linux. .NET Core supports UWP and ASP.NET Core only. UWP is used to build Windows 10 targets Windows and mobile applications. ASP.NET Core is used to build browser based web applications.

So, what to choose?

If you have to make a choice between .NET Framework and .NET Core today, here is the criteria. Keep in mind, a year or so down the road, you may not want to choose .NET Framework at all.

As of today:

.NET Framework is a better choice if you:

  • Do not have time to learn a new technology.
  • Need a stable environment to work in.
  • Have nearer release schedules.
  • Are already working on an existing app and extending its functionality.
  • Already have an existing team with .NET expertise and building production ready software.
  • Do not want to deal with continuous upgrades and changes.
  • Building Windows client applications using Windows Forms or WPF
.NET Core is a better choice if you:
  • Want to target your apps on Windows, Linux, and Mac operating systems.
  • Are not afraid of learning new things.
  • Are not afraid of breaking and fixing things since .NET Core is not fully matured yet.
  • A student who is just learning .NET.
  • Love open source.
The following table may help you make your decision.
 
High-performance and scalable system without UI .NET Core is much faster.
Docker containers support Both. But .NET Core is born to live in a container.
Heavily reply on command line .NET Core has a better support.
Cross-platform needs .NET Core
Using Microservices Both but .NET Core is designed to keep in mind today’s needs.
User interface centric Web applications .NET Framework is better now until .NET Core catches up.
Windows client applications using Windows Forms and WPF .NET Framework
Already have a pre-configured environment and systems .NET Framework is better.
Stable version for immediate need to build and deploy .NET Framework has a been around since 2001. .NET Core is just a baby.
Have existing experienced .NET team .NET Core has a learning curve.
Time is not a problem. Experiments are acceptable. No rush to deployment. .NET Core is the future of .NET.

 

ByAlexia Pamelov

How To Apply CSS In ASP.NET Server Controls In Real Time Scenario

CheapWindowsHosting.com | Best and cheap ASP.NET hosting. CSS means Cascading Style Sheet. The World Wide Web Consortium (W3C) created CSS. CSS describes the style of an HTML document.

CSS describes how HTML elements should be displayed.

Description

External stylesheets are stored in CSS files. CSS is used to define the styles for your Web pages, which includes the design, layout and the variations in display for the different devices and the screen sizes.

Steps
 
Part1

Create a CSS file named Styles.css.  
body {  
    font-family: Arial;  
}  
  
table {  
            font-family: arial, sans-serif;  
            border-collapse: collapse;  
            width: 70%;  
      }  
  
.button {  
    background-color: #4CAF50;   
    border: none;  
    color: white;  
    padding: 15px 32px;  
    text-align: center;  
    text-decoration: none;  
    display: inline-block;  
    font-size: 14px;  
    margin: 4px 2px;  
    cursor: pointer;  
}  
  
.button4 {border-radius: 14px;}  
  
.textbox {  
    height: 50px;  
    padding: 0 10px;  
    border: none;  
    background: Orange;  
    background: Orange;  
    box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.5);  
    font-family: 'Montserrat', sans-serif;  
    text-indent: 10px;  
    color: blue;  
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);  
    font-size: 20px;  
    width: 470px;  
}  
 .textbox:focus {  
    box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2), inset 0 1px 1px rgba(0, 0, 0, 0.1), 0 0 0 3px rgba(255, 255, 255, 0.15);  
    outline: none;  
    background: Orange;  
    background: Orange;  
    outline: solid 1px yellow;  
}

Description of Part1

To apply design and layout to ASP.NET button controls, the button background color should be Green and the text on button should be White.

.button {  
    background-color: #4CAF50;   
    border: none;  
    color: white;  
    padding: 15px 32px;  
    text-align: center;  
    text-decoration: none;  
    display: inline-block;  
    font-size: 14px;  
    margin: 4px 2px;  
    cursor: pointer;  
}  
  
.button4 {border-radius: 14px;}

For table design and layout, the table width should be 70%.

table {  
            font-family: arial, sans-serif;  
            border-collapse: collapse;  
            width: 70%;  
      }

For textbox design and layout, the textbox background color is Orange and Text is in blue. 

.textbox {  
    height: 50px;  
    padding: 0 10px;  
    border: none;  
    background: Orange;  
    background: Orange;  
    box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.5);  
    font-family: 'Montserrat', sans-serif;  
    text-indent: 10px;  
    color: blue;  
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);  
    font-size: 20px;  
    width: 470px;  
}  
 .textbox:focus {  
    box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2), inset 0 1px 1px rgba(0, 0, 0, 0.1), 0 0 0 3px rgba(255, 255, 255, 0.15);  
    outline: none;  
    background: Orange;  
    background: Orange;  
    outline: solid 1px yellow;  
}

Part2

Add a Webform named Default.aspx. 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  
<!DOCTYPE html>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title>Satyaprakash Wcf Concept</title>  
    <link href="Styles.css" rel="stylesheet" />  
    <script language="javascript" src="../Validation.js" type="text/javascript"></script>  
    <script language="javascript" type="text/javascript">  
        function Validation() {  
            if (Required('<%=txtname.ClientID%>', ' Name'))  
                if (Required('<%=txtGender.ClientID%>', ' Gender'))  
                    if (Required('<%=txtsalary.ClientID%>', ' Salary'))  
                        return true;  
            return false;  
        }  
    </script>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
         <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYAPRAKASH's  WCF CONCEPT</h2>  
        <fieldset>  
            <legend style="font-family:Arial Black;color:orangered">WCF INSERT USING STORED PROCEDURE</legend>  
            <table align="center" border="1" cellpadding="4" cellspacing="4">  
            <tr><td align="center"><asp:TextBox ID="txtname" class="textbox" runat="server" placeholder="Enter Name.."></asp:TextBox></td></tr>  
            <tr><td align="center"> <asp:TextBox ID="txtGender" class="textbox" runat="server" placeholder="Enter Gender.." ></asp:TextBox></td></tr>  
            <tr><td align="center"><asp:TextBox ID="txtsalary" class="textbox" runat="server" placeholder="Enter Salary.."></asp:TextBox></td></tr>    
            <tr><td align="center">  
                <asp:Button ID="btnsave" runat="server" Text="Save" class="button button4" OnClick="btnsave_Click" OnClientClick="javascript:return Validation();" />  
                <asp:Button ID="btnreset" runat="server" Text="Reset" class="button button4" OnClick="btnreset_Click"/>  
            </td></tr>                  
         </table>  
       </fieldset>  
    </div>  
    <footer>  
        <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>  
    </footer>  
    </form>    
</body>  
</html>

Description of Part2

How to apply CSS classes in Server controls of ASP.NET Web page.

To apply CSS in button , proceed as shown below.

<asp:Button ID="btnsave" runat="server" Text="Save" class="button button4" OnClick="btnsave_Click" OnClientClick="javascript:return Validation();" />  
<asp:Button ID="btnreset" runat="server" Text="Reset" class="button button4" OnClick="btnreset_Click"/>

To apply CSS in TextBoxes, proceed as shown below.

<asp:TextBox ID="txtname" class="textbox" runat="server" placeholder="Enter Name.."></asp:TextBox>  
<asp:TextBox ID="txtGender" class="textbox" runat="server" placeholder="Enter Gender.." ></asp:TextBox>  
asp:TextBox ID="txtsalary" class="textbox" runat="server" placeholder="Enter Salary.."></asp:TextBox>

To apply CSS in tables, proceed, as shown below. 

table {    
            font-family: arial, sans-serif;    
            border-collapse: collapse;    
            width: 70%;    
      }
<table align="center" border="1" cellpadding="4" cellspacing="4">
Here CSS classes table of CSS file is added.
The output of TextBoxes of ASP.NET Web page is given below.
1

The output of buttons of ASP.NET Web page is given below.

2

The output of table of ASP.NET Web page is given below.

3

 

ByAlexia Pamelov

Testing ASP.NET Core Identity

CheapWindowsHosting.com | Best and cheap ASP.NET Core hosting. In the following article, you will learn how to implement and unit test ASP.NET Core Identity.

ASP.NET Core Identity is a membership system which allows you to add login functionality to your application. Users can create an account and login with a user name and password or they can use an external login providers such as Facebook, Google, Microsoft Account, Twitter and more.

You can configure ASP.NET Core Identity to use a SQL Server database to store user names, passwords, and profile data. Alternatively, you can use your own persistent store to store data in another persistent storage, The following article will use SQL Server as data source engine.

The project described in the article will also use OpenIddict to implement token authentication: OpenIddict aims at providing a simple and easy-to-use solution to implement an OpenID Connect server in any ASP.NET Core application.

Setup Project

The following article will add ASP.NET Core Identity to the sample project used by: Implementing SOLID REST API using ASP.NET Core.

In order to use OpenIddict, add the appropriate MyGet repositories to your NuGet sources. This can be done by adding a new NuGet.Config file at the root of your solution:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="NuGet" value="https://api.nuget.org/v3/index.json" />
    <add key="aspnet-contrib" value="https://www.myget.org/F/aspnet-contrib/api/v3/index.json" />
  </packageSources>
</configuration>

 In order to use ASP.NET Core Identity and OpenIddict add the following packages to your project:

...
    <PackageReference Include="OpenIddict" Version="1.0.0-beta2-0580" />
    <PackageReference Include="OpenIddict.Core" Version="1.0.0-beta2-0580" />
    <PackageReference Include="OpenIddict.EntityFrameworkCore" Version="1.0.0-beta2-0580" />
    <PackageReference Include="OpenIddict.Mvc" Version="1.0.0-beta2-0580" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
...

 

Setup Authentication

Create new Startup.Auth.cs file which will contain the setup of authentication:

using AspNet.Security.OpenIdConnect.Primitives;
using Blog.Turnmeup.DAL.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Blog.Turnmeup.API
{
    public partial class Startup
    {



        private void ConfigureServicesAuth(IServiceCollection services)
        {

            services.AddDbContext<IdentityDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("AuthServer"));
                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            });


            // Register the OpenIddict services.
            services.AddOpenIddict(options =>
            {
                // Register the Entity Framework stores.
                options.AddEntityFrameworkCoreStores<IdentityDbContext>();

                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to
                // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.AddMvcBinders();

                // Enable the token endpoint (required to use the password flow).
                options.EnableTokenEndpoint("/connect/token");

                // Allow client applications to use the grant_type=password flow.
                options.AllowPasswordFlow();

                // During development, you can disable the HTTPS requirement.
                options.DisableHttpsRequirement();
            });

            // TODO: Inject custom validation 
            // services.AddTransient<IPasswordValidator<AppUser>, CustomPasswordValidator>();
            // services.AddTransient<IUserValidator<AppUser>, CustomUserValidator>();

            // Register the Identity services.
            services.AddIdentity<AppUser, IdentityRole>(opts => {
                opts.Password.RequiredLength = 6;
                opts.Password.RequireNonAlphanumeric = false;
                opts.Password.RequireLowercase = false;
                opts.Password.RequireUppercase = false;
                opts.Password.RequireDigit = false;
            })
            .AddEntityFrameworkStores<IdentityDbContext>()
            .AddDefaultTokenProviders();

            // Configure Identity to use the same JWT claims as OpenIddict instead
            // of the legacy WS-Federation claims it uses by default (ClaimTypes),
            // which saves you from doing the mapping in your authorization controller.
            services.Configure<IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
            });
        }


        private void ConfigureAuth(IApplicationBuilder app)
        {
            app.UseIdentity();
            app.UseOpenIddict();
        }
    }
}

 

The Startup.Auth.cs contains the partials Startup class and initialises identity environment:

  • adds the IdentityDbContext to the application services;
  • maps AppUser model class as identity class;
  • configures the use of OpenIddict;
Retrieve data from data source

The following schema shows the API implementation, from Data access layer to the API layer:

Blog.Turnmeup.API_.Identity-1

In order to retrieve user data from data source, the application will use 4 key components:

  • AppUser defines the user data source model;
  • UserRepository connects services class to the data source. It uses DbContext in order to retrieve information from database;
  • UserService  aggregates different providers: UserValidator, PasswordValidator, SignInManager; It is used by the UserController to obtain informations form database;
  • UsersController handles http requests form the client and retrieve information about users;

The following code shows the implementation of the UserController. The UserService and UserRepository are available on Github.

using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Primitives;
using AspNet.Security.OpenIdConnect.Server;
using AutoMapper;
using Blog.Turnmeup.API.Models.Users;
using Blog.Turnmeup.DL.Infrastructure.ErrorHandler;
using Blog.Turnmeup.DL.Models;
using Blog.Turnmeup.DL.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using SignInResult = Microsoft.AspNetCore.Mvc.SignInResult;

namespace Blog.Turnmeup.API.Controllers
{
    [Route("api/[controller]")]
    public class UsersController : Controller
    {
        private readonly IUsersService _usersService;
  
        private readonly IErrorHandler _errorHandler;
     


        public UsersController(IUsersService usersService, IErrorHandler errorHandler)
        {
            _usersService = usersService;
            _errorHandler = errorHandler;
          
        }

        [HttpGet]
        public List<UserModel> Get()
        {
            return _usersService.Get().ToList();
        }

        [HttpPost("/api/[controller]/login")]
        public async Task<UserModel> Login([FromBody]LoginRequestModel loginModel)
        {

            if (!ModelState.IsValid)
            {
                throw new HttpRequestException(string.Format(_errorHandler.GetMessage(ErrorMessagesEnum.ModelValidation), "", ModelState.Values.First().Errors.First().ErrorMessage));
            }

            var user = _usersService.GetByEmail(loginModel.Email);

            if (user == null)
                throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthUserDoesNotExists));

            await _usersService.SignOutAsync();
            var result = await _usersService.PasswordSignInAsync(
                user, loginModel.Password, false, false);

            if (result.Succeeded)
            {
                return user;
            }

            throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthWrongCredentials));
        }

        [HttpGet("{email}")]
        public UserModel Get(string email)
        {
            return _usersService.GetByEmail(email);
        }


        [HttpPost("/api/[controller]/create")]
        public async Task<UserModel> Create([FromBody]CreateRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpRequestException(string.Format(
                    _errorHandler.GetMessage(ErrorMessagesEnum.ModelValidation),
                    ModelState.Values.First().Errors.First().ErrorMessage));
            }
            var user = new UserModel
            {
                UserName = model.Name,
                Email = model.Email
            };

            var result = await _usersService.Create(user, model.Password);

            if (result.Succeeded)
            {
                return _usersService.GetByEmail(model.Email);
            }
            throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthCannotCreate));
        }


        [HttpPost("/api/[controller]/delete")]
        public async Task<UserModel> Delete([FromBody] DeleteRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpRequestException(string.Format(
                    _errorHandler.GetMessage(ErrorMessagesEnum.ModelValidation),
                    ModelState.Values.First().Errors.First().ErrorMessage));
            }
            var user = _usersService.GetByEmail(model.Email);
            if (user == null)
                throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthUserDoesNotExists));


            var result = await _usersService.Delete(user);
            if (result.Succeeded)
            {
                return user;
            }

            throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthCannotDelete));
        }

        [HttpPost]
        public async Task<UserModel> Edit([FromBody] UpdateRequestModel request)
        {
            var user = _usersService.GetByEmail(request.Email);

            if (user == null) throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthUserDoesNotExists));

            var validEmail = await _usersService.ValidateUser(user);

            if (!validEmail.Succeeded)
            {
                _errorHandler.ErrorIdentityResult(validEmail);
            }

            IdentityResult validPass = null;

            if (!string.IsNullOrEmpty(request.Password))
            {
                validPass = await _usersService.ValidatePassword(user, request.Password);
                if (validPass.Succeeded)
                {
                    user.PasswordHash = _usersService.HashPassword(user,
                        request.Password);
                }
                else
                {
                    _errorHandler.ErrorIdentityResult(validPass);
                }
            }
            if (validPass != null && ((!validEmail.Succeeded || request.Password == string.Empty || !validPass.Succeeded)))
                throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthNotValidInformations));

            var result = await _usersService.Update(user);

            if (result.Succeeded)
            {
                return user;
            }

            throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthCannotUpdate));

        }

        [HttpPost, Produces("application/json")]
        public async Task<SignInResult> Token(TokenRequestModel request)
        {

            if (!ModelState.IsValid)
            {
                throw new HttpRequestException(string.Format(_errorHandler.GetMessage(ErrorMessagesEnum.ModelValidation), ModelState.Values.First().Errors.First().ErrorMessage));
            }

            var user = _usersService.GetByEmail(request.Username);
            if (user == null) throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthUserDoesNotExists));


            await _usersService.SignOutAsync();
            var result = await _usersService.PasswordSignInAsync(
                user, request.Password,false, false);

            if (!result.Succeeded) throw new HttpRequestException(_errorHandler.GetMessage(ErrorMessagesEnum.AuthCannotRetrieveToken));

            // Create a new ClaimsIdentity holding the user identity.
            var identity = new ClaimsIdentity(
                OpenIdConnectServerDefaults.AuthenticationScheme,
                OpenIdConnectConstants.Claims.Name, null);
            // Add a "sub" claim containing the user identifier, and attach
            // the "access_token" destination to allow OpenIddict to store it
            // in the access token, so it can be retrieved from your controllers.
            identity.AddClaim(OpenIdConnectConstants.Claims.Subject,
                "71346D62-9BA5-4B6D-9ECA-755574D628D8",
                OpenIdConnectConstants.Destinations.AccessToken);
            identity.AddClaim(OpenIdConnectConstants.Claims.Name, user.UserName,
                OpenIdConnectConstants.Destinations.AccessToken);


            var principal = new ClaimsPrincipal(identity);
            return SignIn(principal, OpenIdConnectServerDefaults.AuthenticationScheme);
        }
    }
}

Unit test User APIs

Obviously, we need to cover UsersController using unit tests. The following project will use xUnit and Moq as mocking framework.

Firstly, the UsersControllerTests defines two fake classes: FakeUserManager and FakeSignInManager, which will be used by the mocking framework:

using System;
using System.Threading.Tasks;
using Blog.Turnmeup.DAL.Models;
using Blog.Turnmeup.DL.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;

namespace Blog.Turnmeup.API.Tests
{
    public class FakeUserManager : UserManager<AppUser>
    {
        public FakeUserManager()
            : base(new Mock<IUserStore<AppUser>>().Object,
                  new Mock<IOptions<IdentityOptions>>().Object,
                  new Mock<IPasswordHasher<AppUser>>().Object,
                  new IUserValidator<AppUser>[0],
                  new IPasswordValidator<AppUser>[0],
                  new Mock<ILookupNormalizer>().Object,
                  new Mock<IdentityErrorDescriber>().Object,
                  new Mock<IServiceProvider>().Object,
                  new Mock<ILogger<UserManager<AppUser>>>().Object)
        { }

    }
}

 

using Blog.Turnmeup.DAL.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;

namespace Blog.Turnmeup.API.Tests
{
    public class FakeSignInManager : SignInManager<AppUser>
    {
        public FakeSignInManager()
            : base(new Mock<FakeUserManager>().Object,
                  new HttpContextAccessor(),
                  new Mock<IUserClaimsPrincipalFactory<AppUser>>().Object,
                  new Mock<IOptions<IdentityOptions>>().Object,
                  new Mock<ILogger<SignInManager<AppUser>>>().Object )
        { }
    }
}

 In order to mock ASP.NET Core Identity, create a new Test server which will solves the application dependencies:

using System;
using System.Net.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;

namespace Blog.Turnmeup.API.Tests
{
    public class TestFixture<TStartup> : IDisposable where TStartup : class
    {
        public readonly TestServer Server;
        private readonly HttpClient _client;


        public TestFixture()
        {
            var builder = new WebHostBuilder()
                .UseContentRoot($"..\\..\\..\\..\\..\\src\\Blog.Turnmeup.API\\")
                .UseStartup<TStartup>();

            Server = new TestServer(builder);
            _client = new HttpClient();
        }


        public void Dispose()
        {
            _client.Dispose();
            Server.Dispose();
        }
    }
}

 Finally, we need to mock our FakeUserManager and FakeSignInManager classes by using Moq. The mocking will be implemented by the constructor (setup) of the UserControllerTest class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Blog.Turnmeup.API.Controllers;
using Blog.Turnmeup.API.Models.Users;
using Blog.Turnmeup.DAL.Models;
using Blog.Turnmeup.DL.Infrastructure.ErrorHandler;
using Blog.Turnmeup.DL.Models;
using Blog.Turnmeup.DL.Repositories;
using Blog.Turnmeup.DL.Services;
using Microsoft.AspNetCore.Identity;
using Moq;
using Xunit;

namespace Blog.Turnmeup.API.Tests.Controllers
{
    public class UserControllerTests : IClassFixture<TestFixture<Startup>>
    {

        private IUsersRepository Repository { get; set; }

        private IUsersService Service { get; }

        private UsersController Controller { get; }

        public UserControllerTests(TestFixture<Startup> fixture)
        {

            var users = new List<UserModel>
            {
                new UserModel
                {
                    UserName = "Test",
                    Id = Guid.NewGuid().ToString(),
                    Email = "[email protected]"
                }

            }.AsQueryable();

            var fakeUserManager = new Mock<FakeUserManager>();

            fakeUserManager.Setup(x => x.Users)
                .Returns(users);

            fakeUserManager.Setup(x => x.DeleteAsync(It.IsAny<UserModel>()))
             .ReturnsAsync(IdentityResult.Success);
            fakeUserManager.Setup(x => x.CreateAsync(It.IsAny<UserModel>(), It.IsAny<string>()))
            .ReturnsAsync(IdentityResult.Success);
            fakeUserManager.Setup(x => x.UpdateAsync(It.IsAny<UserModel>()))
          .ReturnsAsync(IdentityResult.Success);


            Repository = new UsersRepository(fakeUserManager.Object);


            var mapper = (IMapper)fixture.Server.Host.Services.GetService(typeof(IMapper));
            var errorHandler = (IErrorHandler)fixture.Server.Host.Services.GetService(typeof(IErrorHandler));
            var passwordhasher = (IPasswordHasher<AppUser>)fixture.Server.Host.Services.GetService(typeof(IPasswordHasher<AppUser>));


            var uservalidator = new Mock<IUserValidator<AppUser>>();
            uservalidator.Setup(x => x.ValidateAsync(It.IsAny<UserManager<AppUser>>(), It.IsAny<AppUser>()))
             .ReturnsAsync(IdentityResult.Success);
            var passwordvalidator = new Mock<IPasswordValidator<AppUser>>();
            passwordvalidator.Setup(x => x.ValidateAsync(It.IsAny<UserManager<AppUser>>(), It.IsAny<AppUser>(), It.IsAny<string>()))
             .ReturnsAsync(IdentityResult.Success);

            var signInManager = new Mock<FakeSignInManager>();

            signInManager.Setup(
                    x => x.PasswordSignInAsync(It.IsAny<AppUser>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>()))
                .ReturnsAsync(SignInResult.Success);


            //SERVICES CONFIGURATIONS
            Service = new UsersService(Repository, mapper, uservalidator.Object, passwordvalidator.Object, passwordhasher, signInManager.Object);
            Controller = new UsersController(Service, errorHandler);
        }



        [Theory]
        [InlineData("[email protected]", "Ciao.Ciao", "Test_user")]
        public async Task Insert(string email, string password, string name)
        {
            //Arrange
            var testUser = new CreateRequestModel
            {
                Email = email,
                Name = name,
                Password = password
            };
            //Act
            var createdUser = await Controller.Create(testUser);
            //Assert
            Assert.Equal(email, createdUser.Email);
        }

        [Fact]
        public void Get()
        {
            //Act
            var result = Controller.Get();
            // Assert
            Assert.NotNull(result);
        }

        [Theory]
        [InlineData("[email protected]")]
        public void GetByEmail(string email)
        {
            //Act
            var result = Controller.Get(email);
            // Assert
            Assert.Equal(result.Email, email);
        }



        [Theory]
        [InlineData("[email protected]", "password", "Test")]
        public async Task Update(string email, string password, string name)
        {
            //Arrange
            var testUser = new UpdateRequestModel
            {
                Email = email,
                Password = password
            };

            //Act
            var updated = await Controller.Edit(testUser);
            // Assert
            Assert.Equal(email, updated.Email);
        }

        [Theory]
        [InlineData("[email protected]", "Ciao.Ciao")]
        public async Task Delete(string email, string password)
        {
            //Arrange
            var testUser = new DeleteRequestModel
            {
                Email = email,
                Password = password
            };
            //Act
            var deleted = await Controller.Delete(testUser);
            //Assert
            Assert.Equal(email, deleted.Email);
        }

        [Theory]
        [InlineData("[email protected]", "Ciao.Ciao")]
        public async Task TokenAsync(string email, string password)
        {
            //Arrange
            var testUser = new TokenRequestModel
            {
                Username = email,
                Password = password
            };

            //Act
            var updated = await Controller.Token(testUser);
            // Assert
            Assert.Equal("Test", updated.Principal.Identity.Name);
        }
    }
}

Conclusion

In conclusion, ASP.NET Core Identity is the out of box membership framework provided by ASP.NET Core. This article shows how to test the behaviour of the user authentication, you can find the complete project on GitHub.

ByAlexia Pamelov

What is Difference things between ASP.NET Core MVC and ASP.NET MVC 5

CheapWindowsHosting.com | Best and cheap ASP.NET core MVC hosting. The best way to learn what’s new in any technology is to compare with its earlier version. Here will be understanding the difference between ASP.NET Core MVC and ASP.NET MVC 5 by creating sample application and comparing project solution  structure between them.

Well we have many difference(s) between ASP.NET Core MVC and ASP.NET MVC 5 in solution structure itself, lets explore them without code been written.

ASP.NET Core is a lean and composable framework for building web and cloud applications. ASP.NET Core is fully open source.

Quick look of ASP.NET Core improvements

  • Build and run cross-platform ASP.NET apps on Windows, Mac and Linux
  • Built on .NET Core, which supports true side-by-side app versioning
  • New tooling that simplifies modern Web development
  • Single aligned web stack for MVC and Web API
  • Cloud-ready environment-based configuration
  • Integrated support for creating and using NuGet packages
  • Built-in support for dependency injection
  • Ability to host on IIS or self-host in your own process

Difference between ASP.NET Core MVC and ASP.NET MVC 5 in 10 points

Firstly create ASP.NET Core MVC application and ASP.NET MVC 5 using Visual Studio 2015 Community Edition against .NET Framework 6.

Difference 1 – Single aligned web stack for ASP.NET Core MVC and Web APIs

ASP.NET MVC 5 will give us option of choosing MVC or Web API or both while creating web application. It was because web stack for MVC 5 and Web API was not the same.

ASP.NET Core MVC now has single aligned web stack for MVC and Web API. Image below shows check box are GREYED out for MVC and Web API while MVC 5 gives option to add Web API.

difference1

Difference 2 – Project(Solution) Structure Changes

If you see ASP.NET Core MVC solution explorer on right hand side, there is no Web.config, Global.asax. Then how it deals with configuration settings, authentication and application start specific code execution.

Project.json, appsettings.json are some files which does those work of missing files from ASP.NET MVC 5. There are many changes if we look at folder by folder.

difference2

Difference 3 – ASP.NET Core MVC targets Full .NET  and .NET Core

We have being working on full .NET framework, it is amazing experience till now and will continue to be. Then what is .NET core?

.NET Core is a general purpose development platform maintained by Microsoft and the .NET community on GitHub. It is cross-platform, supporting Windows, macOS and Linux, and can be used in device, cloud, and embedded/IoT scenarios

Oh cross-platform !! Yes, now we can develop ASP.NET Core web apps against .NET core and run in either Windows or Linux or Mac.  Take a quick look at image

Wait it’s not over yet, not only we can develop in Windows OS but also in Linux, Mac using Visual Studio Code  or any other code editors like Vim, Atom, Sublime.

coreFullDotNet

Difference 4 – ASP.NET Core apps  doesn’t need IIS for hosting

Don’t get surprised, the goal of ASP.NET Core is to be cross-platform using .NET core framework. With this in mind Microsoft decided to host ASP.NET Core applications not only on IIS but they can be self hosted or use nginx web server on linux. Kestrel will be internal web server for request processing

Difference 5 – wwwroot is now place for static files

The wwwroot folder represents the actual root of the web app when running on a web server. Static files like config.json, which are not in wwwroot will never be accessible, and there is no need to create special rules to block access to sensitive files.

These static files might be plain HTML, Javascript, CSS, images, library etc.

wwwroot

In addition to the security benefits, the wwwroot folder also simplifies common tasks like bundling and minification, which can now be more easily incorporated into a standard build process and automated using tools like Grunt.

“wwwroot” name can be changed in project.json under “webroot”: “Demowwwroot”

Difference 6 – New approach to Server side and client side dependency management of packages.

Any .NET developer would be familiar that References folder holds all DLLs,  Nuget packages for particular .NET Framework, While in ASP.NET Core development in Visual Studio we can target DNX 4.5.1 and DNX Core 5.0.

Leverage the experience of working in Visual Studio IDE and deploy ASP.NET 5 applications either in Windows, Linux or Mac using .NET Core. Its Server side management of dependencies.

Client side dependency management is more important because client side has more different packages from server side. Client side will surely have jQuery, Bootstrap, grunt, any Javascript frameworks like AngularJS, Backbone etc, images, style files.

Client side package management in open source community has two great names “Bower” and “NPM”. They are part of “Dependencies”.

server-client-side

Difference 7 – Server side packages save space in ASP.NET Core

We have being using NuGet package manager to add reference to assemblies, library, framework or any third party packages. They would have being downloaded from NuGet which creates “Packages” folder in project structure.

30 sample ASP.NET Core applications, all of them use NuGet packages to reference dependencies each costly approx 70 MB disk space, so we end up nearly using 2GB disk space for storing packages even though they all are same.

Some SMART developers know this issue, they have some work around of their own.

ASP.NET Core came up with storing all the packages related to its development in Users folder and while creating ASP.NET Core applications, Visual Studio will reference them from Users folder.

Now even if you have 100 sample ASP.NET 5 applications, they all are referencing from dotnet in Users folder which is near to 400 MB as of now.

folderrefer

Difference 8 – Inbuilt Dependency Injection (DI) support for ASP.NET Core

Dependency Injection (DI) achieves loosely coupled, more testable code, its very important because its kind of coding standard.

In ASP.NET MVC 5/4 or classic ASPX based applications, we use to have separate DI containers used like Unity, AutoFac, StructureMap etc,. We had to build up our project to use DI, its additional effort.

Now in ASP.NET Core applications, dependency injection is inbuilt i.e. no setup headache for DI. Just create some services and get ready to use DI.

Infact sample Core MVC application has DI inbuilt in it, lets open “Startup.cs” and look for “ConfigureServices(IServiceCollection services)” method. Its main purpose is configuration of services like EF, Authentication, adding MVC and hand written custom services like IEmailServer and ISmsSender.

diexample

Difference 9 – User Secrets of ASP.NET Core

Many times we keep sensitive data during our development work inside project tree, often we mistaken share these secrets with other through sharing of code, accidentally adding it TFS (source control). Once in while we might have experienced this.

ASP.NET Core based applications have now concept of User Secrets; if we look at “project.json” file, we see that “userSecretsId” is present and Secret Manager tool uses this id to generate user secrets.

The Secret Manager tool provides a more general mechanism to store sensitive data for development work outside
of your project tree.

The Secret Manager tool does not encrypt the stored secrets and should not be treated as a trusted store. It is for development purposes only.

There are many differences compared to ASP.NET MVC 5/4 but without writing single of code if we can find these differences then it means Microsoft has moved much ahead in terms of making it Open Source.

ByAlexia Pamelov

How to Resolve the Registered Script Control Error in DotNetNuke

CheapWindowsHosting.com | Best and cheap DotNetNuke hosting. If you’ve made the transition from DotNetNuke 6 to DotNetNuke 7 you’ve probably discovered that the AJAX Toolkit controls don’t play nice with DotNetNuke any more.  Fortunately the Telerik AJAX controls have been bundled with DotNetNuke for version 7.  I’ve discovered that converting to the Telerik controls has been beneficial and worth the upgrade.
Still, it can be a pain getting the code right.  One particular error that I ran into today was the Registered Script Control error.  It looks something like this:

“Script control ‘{controlname}’ is not a registered script control. Script controls must be registered using RegisterScriptControl() before calling RegisterScriptDescriptors().  Parameter name: scriptControl”

DotNetNuke-Development

The error results from “stacked” AJAX controls.  Consider the following HTML

<%@ Register TagPrefix=”dnnui” Namespace=”DotNetNuke.Web.UI.WebControls” Assembly=”DotNetNuke.Web” %>
<%@ Register TagPrefix=”DNN” Namespace=”DotNetNuke.UI.WebControls” Assembly=”DotNetNuke.WebControls” %>
   <DNN:DNNTabStrip ID=”tabsProject” runat=”server” TabRenderMode=”All” Visible=”true”>
     <DNN:DNNTab runat=”server” Label-Text=”Properties” ID=”tabGeneral”>
       <dnnui:DnnAjaxPanel runat=”server” ID=”dapMain”>
         <asp:Label runat=”server” ID=”lblInfo”></asp:Label>
       </dnnui:DnnAjaxPanel>
   </DNN:DNNTab>
     <DNN:DNNTab runat=”server” Label-Text=”Properties” ID=”tabSecond”>
       <dnnui:DnnAjaxPanel runat=”server” ID=”dapSecond”>
         <asp:Label runat=”server” ID=”lblMessage”></asp:Label>
       </dnnui:DnnAjaxPanel>
   </DNN:DNNTab>
      </DNN:DNNTabStrip>

 Let’s say that the second tab (tabSecond) should only appear under certain conditions; a record was created, a particular user is logged, whatever the condition is doesn’t matter, just that the tab should appear at certain times and not appear at other times.
In the code behind the condition block might look like this:

if (condition) then
tabSecond.Visible = False
end if

 But this results in the Registered Script Control error.  Modify the condition block this way:

if (condition) then
dapSecond.EnableAJAX = False
tabSecond.Visible = False
end if

This should resolve the error

What was the issue?  I’m glad you asked.
The issue causing the error is that AJAX controls are registered with the AJAX script manager and cannot be unregistered, or moved.  Hiding an AJAX control is equivalent to moving it from the script.  In order to circumvent that we’re disabling AJAX on the control before it has a chance to be rendered and registered with the script manager.

ByAlexia Pamelov

How to Bind Data to a Label From a SqlDataSource

CheapWindowsHosting.com | Best and cheap SQL Server 2016 hosting. Label controls in ASP.NET don’t have a smart tag that allows you to select a data source, so at first glance, it is not easy to see how to bind a value returned from a SqlDataSource or AccessDataSource control to the label. Here’s how to programmatically access the data returned by such a DataSource and apply it to a non-databound control.

sql

To programmatically access the contents of a SqlDataSource or AccessDataSource control you need to explicitly call its Select() method. This method accepts a single input parameter of type DataSourceSelectArguments. This parameter can contain information regarding the filters to apply or the column to Order By. For example, when working with a sortable GridView, sorting a column calls the Select() method, and passes in a DataSourceSelectArguments instance with its SortExpression property set to the column name the user chose to sort by. If you don’t want the DataSource to sort or filter, you pass in DataSourceSelectArguments.Empty.

Depending on the DataSourceMode of the DataSource control, one of two objects are returned when the Select() method is called. If the DataSourceMode is set to DataReader, a DataReader object is returned. The type of DataReader (SqlDataReader, OleDbDataReader, OdbcDataReader etc) that is returned depends entirely on the provider type used – in other words, whether you are using the OleDb provider, SqlClient provider etc. It has nothing to do with the type of DataSource control. The examples below both query an Access database, but one uses the AccessDataSource control, and the other uses the SqlDataSource control. Both return OleDbDataReaders, because it is the OleDbProvider library that is used for the connection.

If the DataSourceMode is set to Dataset, or not set at all (which means that the default setting of Dataset is used) the object that is returned is a DataView. A DataView is like a DataTable on steroids. It exposes methods that allow you to filter and sort data, for example, and bind it. A DataView contains a collection of DataRowView objects, which represent each row in the returned results.

So, with a DataReader, you would access the values during the DataReader.Read() operation, in very much the same way as if you are using plain ADO.NET code, whereas with the DataSet, you would need to create an object of the appropriate type – DataView, then iterate the DataRowView collection to access the values. In this, the code is remarkably similar to accessing values directly from a DataSet’s table collection using plain ADO.NET.

The code below shows the contents of an aspx file, which contains two label controls, and two SqlDataSource controls. Each SqlDataSource control has its DataSource mode set to alternative values – DataSet and DataReader, and both of them have an OnSelecting event defined in which the value of the EmployeeID parameter is assigned:

<asp:Label ID="Label1" runat="server" /> <asp:Label ID="Label2" runat="server" />

<asp:SqlDataSource
    ID="SqlDataSource1"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
    DatasourceMode="DataSet"
    SelectCommand="SELECT [LastName], [FirstName] FROM [Employees] WHERE ([EmployeeID] = ?)"
    OnSelecting="SqlDataSource1_Selecting">
    <SelectParameters>
        <asp:Parameter Name="EmployeeID" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

 

<asp:SqlDataSource
    ID="SqlDataSource2"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
    DatasourceMode="DataReader"
    SelectCommand="SELECT [LastName], [FirstName] FROM [Employees] WHERE ([EmployeeID] = ?)"
    OnSelecting="SqlDataSource2_Selecting">
    <SelectParameters>
        <asp:Parameter Name="EmployeeID" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

 The following code snippet shows the aspx.cs file contents, where the parameter values are set in the Selecting event handler. In the Page_Load method, the data returned by each of the Sql DataSource controls is accessed and a value consigned to a label. The method of access depends on the DataSource mode, but is identical for both SqlDataSource and AccessDataSource:

[C#]
protected void Page_Load(object sender, EventArgs e)
{

    DataView dvSql = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
    foreach (DataRowView drvSql in dvSql)
    {
        Label1.Text = drvSql["FirstName"].ToString();
    }

    OleDbDataReader rdrSql = (OleDbDataReader)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
    while (rdrSql.Read())
    {
        Label2.Text = rdrSql["LastName"].ToString();

    }
    rdrSql.Close();
}



protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["EmployeeID"].Value = 2;
}

protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["EmployeeID"].Value = 2;
}

[VB]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

Dim dvSql As DataView =
    DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
    For Each drvSql As DataRowView In dvSql
        Label1.Text = drvSql("FirstName").ToString()
    Next

Dim rdrSql As OleDbDataReader =
    DirectCast(SqlDataSource2.Select(DataSourceSelectArguments.Empty), OleDbDataReader)
    While rdrSql.Read()

        Label2.Text = rdrSql("LastName").ToString()
    End While
    rdrSql.Close()
End Sub

Protected Sub SqlDataSource1_Selecting(ByVal sender As Object,
    ByVal e As SqlDataSourceSelectingEventArgs)
    e.Command.Parameters("EmployeeID").Value = 2
End Sub

Protected Sub SqlDataSource2_Selecting(ByVal sender As Object,
    ByVal e As SqlDataSourceSelectingEventArgs)
    e.Command.Parameters("EmployeeID").Value = 2
End Sub

 When using this technique with Sql Server – or more specifically the SqlClient provider, change OleDbDataReader to SqlDataReader in the above code. Happy Coding.

ByAlexia Pamelov

Tips Global Routes for ASP.NET Core MVC

CheapWindowsHosting.com | Best and cheap ASP.NET Core MVC. Want to detect part of the url for every single action in your asp.net core mvc app? It’s useful for determining API versions, detecting user accounts and it’s quite easy to do.

Today we’re going to prepend api/{mode} to all routes in our api. {mode} will contain “test” or “live” and represents which environment we want to use. This saves us from writing it on all our controllers and we’ll setup a property in our BaseController so all of our controllers have a handy shortcut.

You need an IApplicationModelConvention

ASP.NET Core MVC has been written to be very customisable. The handy IApplicationModelConvention interface lets you make changes to the mvc application and gives you access to read the Controllers, Filters and a few other things.

The approach we’ll take is to read all of our controller’s routes and either combine our prefix with any existing routes, or create new routes where one doesn’t exist.

Here’s the completed code:

public class ModeRouteConvention : IApplicationModelConvention
{
    public void Apply(ApplicationModel application)
    {
        var centralPrefix = new AttributeRouteModel(new RouteAttribute("api/{mode}"));
        foreach (var controller in application.Controllers)
        {
            var routeSelector = controller.Selectors.FirstOrDefault(x => x.AttributeRouteModel != null);

            if (routeSelector != null)
            {
                routeSelector.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(centralPrefix,
                    routeSelector.AttributeRouteModel);
            }
            else
            {
                controller.Selectors.Add(new SelectorModel() { AttributeRouteModel = centralPrefix });
            }
        }
    }
}

 You add it to your application using:

// Add framework services.
services.AddMvc(options => {
    options.Conventions.Insert(0, new ModeRouteConvention());
});

What’s going on?

Ok first we’ll look at the ModeRouteConvention class. The AttributeRouteModel class is pretty much just a wrapper on the [Route()] attribute, providing slightly more information and allowing for easy combination of routes.

Next, we check if the controller already has a Route attribute. If it does, we use the convenient CombineAttributeRouteModel method to combine our prefix with the existing route, remembering to put our route first. If one doesn’t exist we just use our one instead.

Add Mode Property to Base Controller

Next we want to automatically parse the mode and expose a property for all of our controllers to use. We’ll start by writing the base controller.

publicclassBaseController:Controller{protectedboolIsLive{get{var mode =this.RouteData.Values["mode"]asstring;return mode?.ToLower()=="live";}}}

Now we can easily check if we’re in live mode or not from our controllers.

[Route("[controller]")]publicclassPaymentsController:BaseController{[HttpPost("process/{id}")]public async Task<IActionResult>ProcessPayment(string id){if(IsLive){// Send to the real bankreturnJson(_paymentsProcessor.Process(id));}else{// Just pretend it workedreturnJson(true);}}}

Looking at our controller’s Route Attribute you can a value of [controller]. MVC replaces this with the name of the controller. The example action endpoint is a POST method with a route of “process” that also contains the ID. We check if the request is for the live environment or the test one and then we react accordingly.

The final urls look like this:

  • Test: http://example.com/api/test/payments/process/pmt_1234
  • Live: http://example.com/api/live/payments/process/pmt_1234