WPF and WinForms Will Run on .NET Core 3

WPF and WinForms Will Run on .NET Core 3

If you haven't had a chance to explore the new capabilities of .NET Core 3, read along with an expert in the framework to discover what it brings to the table.


Maybe you already heard or read about the fact that Microsoft brought WinForms and WPF to .NET Core 3.0. Maybe you already saw the presentations on the Connect conference, or any other conference or recording when Scott Hanselman shows how to run a pretty old WPF application on .NET Core. I saw a demo where he ran BabySmash on .NET Core.

BTW: My oldest son really loved that BabySmash when he was a baby.
WPF and WinForms on .NET Core?

I was really wondering about this step, even because I wrote an article for a German .NET magazine some months before where I mentioned that Microsoft won’t build a UI Stack for .NET Core. There were some other UI stacks built by the community. The most popular is Avalonia.

But this step makes sense anyway. Since the .NET Standards move the API of .NET Core more to the same level of the .NET framework, making the APIs almost equal was simply a question of time. WPF and WinForms are based on .NET Libraries, so it should run on .NET Core.


Does This Mean it Runs on Linux and Mac?

Nope! Since WinForms and WPF uses Windows only technology in the background, it cannot run on Linux or Mac. It is really dependent on Windows. The sense of running it on .NET Core is performance and to be independent of any framework. .NET Core is optimized for performance so you can run super fast web applications in the cloud. .NET Core is also independent of the installed framework on the machine. Just deploy the runtime together with your application.

You are now able to run fast and self-contained Windows desktop applications. That’s awesome, isn’t it!?


The .NET CLI

Every time I install a new version of the .NET Core runtime I try dotnet new and I was positively shocked about what I saw this time:

You are now able to create a Windows Form or a WPF application using the .NET CLI. This is cool. And I for sure needed to try it out:

dotnet new -n WpfTest -o WpfTest dotnet new -n WpfTest -o WpfTest 

And yes, it is working as you can see here in Visual Studio Code:

And this is the WinForms project in VS Code

Running dotnet run on the WPF project:

And again on the WinForms GUI:


IDE

Visual Studio Code isn’t the right editor for this kind of project. If you know XAML pretty well, it will work, but WinForms definitely won’t work well. You need to write the designer code manually and there isn’t any designer support yet. Maybe there will be some in the future, but I’m not sure.

The best choice to work with WinForms and WPF on .NET Core is Visual Studio 2017 or newer.


Last Words

I don’t think I will now start to write desktop apps on .NET Core 3, because I’m a web guy. But it is a really nice option to build apps like this on .NET Core.

BTW: Even EF 6 will work in .NET Core 3, which means you also don’t need to rewrite the database access part of your desktop application.

As I wrote, you can now use this super fast framework and the option to create self-contained apps. I would suggest you try it out and play around with it. Do you have an older desktop application based on WPF or WinForms? I would be curious about whether you can run it on .NET Core 3. Tell me how easy it was to get it running on .NET Core 3.


Learn More

The Complete ASP.NET MVC 5 Course

Build a Real-world App with ASP.NET Core and Angular 2 (4+)

ASP NET Core (ASP.NET 5),MVC 6,C#,Angular2 & EF Crash Course

Rest Api’s in Asp.Net and C#

Hands on ASP .Net Core 2

Originally published by Juergen Gutsch at https://dzone.com

Supporting Windows Forms and WPF in .NET Core 3

Supporting Windows Forms and WPF in .NET Core 3

In this episode, Jeremy interviews Mike Harsh about some of the work being done and decisions being made to enable Windows Forms and WPF applications to run well on .NET Core 3.0 and beyond.

In this episode, Jeremy interviews Mike Harsh about some of the work being done and decisions being made to enable Windows Forms and WPF applications to run well on .NET Core 3.0 and beyond.

[04:20] - What was the motivation behind bring desktop workloads to .NET Core?

[10:42] - What was the biggest challenge with add support for desktop technologies?

[12:42] - How did the decision to open source Windows Forms and WPF come about?

[14:01] - How easy was it to open source Windows Forms and WPF?

[17:35] - What does the roadmap look like?

[20:45] - What does the future of Windows Forms look like?

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading .NET Core

WPF and WinForms Will Run on .NET Core 3

How to Port Desktop Applications to .NET Core 3.0

Build amazing web apps with ASP.NET Core 3.0

Moving from Node.js to .NET Core

Building Single Page Application Using ASP.NET Core & Angular

How to send multipart/form-data to asp.net core web api?

I'm trying to send a image and textfields to a api endpont but i'm reciving "Unsupported content type 'multipart/form-data; boundary=---------------------------81801171514357" This is a ASP.NET Core 2.1 Web api.

I'm trying to send a image and textfields to a api endpont but i'm reciving "Unsupported content type 'multipart/form-data; boundary=---------------------------81801171514357" This is a ASP.NET Core 2.1 Web api.

I have this:

[HttpPost("/api/account"), Authorize]
public void SaveUser(UserModel info)

And my model:

    [JsonProperty(PropertyName = "avatar")]
    [DataType(DataType.Upload)]
    public IFormFile Avatar { get; set; }
[JsonProperty(PropertyName = "name")]
[DataType(DataType.Text)]
public string Name { get; set; }

Then i use axios:

    var formData = new FormData();
formData.append("avatar", imageFile);
formData.append("name", name);
axios.post("/api/account", formData);

I expected this method to run, not throw an exception. But how?

I have tried to add:

[Consumes("application/json", "multipart/form-data")]

But no success..

Then i tried:

[HttpPost("/api/account"), Authorize]
public void SaveUser([FromForm]UserModel info)

The method runs, but the properties is empty on info object :(

Create Login and Registration in Your ASP.NET Core MVC App

Create Login and Registration in Your ASP.NET Core MVC App

This tutorial walks you through setting up login and registration with ASP.NET Core MVC. In this tutorial, you learned how to add authentication to your ASP.NET Core MVC app and allow users to register for a new account.

This tutorial walks you through setting up login and registration with ASP.NET Core MVC. In this tutorial, you learned how to add authentication to your ASP.NET Core MVC app and allow users to register for a new account.

User authentication and authorization are common features in web applications, but building these mechanics has the potential to take a lot of time. Doing so requires setting up persistent storage for user information (in some type of database) and paying keen attention to potential security issues around sensitive operations like hashing passwords, password reset workflows, etc. - weeks of development time begin to add up before we ever get to the functionality that delivers value to your users.

In this post, we’ll walk through how Okta simplifies this process for us and set up a simple integration for an ASP.NET Core MVC app using the Okta NuGet package. We’ll build functionality for users to register for new accounts and login with their Okta credentials.

Scaffold Your ASP.NET Project

To follow along with this tutorial start by creating a new app in the console:

mkdir MyOktaProject
cd MyOktaProject
dotnet new mvc


Configure User Registration

If you don’t already have one, you’ll need to create an Okta developer account. Doing so will give you a URL for your organization called an “Okta domain”. It will also allow you to create your login credentials for accessing the Okta dashboard.

Upon submission of this form, you will receive an email Okta with instructions to obtain your credentials and complete your registration.

Execute the following steps to configure Okta so that users can register themselves for an account.

  1. From the Administrative Dashboard, hover over Users and click Registration
  2. Click Enable Registration
  3. Save the changes

Configure Basic User Authentication

Once you have access to your account you can proceed to the Dashboard using a link like the one below:

<span

class="okta-preview-domain">https://{yourOktaDomain}/admin/dashboard

On the Dashboard, click Applications in the main menu and on the Application screen, click Add Application.

Select Web then click Next.

On the Create New Application screen, set the following values:

Click Done, then click Edit next to General Settings on your newly created Okta app. Edit the following values:

Logout redirect URIs: https://localhost:5001/signout-callback-oidc

Initiate login URI: https://localhost:5001/authorization-code/callback

Add .NET Authentication Dependencies

Once your account is set up you need to add the Okta.Sdk library to your project. This post will take the approach of using the NuGet package, but the Github repository for Okta.AspNetCore can be found here.

To proceed simply search for the latest version of the Okta.Sdk NuGet package in your IDE of choice (version 1.2.0 at the time of this publication) and install it. If you’re using Visual Studio you can do this by right-clicking on the project in the solution explorer and selecting Manage NuGet Packages. For those of you not using Visual Studio, add the package via console window using the following command:

dotnet add package Okta.Sdk --version 1.2.0


Configure Your ASP.NET App for Login

Authentication works by redirecting users to the Okta website, where they will log in with their credentials, and then be returned to your site via the URL you configured above.

Add the following code to your appsettings.json file:

  "Okta": {
    "Issuer": "https://{yourOktaDomain}/oauth2/default",
    "ClientId": "{yourClientId}",
    "ClientSecret": "{yourClientSecret}"
  }


You can find each of the actual values needed to replace the settings in the config above in the following places:

ClientId refers to the client ID of the Okta application ClientSecret refers to the client secret of the Okta application Issuer will need the text {yourOktaDomain} replaced with your Okta domain, found at the top-right of the Dashboard page

Add some using statements to your Startup.cs file:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;


Add the following code to the top of the ConfigureServices method in your Startup.cs file:

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.ClientId = Configuration["okta:ClientId"];
        options.ClientSecret = Configuration["okta:ClientSecret"];
        options.Authority = Configuration["okta:Issuer"];
        options.CallbackPath = "/authorization-code/callback";
        options.ResponseType = "code";
        options.SaveTokens = true;
        options.UseTokenLifetime = false;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name"
        };
    });


In the Configure() method of your Startup.cs file add this line just before the app.UseMvc() method:

app.UseAuthentication();


Add the following MeViewModel to the Models directory:

using System.Collections.Generic;

namespace OktaAspNetCoreMvc.Models
{
    public class MeViewModel
    {
        public string Username { get; set; }

        public bool SdkAvailable { get; set; }

        public dynamic UserInfo { get; set; }

        public IEnumerable<string> Groups { get; set; }
    }
}


Add Login to Your ASP.NET App

Now that all the configuration and plumbing is done, you’re ready to add the code that will actually log users into your application.

Add the following AccountController to the Controller directory.

The controller exposes the Login() action. If the user has already been authenticated, the Login() action will redirect them to the home page. Otherwise, it will redirect them to the Okta login screen.

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc;
using Okta.Sdk;

namespace OktaAspNetCoreMvc.Controllers
{
    public class AccountController : Controller
    {
        private readonly IOktaClient _oktaClient;

        public AccountController(IOktaClient oktaClient = null)
        {
            _oktaClient = oktaClient;
        }

        public IActionResult Login()
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return Challenge(OpenIdConnectDefaults.AuthenticationScheme);
            }

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


Add the following code to your _Layout.cshtml file, just below the main menu to add the login button, or a welcome message, based on the current user’s status.:

   @if (User.Identity.IsAuthenticated)
    {
        <ul class="nav navbar-nav navbar-right">
            <li><p class="navbar-text">Hello, @User.Identity.Name</p></li>
        </ul>
    }
    else
    {
        <ul class="nav navbar-nav navbar-right">
            <li><a asp-controller="Account" asp-action="Login">Log in</a></li>
        </ul>
    }


For information on user authorization using Okta groups check out Lee Brandt’s article on user authorization in ASP.NET Core with Okta.

Register Users

If you following the instructions above to enable self-service registration the “Don’t have an account? Sign Up” message will appear at the bottom of the login form. In the next step, you’ll run the application.

Log In Using ASP.NET

That’s it! To run your solution open up a terminal and enter the following command:

dotnet run


Then navigate to http://localhost:5001 in your browser and enjoy!

The source code for this tutorial is available on GitHub.

Now you have a website with a working login and user registration form. Your website also allows users to recover lost passwords. By repeating these steps you can create a network of tools that your users can access all with the same login.

Learn More

The Complete ASP.NET MVC 5 Course

Build a Real-world App with ASP.NET Core and Angular 2 (4+)

ASP NET Core (ASP.NET 5),MVC 6,C#,Angular2 & EF Crash Course

Rest Api’s in Asp.Net and C#

Hands on ASP .Net Core 2