How To Select Insert, Update And Delete With ASP.NET MVC

How To Select Insert, Update And Delete With ASP.NET MVC

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. In all the above articles I have explained about ASP.Net MVC. Now I think you are clear about ASP.Net MVC and creating simple ASP.Net MVC applications. Whenever we are developing the applications we are related to a database and in the database driven applications we need to perform CRUD operations. On various blogs and sites you will find CRUD operation samples about ASP.Net MVC. But on many the sites I have seen they are all using Entity Framework to perform the CRUD. Since it is the standard, we have to follow it while developing ASP.Net MVC applications instead of using DataSet, Command, Connection, DataAdapter and DataReader. But in many cases we have to use these ADO.Net 2.0 operations. In this  article we will perform all the operations using ADO.NET instead of the ADO.NET Entity Framework. But use these ADO.Net only where you need to else use the ADO.Net Entity Framework only. So let’s start performing CRUD using ADO.Net.

Step 1 : Create the table in your database with the following script.

Step 2 : Now create a new ASP.Net MVC3 Web application with an empty template. This will create one predefined structure with Controllers, Modes and Views folders. All these folders are empty; now we have to add the content to these folders.

Step 3 : As you know, first we have to create a controller so let’s add a new controller with the name Home in the controllers folder. Now our empty controller is ready with an Index method. On the index method we will call the dataset from the database to display the existing Authors in our table. For this we will create a model which will return the dataset, then we will display this data on the view through the Index method of the Home controller. So let’s create one model i.e. class in Models folder with the name SelectModel and write the following code in it to retrieve the data from the database.

In the selectModel class we have one method called GetAllAuthors which returns the dataset of all authors. Now modify your Index method of Home Controller like Entity Framework.

In the above line of code we called the GetAllAuthors method from SelectModel which will return the dataset object and simply we put this dataset in the viewbag. As you know in C# 4.0 we have dynamic programming; you can see one excellent example with viewbag. Here we have written ViewBag.AuthorList which will create dynamically on Author list on runtime for us. Still now we are finished up to calling the dataset and transferring it to the view but still we don’t have any
view so right-click in the Index method and add a new empty view to display our authorlist and write the following markup to display the results.

In the above markup we are displaying our authorlist by creating a HTML table with having Edit and Delete links and lastly having one more ActionLink to add a new author record.

Step 4 : At this stage we are ready with our Index or select operation; now we can add more methods to our Home Controller to perform Edit, Update and Delete operation so let’s start with adding a new record i.e. inserting a new record in the database. In the last step we added an Add New Author ActionLink with Add method so we need to add two more methods in our Home Controller, one for displaying the fields and another for inserting the values; but before that we need to create our model. So add one Model class called InsertModel in your models folder and write the code like below.

The Above code contains some properties with attributes that are used for validation on our view as well as the InsertModel contains Insert method for inserting values in database. Now our InsertModel is ready, so you can add two methods for adding the record in the database add one ADD method with [HttpGet] and a second ADD method with [HttpPost] attributes. These attributes are all of you known. So create two add methods like below.

In the above code, first one add method simply returns the view to take some input from the user and the second add method gets the values from the view and validates it and inserts these values into the database by calling the Insert method of InserModel.

Step 5 : Still now we have only finished Select and Insert operations; now we will see Edit and update. In step3 we have added one edit link bind with AuthorId. On the basis of this AuthorId we will Edit the record and update the record in the database. As in previous steps we need one more Model class so add a Model class called UpdateModel and write the code like below.

In the above code we have properties and one Update method to update the record in the database. In all ModelClasses you can see I’m using ADO.Net only.
Now we have our model class ready so we can add some methods to perform Edit and update operations in our Home Controller so add two more methods called Edit for editing and updating the records like below.

In the above code you can see first the edit method performs some logic to call the specified id record from the database and display this record on the view and the second Edit method performs the update operations.

Step 6 : Now our last operation still remains, i.e. delete; so to delete, add one more model called DeleteModel and write the following code which contains only a delete method to delete the record of the specified AuthorId from the database

In Step3 we have added one ActionLink with delete and given the authorid to it for deleting the specified authorid record from the database. So now we can add one Delete Method in our Home Controller, so add it and write the following code to call the delete method of the DeleteModel to delete the record.

Now we have completed all our operations. Now you can run the application and can perform all the Select, Insert, Update and Delete operations.

Conclusion: In this article we have seen how to add, edit, update and delete the records using ADO.NET in ASP.Net MVC. I hope you enjoyed this article.

Securing Access to Files using the ASP.NET IHttpHandler

Securing Access to Files using the ASP.NET IHttpHandler

CheapASPNETHostingReview.com | Best and cheap ASP.NET hosting. The IHttpHandler interface is an underused interface in my humble opinion. It gives the developer the ability to process HTTP requests with custom HTTP handlers. Have you ever wondered why aspx pages are processed by ASP.NET?

To answer that question, you need to open the Application Configuration dialog in IIS. This example uses IIS 6. The Application Configuration is located on the Home Directory tab in IIS. Clicking the configuration button opens the Application Configuration dialog shown below. Highlighted is the .aspx Application Extension. The executable path for this extension is c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll.

When IIS receives a request and the extension is .aspx, it directs the request to the aspnet_isapi.dll. The aspnet_isapi.dll will check the web.config file located in C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG to see what class will handle the request. The following code is a small extract of the web.config file:

In the code above, the httpHanders section has an entry for *.aspx. All *.aspx requests will be processed by the System.Web.UI.PagehandlerFactory class.
You as the developer have the ability to process HTTP requests with customer HTTP handlers. In the following article I’ll take you through a typical business scenario where custom HTTP handlers are great. Here are the business rules we must follow:

  • ceo files can only be viewed by the CEO
  • The CEO must be logged into the website

Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application. C# users can name the application as ‘HttpHandler’. VB.NET users can call it ‘HttpHandlerVB’

  • Right click the project and choose Add > New Folder. Rename the folder to SecuredFiles. This is where the CEO files will be. Add a new text file to this folder and rename the extension to *.ceo.
  • Right click the project and choose Add > New Item > Generic Handler.

Open the CustomHandler.ashx file and add the following code:
C#

The CustomHandler class implements the IHttpHandler interface. Implementing this interface allows you to create custom HTTP handlers. The two methods that we must implement are ProcessRequest and IsReusable. ProcessRequest accepts the HttpContext as a parameter, which contains all the information about the HTTP request. We want this HTTP handler to check HttpContext to ensure the HTTP request is from an authenticated user and they’re username is CEO.
Next you must update the web.config file and add a new entry to the httpHandlers section. The following xml is required:

This tells our website that if there are any HTTP requests for pages that have a *.ceo extension, they will be processed by the WebApplication1.CustomHandler class.
To complete this demo you’ll need to update the web.config file to use Forms authentication. The following xml is required:

Right click on the project and choose Add > New Item > Web Form. Add a Login control to the page and add the following code to the Authenticate event:
C#

The authentication would normally be verified against a database, but for this example we’ll let everyone through. Type in any username and password of your choice. Once the user has logged in they’ll be redirected to the Default.aspx page. There is a link to the CEO file. Clicking on that link will direct the HTTP request to the CustomerHandler class. If the user has logged in as CEO (username: Ceo) they will be able to download the file. If not, they will see a message on the screen that says No access unless you’re the CEO!!!.
HTTP handlers are a great way to write generic functions to handle HTTP requests. You can utilize HTTP handlers to process both GET and POST requests. I’ve found them useful for the scenario above and I’m positive you can take this example and come up with other ways to utilize this powerful tool.

AD Authentication ASP.NET Core 2.0

AD Authentication ASP.NET Core 2.0

CheapASPNETHostingReview.com | ASP.NET Core and Azure AD have been kind of my passion for the last year. Naturally with ASP.NET Core 2.0 coming out I wanted to see what had changed in the area of authentication. I made an article on enabling Azure AD authentication in ASP.NET Core 1.0 almost a year ago.

ASP.NET Core 2.0 authentication changes

Many things have changed in 2.0. Authentication is one of them. I will go through changes to other parts in future articles.

In ASP.NET Core 1.X, authentication middleware were registered in the Configure method in the Startup class. That has had a major change. There is now only a single middleware that you add:

Other middleware, like cookie authentication middleware need not be added.

Instead, authentication is now done through services. You will add them in ConfigureServices. Here for example we add cookie authentication.

Another thing that has changed is that we can now define the default authentication/challenge/sign-in handler in one place. You can see an example of the new approach in the next section.

Setting up Azure AD authentication in Startup

In an MVC application that wants to use Azure AD authentication, we need two authentication handlers:

  1. Cookies
  2. Open Id Connect

We can add them to the service collection like this:

Cookies is responsible for two things:

  1. Signing the user in (creating the authentication cookie and returning it to the browser)
  2. Authenticating cookies in requests and creating user principals from them

Open Id Connect is responsible for only one thing really: Responding to challenges from [Authorize] or ChallengeResult returned from controllers.

When it receives a challenge, it sends the user to authenticate against the identity provider (in this case Azure AD). When the user gets redirected back to the app, it does a multitude of things to authenticate the returned info, and then requests the default sign-in handler to sign the user in.

So let’s configure the default handlers:

Note there that by default, cookie authentication handles authentication and sign-in. Open Id Connect only handles challenges. In 1.X, these would have been defined in the middleware options (except for the default sign-in middleware).

Then we need to add the authentication middleware to Configure as mentioned before:

For basic scenarios, we are actually almost done. Just one thing missing, the configuration!

Configuring Open Id Connect automatically/slightly manually

Previously we added Open Id Connect authentication like this:

If you check it’s documentation, it says:

Adds OpenIdConnect authentication with options bound against the “OpenIdConnect” section from the IConfiguration in the service container.

So, it expects you have a section like this e.g. in appsettings.json:

And in user secrets:

These will automatically map to properties in OpenIdConnectOptions.

So, configuration? Done.

Now, in some cases you want to e.g. define handlers that do something when you receive the authorization code.

There’s just one small thing. When you specify handlers like this:

Configuration is not bound in this case. You can do that however just by adding one line of code:

If you just need the authentication and no access tokens to APIs etc., the first option with no arguments that auto-binds to the configuration is best.

Otherwise, at least bind options from configuration so you don’t have to type configuration keys manually.

Here is a more complete example of configuring Open Id Connect:

We first bind the configuration section “Authentication” to the Open Id Connect options. Then we setup an event handler for when we get an authorization code from Azure AD. We then exchange it for an access token for Microsoft Graph API.

The token cache class that I made here uses the distributed cache to store tokens. In development that would be a memory-backed cache, but in production it could be backed by a Redis cache or an SQL database.

Now while the handler can acquire an access token, I prefer using ADAL/MSAL as tokens then get cached, and it handles token refresh automatically.

We also setup an exception filter for MVC so that if ADAL token acquisition fails (because the token was not found in cache), we redirect the user to Azure AD to get new tokens. The reason why we use the absolute newest bits (at the time of writing) in the sample app on GitHub, is because Automatic ChallengeBehavior is finally gone in these versions :) Now when you return a ChallengeResult, you get the challenge behaviour every time. If you want to return a 403, you return a ForbidResult.

Best SEO Friendly URL’s for ASP.NET Core 2.0

Best SEO Friendly URL’s for ASP.NET Core 2.0

CheapASPNETHostingReview.com | Best and cheap ASP.NET core 2.0 hosting. For some reason there are not a lot of Search Engine Optimization (SEO) blog posts or projects out there. Taking a few simple steps can make your site rank higher in Google or Bing search results so it’s well worth doing.

What is an SEO Friendly URL?

Essentially you want a simple short URL that tells the user what they are clicking on at a glance. It should also contain keywords pertaining to what is on the page for better Search Engine Optimization (SEO). In short, a page will appear higher up in search results if the term a user searches for appears in the URL. Your URL should look like this:

SEO-Friendly-URL

The URL contains an ID for a product and ends with a friendly title. The title contains alphanumeric characters with dashes instead of spaces. Note that the ID of the product is still included in the URL, to avoid having to deal with two friendly titles with the same name.

If you elect to omit the ID, then you have to do a lot of footwork to make things work. Firstly, you have to use the title as a kind of primary key to get the product data from your database and secondly, you also have to figure out what to do when there are two pages with the same title. Each time you want to create a new title, you have to scan your data store to see if the title already exists and if it does either error and force the creation of a different title or add make it unique by adding a number on the end. This is a lot of work but does produce a nicer URL, the choice is yours.

How to Build One

Take a look at the controller action below. It is a very simple example of how to use SEO friendly URL’s. In our example we have a product class which has a ID and title properties, where the title is just the name of the product.

All the work is done by the FriendlyUrlHelper which turns the product title which may contain spaces, numbers or other special characters (which would not be allowed in a URL without escaping them) into a lower-kebab-case title.

This generated friendly title is compared with the one that is passed in and if it is different (Someone may have omitted the friendly title or mis-spelled it) we perform a permanent redirect to the product with the same ID but now with the friendly title. This is important for SEO purposes, we want search engines to only find one URL for each product. Finally, if the friendly title matches the one passed in we return the product view.

The FriendlyUrlHelper

The FriendlyUrlHelper was inspired by a famous StackOverflow question ‘How does Stack Overflow generate its SEO-friendly URLs?‘. The full source code for it is shown below.

The difference between my version and the one in the StackOverflow answer is that mine optionally handles non-ASCII characters using the boolean remapToAscii parameter. This parameter remaps special UTF8 characters like ‘è’ to their ASCII equivalent ‘e’. If there is no equivelant, then those characters are dropped. All modern browsers except Internet Explorer and Edge display the ‘è’ correctly. Older browsers like Internet Explorer percent encode these international characters so they are displayed as’%C3%A8′. What you set this to depends on whether your target users are English speakers and if you care about supporting IE and Edge. I must say that I was hoping Edge would have added support so that remapToAscii could be turned off by default but I’m sorely dissapointed.

Using the third parameter you can specify a maximum length for the title with any additional characters being dropped. Finally, the last thing to say about this method is that it has been tuned for speed.

Where Can I Get It?

This is a great little snippet of code to make your URL’s a human readable, while giving your site an SEO boost. It doesn’t take much effort to use either. This helper class is available in the Boilerplate.AspNetCore NuGet package or you can look at the source code in the ASP.NET MVC Boilerplate Framework GitHub page.

Deploy ASP.NET Core to IIS & How ASP.NET Core Hosting Works

Deploy ASP.NET Core to IIS & How ASP.NET Core Hosting Works

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core 1.0 hosting. In this article, we will review how to deploy an ASP.NET Core application to IIS. Deploying an ASP.NET Core app to IIS isn’t complicated, but ASP.NET Core hosting is a little different than ASP.NET.

How to Configure Your ASP.NET Core App For IIS

The first thing you will notice when creating a new ASP.NET Core project is they are actually console applications. Your project now contains a Program.cs file just like a console app would have and it contains the following code:

What is the WebHostBuilder?

All ASP.NET Core applications require a WebHost object that essentially serves as the application and web server. WebHostBuilder is used to configure and create the WebHost. You will normally see UseKestrel() and UseIISIntegration() in the WebHostBuilder setup code.

What do these do?

  • UseKestrel() – This registers the IServer interface for Kestrel as the server that will be used to host your application. In the future, there could be other options, including WebListener which will be Windows only.
  • UseIISIntegration() – This tells ASP.NET that IIS will be working as a reverse proxy in front of Kestrel. This then specifies some settings around which port Kestrel should listen on, forwarding headers, and other details.

If you are planning to deploy your application to IIS, UseIISIntegration() is required

What is AspNetCoreModule?

You may have noticed that ASP.NET Core projects create a web.config file. This is only used when deploying your application to IIS. It registers the AspNetCoreModule as an HTTP handler.

Default web.config for ASP.NET Core:

If you are planning to deploy your application to IIS, UseIISIntegration() is required

Default web.config for ASP.NET Core:

AspNetCoreModule handles all incoming traffic to IIS and acts as the reverse proxy that knows how to hand the traffic off to your ASP.NET Core application. You can view the source code of it on GitHub. It also ensures that your web application is running. It is responsible for starting your process up.

Install .NET Core Windows Server Hosting Bundle

Before you deploy your application, you need to install the .NET Core hosting bundle for IIS. This will install the .NET Core runtime, libraries, and the ASP.NET Core module for IIS.

After installing it, you may need to do a “net stop was /y” and “net start w3svc” to ensure all the changes are picked up for IIS.

Steps to Deploy ASP.NET Core to IIS

Before you deploy, you need to make sure that WebHostBuilder is configured properly to use Kestrel and IIS. Your web.config should also exist and look similar to our example above.

Step 1: Publish to a File Folder

how-to-deploy-asp-net-core-to-iis-10614

Step 2: Copy Files to Preferred IIS Location

Now you need to copy your publish output to where you want the files to live. If you are deploying to a remote server, you may want to zip up the files and move to the server. If you are deploying to a local dev box, you can copy them locally.

For my example, I am copying the files to C:\inetpub\wwwroot\AspNetCore46

You will notice that with ASP.NET core there is no bin folder and it potentially copies over a ton of different .NET dlls. Your application may also be an EXE file if you are targeting the full .NET Framework. My little sample project had over 100 dlls in the output.

img_58ee6a96d49de-1024x631

Step 3: Create Application in IIS

First, create a new IIS Application Pool. You will want to create one under the .NET CLR version of “No Managed Code“. Since IIS only works as a reverse proxy, it isn’t actually executing any .NET code.

Second, create your new application under your existing IIS Site, or create a new IIS site. Either way, you will want to pick your new IIS Application Pool and point it at the folder you copied your ASP.NET publish output files to.

img_58ee6b7a8b7e4

Step 4: Load Your App!

At this point, your application should load just fine. If it does not, check the output logging from it. Within your web.config file you define how IIS starts up your ASP.NET Core process. Enable output logging by setting stdoutLogEnabled=true and you may also want to change the log output location as configured in stdoutLogFile. Check out the example web.config before to see where they are set.

Advantages of Using IIS with ASP.NET Core Hosting

Microsoft recommends using IIS with any public facing site for ASP.NET core hosting. IIS provides additional levels of configurability, management, security, logging, and many other things. Check out my blog post about Kestrel vs IIS to see a whole matrix of feature differences. It goes more in depth about what Kestrel is and why you need both Kestrel & IIS.

One of the big advantages to using IIS is the process management. IIS will automatically start your app and potentially restart it if a crash were to occur. If you were running your ASP.NET Core app as a Windows Service or console app, you would not have that safety net there to start and monitor the process for you.

Using multiple hosting environments on the same machine in ASP.NET Core

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core hosting. This short post about how to set the hosting environment in ASP.NET Core.

However, if this is a capability you think you will need, you can use a similar approach to the one I use in that post to set the environment using command line arguments.

This approach involves building a new IConfiguration object, and passing that in to the WebHostBuilder on application startup. This lets you load configuration from any source, just as you would in your normal startup method, and pass that configuration to the WebHostBuilder using UseConfiguration. The WebHostBuilder will look for a key named "Environment" in this configuration, and use that as the environment.

For example, if you use the following configuration.

 You can pass any setting value with this setup, including the “environment variable”:

This is fine if you can use command line arguments like this, but what if you want to use environment variables? Again, the problem is that they’re shared between all apps on a machine.

However, you can use a similar approach, coupled with the UseEnvironment extension method, to set a different environment for each machine. This will override the ASPNETCORE_ENVIRONMENT value, if it exists, with the value you provide for this application alone. No other applications on the machine will be affected.

To test this out, I added the MYCOOLPROJECT_ENVIRONMENT key with a value of Staging to the launch.json file VS uses when running the app:

Running the app using F5, shows that we have correctly picked up the Staging value using our custom environment variable:

With this approach you can effectively have a per-app environment variable that you can use to configure the environment for an app individually.

Summary

On shared hosting, you may be in a situation when you want to use a different IHostingEnvironment for multiple apps on the same machine. You can achieve this with the approach outlined in this post, building an IConfiguration object and passing a key to WebHostBuilder.UseEnvironment extension method.

How To Route Constraints In ASP.NET Core

How To Route Constraints In ASP.NET Core

logo

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core. Route Constraints can be a handy way to distinguish between similar route names, and in some cases, pre-filter out “junk” requests from actually hitting your actions and taking up resources. A route constraint can be as simple as enforcing that an ID that you expect in a URL is an integer, or as complicated as regex matching on strings.

An important thing to remember is that route constraints are not a way to “validate” input. Any server side validation you wish to occur should still happen regardless of any route constraints set up. Importantly, know that if a route constraint is not met than a 404 is returned, rather than a 400 bad request you would typically expect to see from a validation failure.

Type Constraints

Type constraints are a simple way to ensure that a parameter can be cast to a certain value type. Consider the following code :

At first glance you might assume that if you called “/api/controller/abc” that the route would not match – It would make sense since the id parameter is an integer. But infact what happens is that the route is matched and the id is bound as 0. This is where route constraints come in. Consider the following :

Now if the id in the URL is not able to be cast to an integer, the route is not matched.

You can do this type of constraints with int, float, decimal, double, long, guid, bool and datetime.

Size Constraints

There are two types of “size” constraints you can use in routes. The first is to do with strings and means you can set a minimum length, max length or even a range.

This sets a minimum length for the string value. You can also use maxlength to limit the length.

Alternatively, you can set how many characters a string can be within a range using the length property.

While that’s great for string variables, for integers you can use the min/max/range constraints in a similar fashion.

Regex Constraints

Regex constraints are a great way to limit a string input. By now most should know exactly what regex is so there isn’t much point doing a deep dive on how to format your regex, just throw it in as a constraint and away it goes.

It is worth noting there for whatever reason, the .NET core team added another handy “quick” way of doing alpha characters only instead of regex. There you can just use the constraint of “alpha”.

Developing a Webservice in DotNetNuke

Developing a Webservice in DotNetNuke

CheapASPNETHostingReview.com | Best and cheap DotNetNuke hosting. I have recently been assigned to built a DotNetNuke web service to permit a windows application (or any sort of net client for instance) the flexibility to control DotNetNuke person accounts (create, change roles, delete, retrieve e mail address, and so forth.)

Since I had a tough time locating an accurate code sample or documentation that really applies to DotNetNuke 7.3 and accessing it without having being earlier logged in to DotNetNuke, it absolutely was difficult to constructed anything at all. I ultimately found out how to do it properly so I hard I would put my attempts to some use and write a blog publish explaining how you can get it done step by stage.

That said, let’s begin by the fundamentals and just create a publicly available web services that permits anybody to ping the net service and acquire a pong again. For that we are going to use the new DotNetNuke 7 Providers Framework which makes it fairly simple should you know how to utilize it.

In order to create a net support that will work within DotNetNuke 7, you will need to fireplace up Visual Studio and create a class Library project (c# or VB but all illustrations listed here will be in c#).

That done, we will then reference some needed DotNetNuke 7 required libraries (making use of the Add Reference dialog box), here’s the list:

Then we also need to reference the System.Web class from the .NET tab of the same dialog box.

Finally, we neet to set the output path of the project to the DotNetNuke bin directory and we are ready to code.

Here is the code, the explanations follow:

  1. We merely start with some using statements for our needs as demonstrated previously mentioned
  2. We develop a namespace for our service and no matter what name we use listed here will be part of the url. I utilized MyService just for this instance but use any name which makes perception for your services.
  3. Now we create a public class for our controller. You’ll be able to create numerous controllers if you want to and the controller is just a bunch of related actions that make feeling to group with each other. In my genuine project I have a PingController for testing functions, a UsersController for almost any steps that relate to user accounts and so forth. Just utilize a identify that makes feeling because it will even present up in the url. Two things for being careful right here:
    • The identify of one’s controller should end using the term Controller but only what will come just before it will show inside the url, so for PingController, only Ping will show in the url route.
    • It should inherit DnnApiController so it’ll use the DotNetNuke Providers Framework.
  4. Then we create the actual motion, inside our case, PublicPing. It’s just a straightforward technique which return an HttpResponseMessage and may have a handful of characteristics. By default the brand new providers framework will respond only to host consumers and you also must explicitly enable other access rights if necessary, in this case the [AllowAnonymous] helps make this technique (or action if you prefer) obtainable to anyone with out credentials. The next attribute, [HttpGet] can make this action reply to HTTP GET verb, which can be usually used when requesting some date in the web server.
  5. Finally in that action, you insert whatever code you action needs to do, in this case just return the string “Pong!”, just remember that you should return an HttpResponseMessage rather than a string or int or other item.

Ok so our controller and motion is done, now we just need to map that to an actual URL and that exactly what the final portion of the earlier code does. In essence this code tells DotNetNuke to map a specific url pattern for the techniques outlined in your course. You can use that code as is simply replacing MyService by no matter what your support title is.

Testing:

That is all there is certainly to it, your services is prepared! To test it, first compile it, then just navigate to http://yourdomain/DesktopModules/MyService/API/Ping/PublicPing and you should see “Pong!” inside your browser like a response.

Passing parameters

Ok, so the basic code above is working but it doesn’t do anything useful. Lets add something more useful by creating an action that will give us the email address for a specific user id.

Again, here’s the code and the explanations will follow (place the code inside the same namespace as the previous one):

Initial we build a UsersController course which will hold all actions related to person accounts, it isn’t completely required, you’ll be able to have numerous steps within the same controller, nonetheless because this motion is not in any respect connected to our PingController, let’a create a new one more descriptive.

We then create a GetEmail motion (method) which will accept a userid parameter. The [RequireHost] parameter listed here will make it accessible only to host customers, we are going to see afterwards other authentication options.

The code inside the approach alone is fairly significantly self explanatory. The only interesting factor to notice listed here is the fact that because our course inherits DnnApiController, we already have a PortalSettings item obtainable. That is the big benefit of producing use of the DotNetNuke Solutions Framework. You’ll have a ModuleInfo object to represent your module (if there is 1 using the identical identify as your support, which can be not essential such on this scenario), a PortalSettings object that signifies the portal at the domain title utilized to accessibility the support (portal alias) and at last a UserInfo item symbolizing the person that accessed the web services.

Testing:
If we now navigate to http://yourdomain/MyService/API/Users/GetEmail?userid=2 you need to receive the email tackle back again from the server unless of course obviously that userid does not exist, ensure that you check having a userid that truly exists for that portal. Should you exactly where not formerly linked having a host account, you then will probably be requested for qualifications.

Limiting access to particular roles

Alright, that actually works however, you need to give host qualifications to anyone needing to make use of your webservice. To avoid which you can change [RequireHost] by [DnnAuthorize(StaticRoles=”Administrators”)] which can limit access to administrators. Much better however, you nevertheless must provide them with an admin account. So the easy method to give only constrained entry would be to create a brand new role in DotNetNuke only for your internet services and substitute Administrators by that specific function title within the authentication parameter.

Utilizing HttpPost : (reply to a comment down bellow)

To answer Massod comment bellow, it’s nearly exactly the same thing however, you have to develop an object to contain the posted information.

Let’s make a easy ping that makes use of Submit, very first we need to create an object which will contain the posted info this sort of as:

Then we create the service method something like this:

note that normally, a post would only return ok and no message, I am just doing this so we can test here.

Now since this is a POST verb, we can’t test it by only using url parameters, we need to make an html file with a form to test it out. It would be someting like this:

The crucial thing to not right here is you can not just develop your Publish technique taking a string even when this can be only what you require, you do must create an object which will get your parameters.

Also never overlook that this is only for tests, you usually do not need to make this publicly accessible, you’d probably usually use yet another parameter than [AllowAnonymous] such as [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)] and [ValidateAntiForgeryToken] unless you truly want that for being public.

.NET Core And SQL Server In Linux Docker Containers

.NET Core And SQL Server In Linux Docker Containers

CheapASPNETHostingReview.com | Best and cheap ASP.NET core hosting. Throughout the years, we have been using ASP.NET and SQL Server mainly on Windows. Now the times have changed! You can now develop the same ASP.NET (with more optimized runtime and libraries) apps with the same SQL Server Database Engine on Linux and this is what I want to show you here.

To make things more interesting, I will take Docker, a leading container technology platform, into account for this demo. We have an Azure Linux VM (Ubuntu 16.04) where Docker is installed. We will spin up an ASP.NET Core container and a SQL Server container in a separate Docker user-defined network, accessing the application container from the VM’s public IP address and SQL Server container from SSMS on our local Windows Machine.

image001

Getting Started

I have a Linux Ubuntu 16.04 VM in Azure with Docker installed. I will SSH into the machine and generate a default ASP.NET Core 1.0 LTS project with SQL Server Entity Framework Core provider installed. You can do so manually either using dotnet CLI or Yeoman Generators.

The default ASP.NET Core project uses Identity for authentication\authorization. Identity, in turn, depends upon an EFCore provider which is in our case SQL Server.

Now, we do the following 3 important things here.

  1. Pull down the official Microsoft SQL Server image from Docker Hub
  2. Change the Connection String of the application such that it points to the SQL Server Docker container
  3. Dockerize the application

Pull down the official SQL Server Docker image from the terminal as,

docker pull microsoft/mssql-server-linux:latest

Next, change the connection string of the ASP.NET Core application in the appsettings.json file using Vim or Nano editor at the root as,

Notice the Server name in the connection string. It should not be the localhost if you want to run the application inside the Docker container as in our case. The Server name must match with the SQL Server custom container name when we run it. This is how Services are discovered by the Docker Engine.

Also, make sure that the “Trusted_Connection” is set to false as it forces the integrated security inside the Linux which is not supported.

Now finally, create the Dockerfile to build the Docker image of our application at the root as,

touch Dockerfile

With the contents,

And build the image with any name (aspnetcoreapp in our case) by the typing in the terminal.

docker build -t aspnetcoreapp .

It will start restoring the NuGet packages, set up the environment and build the Docker image for the application.

We now have the SQL Server and ASP.NET Core Docker images. The next thing we need to do is to configure the Azure VM’s Network Security Group (NSG) to open port 80 to allow HTTP traffic from the Internet and the port 1433 to allow our local SQL Server Management Studio to connect to the SQL Server container running inside the Linux VM.

My Linux VM is provisioned using ARM model this is why we need to configure the NSG which was created with the VM. If you used ASM model, configure the VM’s endpoint instead.

To do this, we add Inbound Security Rules for port 80 and 1433. So go to NSG blade => Inbound security rules => Add inbound security rule, type any formal names and open the ports 80 and 1433 as.

image02

This is all we have to do. Now we have 2 Docker images and configured the NSG of the NIC attached with the VM.

Spinning up the containers

Spin up the SQL Server Container

To spin up the SQL Server container, type in the terminal as,

docker run -e ‘ACCEPT_EULA=Y’ -e ‘SA_PASSWORD=Br0ckLesnar!’ -p 1433:1433 -d –name sqlinux –network=isolated_network microsoft/mssql-server-linux

Notice the name of the container. As said earlier, this must match with the server name given in the connection string of the web app settings. Also notice that we must place these running containers inside a separate Docker network. If we don’t specify a network, it will run inside the default network and automatic service discovery does not work in the default network to create a separate Docker network type.

And, use this network for your containers.

Spin up the ASP.NET Core Container

To run the ASP.NET Core container, simply type.

docker run -p 80:5000 -d –name webapp –network=isolated_network aspnetcoreapp

We now have the application and database containers running and they are interacting with each other. To test this, browse to the public IP address or DNS name of your Linux VM on your local machine’s browser and you will see that the application is up and running.

image03

Go to the Register page and try to register a user.

image04

And you can see that the user is successfully created in SQL Server running inside the Docker Container.

image05

Connecting Windows SSMS with Docker SQL Server

Now we will use our local SQL Server tool, called SQL Server Management Studio (SSMS),  to connect the SQL Server instance running inside the Docker container inside the Azure VM. Remember, we opened the port 1433 in the NSG attached to the NIC of the VM. So open the SSMS and type the IP Address of the VM with port (with format [ip_address, port]) inside the Server name section, use the SQL Server Authentication option, type the user SA and type the password we used when we spun the SQL Server container.

image06

We see that the Server is connected — now run a SQL query against one of the tables  created by Identity in the database and you will see that the record has been successfully added and displaying in the SSMS.

image07

Conclusion

We saw how we connect an application container and a database container with service discovery feature of Docker Engine. I did not mount any volume to the SQL Server container nor did I use any Docker Volume plugin to make it even more productive so this is stateless by default. Using the same technique for production use case is not recommended. The idea was to provide a step by step guide to build a simple 3-tier application using Docker containers.

How to Secure your ASP.NET Core MVC and Web API app using Google

How to Secure your ASP.NET Core MVC and Web API app using Google

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core MVC hosting. Now it’s time to tackle a common scenario – securing your .NET Core Web app (even when accessed via Angular).

To keep things simple for this example, we’re going to require our users to log in as soon as they enter our app.

We can use ASP.NET Core to redirect the user to a login page as soon as they hit our default controller action (/home/index).

That way, they can’t even load our Angular app until they’re logged in.

Once they’ve logged in (via Google), Angular will load as normal and any requests from the Angular app to our Web API will work.

The end result

Let’s start by looking at the end result.

When we’ve made the changes to our app, any users attempting to access it will be redirected to this amazing login page.

Log-in-with-Google-1

We’re not going to win any prizes for design here but it will get us up and running. When your user clicks the Log in with Google link, they’ll be redirected to Google for authentication.

Google-sign-in-page

Once they’ve confirmed their email and password, they’ll be redirected back to your application, along with tokens confirming they have been authenticated.

ASP.NET Core will then accept those tokens as proof of identity and check for them on every request to a secure part of your app.

Sample App

To save spinning up yet another sample app, I’m going to use my Angular 2 Weather Station for this.

However, any ASP.NET Core MVC app will suffice.

If you don’t already have one and want to spin up a new app to play along, this should work…

Google – for all your authorization needs

As we covered in our look at big picture, you need an Authorization server. The Auth server takes care of requesting user credentials, confirming they are who they claim to be, then redirecting them back to your application with an access token.

To save ourselves the hassle of creating our own login system for now, we’re going to use Google as our Authorization Server (using OAuth2 and OpenId Connect).

What in the world is OAuth 2 and OpenId Connect?

OK, I’ll level with you.

When I started putting together this article, I fully intended to use OAuth 2 by itself.

If you’re not familiar with it, OAuth 2 is a means by which you can request an authorization key for your app via a third party e.g. Google.

The thing is though, it was never really designed for true user authentication.

If you think back to our house analogy from the big picture. OAuth 2 will give users a key to your house, but once they have a key, there’s no longer any guarantee that they are who they claim to be. They could have given that key to anyone who can now do what they like in your house!

Also, there are no strict rules on how OAuth2 should be implemented. The big providers like Google and Facebook started encouraging sites to use it for pseudo Authentication, hence “Login with Google” buttons appearing everywhere. But OAuth2 by itself is pretty weak for Authentication and there have been a number of significant holes found in it over the last few years.

This is where OpenId Connect comes in. This sits on top of OAuth 2 and effectively turns it into the secure authentication framework you really want it to be.

Using OpenId Connect, you can be much more sure that the person holding the key to your web app is the person they claim to be.

The good news is, setting up OpenId Connect in ASP.NET Core is pretty straightforward and definitely worth it for the extra security it provides.

Set up your app in Google

The first step is to head on over to Google to set up the OAuth 2.0 side of things.

You’ll need to generate credentials for your app (to use when talking to Google) and set up redirect URLs so your users are redirected back to your app when login succeeds or fails.

You can follow the guide on Setting up OAuth 2.0 over at Google’s official support site.

Go ahead, do that now, then you can follow along with the next steps.

Note, as part of the set up, you will need to provide an Authorized redirect URI.

Assuming your ASP.NET app is using the default port, you will typically want to add http://localhost:5000/signin-oidc for testing on your local machine.

But watch out, if you’re using Visual Studio 2017, your app might run via IISExpress using a different port, you’ll need to use the correct URL either way.

Redirect-URI-1

Securing the ASP.NET Core app

Now it’s time to look at our ASP.NET MVC app.

You can easily restrict any part of your app using the [Authorize] attribute.

Given we want to block users before they even get to the Angular app, we’ll go ahead and lock down our Home controller’s Index Action.

Modify HomeController.cs as follows.

When a user accesses our angular app, they start here. With this attribute in place, our application is now effectively restricted to logged in users.

It’s a bit brute force, but this is the simplest approach we can take whilst we get our heads around how all of this works, before we get in to more complicated scenarios like letting users into part of our SPA before requiring them to log in.

All well and good, but if we stop here we’ve literally prevented anyone from getting into our app.

No-auth-set-up

To remedy that, we need to tell ASP.NET Core how we want users to be authenticated, along with some important details like where to send them when they’re not.

Authentication with Cookies

To keep things simple, we’ll use Cookie Authentication here. If anyone tries to access a restricted resource and doesn’t have a legitimate ASP.NET security cookie, they will be redirected to our super login page.

Start off by bringing in the Microsoft Cookies Nuget package.

With that installed, you can easily configure Cookies Authentication in Startup.cs.

This sets things up so that any unauthorized users attempting to access a restricted part of our app, will be required to log in via OpenId Connect.

Create a login page

Before we go any further, it would be a good idea to create our login page, complete with button to log in via Google.

Add an AccountController.cs file to the controllers folder and define a simple Login action.

Create a Login.cshtml view in Views/Account.

If you’re not using Bootstrap, feel free to skip the divs, the key part is the link to sign in with Google (via OpenId Connect).

Now if you’re paying attention you’ll have noticed we’re linking to /account/external but that doesn’t exist (yet).

Back to the AccountController, add an External action.

With this in place, .NET Core is almost ready to challenge your user’s credentials via Google.

Configure OpenId Connect

Finally, you just need to bring in Microsoft’s OpenId Connect NuGet package.

Then head on back over to Startup.cs and modify the Configure method.

You can get hold of your ClientId and ClientSecret from Google (assuming you’ve followed the instructions to set up Google OAuth2)

Important: Don’t go including your Id and Secret “naked” in the code like this other than for testing. In reality you’ll want to protect this sensitive information. One option is to use App Secrets during development.

As you can see, OpenId Connect is actually pretty simple to set up. You need to point it at an authority server (Google in this case).

The OnRedirectToIdentityProvider event handler is there to make sure users are redirected to our login page when they try to access a restricted part of the app. The Request.Path check simply makes sure we don’t accidentally block our app as it attempts to complete the sign-in process via Google.

Give it a spin

All that’s left is to test it out.

When you access your app you’ll be redirected to the login page.

From there, clicking on the Login link will send you off to Google where you can log in with your Google account.

Once you’ve done that, you’ll be sent back to your app where you’ll have been granted access.

Lock down those APIs

So far we haven’t locked down our API controllers. That means anyone (logged in or not) can still go directly to our APIs.

Thankfully, now we’ve tackled the OpenId Connect plumbing, it’s trivial to add the [Authorize] attribute to any of our API controllers, locking them down for anyone but authorized users (who have an auth cookie).

The last step

Phew, you made it this far.

Now your users can log in via Google (using OpenIdConnect).

Once Google’s confirmed their identity (by asking them to log in), they’re redirected back to your app, complete with access and identity tokens.

ASP.NET Core’s Cookie Middleware then kicks in to serialize your user’s principal (information about their identity) into an encrypted cookie. Thereafter, any requests to your app validate the cookie, recreate the principal and assign it to the User property on HttpContext.

One last thing, you might want to give your users a way to sign out of your app. Just add the following to your AccountController.

Any request to /account/signout will now sign them out, requiring them to log in again to access your app.