Accessing the OIDC tokens in ASP.NET Core 2.0

In ASP.NET Core 1.1 So, for example, in ASP.NET Core 1.x, if you wanted to access the tokens (id_token, access_token and refresh_token) from your application, you could set the SaveTokens property when registering the OIDC middleware: 1 2 3 4 5 6 7 8 // Inside your Configure method app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions(“Auth0”) {     // Set all your OIDC options…     // and then set SaveTokens to save tokens to the AuthenticationProperties     SaveTokens = true }); You would then subsequently be able to retrieve those tokens by calling GetAuthenticateInfoAsync inside your controllers, and…

Read More

Adding an external Microsoft login to IdentityServer4

Microsoft Authenticator Identity

This article shows how to implement a Microsoft Account as an external provider in an IdentityServer4 project using ASP.NET Core Identity with a SQLite database. Setting up the App Platform for the Microsoft Account To setup the app, login using your Microsoft account and open the My Applications link https://apps.dev.microsoft.com/?mkt=en-gb#/appList Click the Add an app button. Give the application a name and add your email. This app is called microsoft_id4_enrico. After you clicked the create button, you need to generate a new password. Save this somewhere for the application configuration.…

Read More

Connect ASP.NET MVC 4.6.2 project to IdentityServer4

I have a website running on ASP.NET MVC 4.5.2. I have an IdentityServer4 server running but when I try and authenticate against it I get an: invalid_request I googled a bit but I can’t find a solution. Finally, I found the way. First, in your IdentityServer4 you have to create a new client: public static IEnumerable GetClients() { return new List<client> { new Client { ClientId = “yourid”, AllowedScopes = new List<string> { “openid” }, AllowedGrantTypes = GrantTypes.Hybrid, RedirectUris = new List { “https://yoururl/signin-oidc” }, } } } When you…

Read More

Gravatar Tag Helper for .NET Core 2.1

A tag helper is any class that implements the ITagHelper interface. However, when you create a tag helper, you generally derive from TagHelper, doing so gives you access to the Process method. In your ASP.NET Core project, create a folder to hold the Tag Helpers called TagHelpers. The TagHelpers folder is not required, but it’s a reasonable convention. Now let’s get started writing some simple tag helpers. Tag helpers use a naming convention that targets elements of the root class name (minus the TagHelper portion of the class name). In…

Read More

Render in MVC a link with image and text

Hi guys, I want in MVC to render a text with an image as an ActionLink. For creating a simple anchor tag, we use Html.ActionLink() helper which generates anchor tag for us. If you want to create something a bit more complicated, you must create you own component. For this reason, I created the following code. It allows you to create an anchor with an image and a text. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace PSC.MVC.Helpers { public static class CustomHtmlHelpers { ///…

Read More

ASP.NET LinkButton: children disappears after postback

I have a LinkButton with image and label inside it or tags i and span as in the following picture. The code in the page is: <asp:LinkButton ID="LinkButton1" runat="server"> <i class="glyphicon glyphicon-plus"></i> <span class="js-add-button" runat="server" id="Span1">Add New</span> </asp:LinkButton> After a postback everything inside the LinkButton disappeared. I’ve spent two days to understand why and the solution is very easy. <asp:LinkButton ID="LinkButton1" runat="server"> <i class="glyphicon glyphicon-plus" runat="server"></i> <span class="js-add-button" runat="server" id="Span1">Add New</span> </asp:LinkButton> The tag i doesn’t have runat="server" and for that you lost all content inside the LinkButton. Happy coding!

Read More

Customize Json result in Web API

If you work with Visual Studio 2015 and WebAPI, this short post is for you! We have to make our Web API project easy to debug so, I’m going to remove the XML formatter. I’m doing that because I’m in a test project and I’d like to see the response in the browser. The easily way to force the response to Json for all Web API requests is to remove the XML. Obviously you shouldn’t do it in production. Global.asax var formatters = GlobalConfiguration.Configuration.Formatters; formatters.Remove(formatters.XmlFormatter); Now we can start change…

Read More

Creating a URL shortener using ASP.NET WepAPI and MVC: error handling

In the two previous post I discussed about the first step to creare this application and the implementation of the business logic. Now we can implement the error handling. We have two custom exception classes: ShorturlConflictException (when a segment already exists) and ShorturlNotFoundException (when a segment isn’t found in the database). There is also a third type: an unexpected exception, for example when there is no database connection. Normally, the user will see these errors. We have to build a mechanism where these exceptions are caught and a nice error…

Read More

Creating a URL shortener using ASP.NET WepAPI and MVC: implementing the business layer

In my previsious post I discussed the first implementation of this application. In this post I’m explained how to implement the business layer. First of all you make sure the Business project references the Data, Entities and Exceptions projects. In the Exceptions project you add two new classes: ShorturlConflictException using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSC.Shorturl.Web.Exceptions { public class ShorturlConflictException : Exception { } } ShorturlNotFoundException using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSC.Shorturl.Web.Exceptions { public class ShorturlNotFoundException : Exception {…

Read More

Creating a URL shortener using ASP.NET WepAPI and MVC

In this tutorial, I use several techniques and tools. I use Microsoft Visual Studio 2015 and the latest version of all components. ASP.NET MVC: Microsoft’s modern web application framework. As the name says, it pushes you to use the MVC (model view controller) software design principle. ASP.NET Web API: Web API and MVC are used together in many applications. With MVC, the HTML of the web pages are rendered on the server, and with Web API you can, like the name says, create an API. Web API also uses the…

Read More

OWIN and Facebook: the developers of this app have not set up this app properly for Facebook Login?

Did you received this error when you try to login in your Owin app with Facebook? App Not Set Up: This app is still in development mode, and you don’t have access to it. Switch to a registered test user or ask an app admin for permissions. Solution Go to https://developers.facebook.com/ Click on the My Apps menu on the top bar and select your appThe circle next to your app name is not fully green. When you hover mouse on it, you’ll see a popup saying, "Not available to all…

Read More

C# ASP.NET MVC OWIN and Twitter authentication error

We have an MVC project using OWIN Framework to allow our users to authenticate using Twitter. However starting today, we have been getting this exception when trying to authenticate: System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure. Thanks to the power of open source we can see that the thumbprints for the twitter certificates have been coded in the Katana Project. Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions Recently some certificates must have changed and now the thumbprints no longer match. Please add a new thumb print for the "VeriSign Class 3 Public…

Read More

ASP.NET MVC Return image dynamically drawn in controller

If you have problem returning dynamically drawn image from controller below informations may help. The task looks easy and should be achieved with this code: public ActionResult Image(string text) { //Create new image Image img = new Bitmap(100, 50); Graphics g = Graphics.FromImage(img); //Do some drawing Font font = new Font("Arial", 24); PointF drawingPoint = new PointF(10, 10); g.DrawString(text, font, Brushes.Black, drawingPoint); //Return Image MemoryStream ms = new MemoryStream(); img.Save(ms, ImageFormat.Png); return new FileStreamResult(ms, "image/png"); }   Unfortunately this won’t work. At least not in .NET 4.0. Perceptive person will…

Read More

The current type, is an interface and cannot be constructed. Are you missing a type mapping?

You might have missed to register your Interface and class (which implements that inteface) registration in your code. e.g if the error is "The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?" Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. Using the following code as an example using System; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using PSC.Shorturl.Web.Business; using PSC.Shorturl.Web.Business.Implementations; namespace PSC.Shorturl.Web.App_Start { /// /// Specifies the Unity configuration for the main container. ///…

Read More

Using iTextSharp to generate pdf file in asp.net

One of the common requirement of web applications is to provide users a way to download some contents. In case of a report, almost all of the reporting tools have the export to pdf kind of function available. But sometime, it is not a report that needs to be generated in pdf. But it could be simple web page or content of a page or sometimes a plain text needs to be generated in pdf format. There are many third party tools are available for this task. We can import…

Read More

Templated Razor Delegates

What’s that? I’ll let the code do the speaking. @{ Func<dynamic, object> b = @<strong>@item</strong>; } <span>This sentence is @b(“In Bold”).</span> That could come in handy if you have friends who’ll jump on your case for using the bold tag instead of the strong tag because it’s “not semantic”. Note that the delegate that’s generated is a Func<T, HelperResult>. Also, the @item parameter is a special magic parameter. These delegates are only allowed one such parameter, but the template can call into that parameter as many times as it needs.…

Read More

Creating reusable HTML components in ASP.NET MVC using Razor

Whilst working on a side project I started to notice I was using a lot of the same HTML to create floating boxes. Whilst these boxes looked the same, the content of them changed quite dramatically; for instance, some of the content boxes contained forms, others contained straight text, like so: <div class="panel"> <div class=panel-inner"> <h2 class="panel-title">Panel Title</h2> <div class="panel-content"> /* Can I pass content to be rendered in here here? */ </div> </div> </div> </div>   As my side project progressed and grew, I found myself making more and…

Read More

ASP.NET: The data protection operation was unsuccessful

the data protection operation was unsuccessful. this may have been caused by not having the user profile loaded for the current thread’s user context, which may be the case when the thread is impersonating. If you receive this error from one of your application, you resolve the problem in this way: Open IIS Manager Select Applications Pools, and go ahead and select the App Pool used by your app Right-click on it, and select Advanced Settings, Go to the Process Model Section and Find the “Load User Profile” Option and…

Read More

Using the UpdateProgress to lock down controls in the browser

If it takes awhile for the server to process the postback (e.g. complex rules or badly written code ), the user may not realize that the server is processing the request. This can lead to all kinds of issues with users that are not savvy or familiar with web applications (multiple clicks, moving off the page, etc.). Consequently, I want to tell the user that the server is processing the request and disable the controls on the page. Let’s break this down into two steps: show a message, and disable…

Read More

Chart.js Asp.net : Create Pie chart with database jQuery Ajax C#

This article explains using Chart.js in Asp.net C# Web Application we can create a pie chart with database MS SQL server connectivity via jQuery ajax call.  You can also have a look on related article, . Now in this post here we create a pie chart by using chart.js library and bind data from our database MS Sqlserver, with jQuery ajax calling. Here we are creating a pie chart, which shows data from the database (Ms SQL server).  In my database, I have a table which stores data (website traffic…

Read More

DateDiff() function in C#

I have written the following DateDiff() function in C#. VB.NET users already had it using the Micrsoft.VisualBasic.dll assembly. Now you can use it without referencing this ‘ugly’ extra assembly. using System; namespace PureSourceCode.System { public enum DateInterval { Year, Month, Weekday, Day, Hour, Minute, Second } public class DateTimeUtil { public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2) { TimeSpan ts = date2 – date1; switch (interval) { case DateInterval.Year: return date2.Year – date1.Year; case DateInterval.Month: return (date2.Month – date1.Month) + (12 * (date2.Year – date1.Year)); case DateInterval.Weekday: return…

Read More