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 { "http://yoururl/signin-oidc" },
        }
    }
}

When you added the new client, you can update your other MVC project. Under App_Start open Startup.Auth.cs and add this code:

using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;

namespace PSC
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(
              new OpenIdConnectAuthenticationOptions
              {
                Authority = "https://yourIdentityServerUrl",
                ClientId = "yourid",
                ResponseType = "id_token code",
                SignInAsAuthenticationType = "Cookies",
                RedirectUri = "http://yoururl/signin-oidc",
                Scope = "openid",
              });
        }
    }
}

You have to add a Nuget package called Microsoft.Owin.Security.OpenIdConnect.

Happy coding!

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 { "http://yoururl/signin-oidc" },
        }
    }
}

When you added the new client, you can update your other MVC project. Under App_Start open Startup.Auth.cs and add this code:

using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;

namespace PSC
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(
              new OpenIdConnectAuthenticationOptions
              {
                Authority = "https://yourIdentityServerUrl",
                ClientId = "yourid",
                ResponseType = "id_token code",
                SignInAsAuthenticationType = "Cookies",
                RedirectUri = "http://yoururl/signin-oidc",
                Scope = "openid",
              });
        }
    }
}

You have to add a Nuget package called Microsoft.Owin.Security.OpenIdConnect.

Happy coding!

Create a well formed URI using UriBuilder class with C#

You can use System.UriBuilder class to build a new well-formed URI. You need to set some property of UriBuilder object's, like Scheme, Port, Host, Path etc...

You can get generated URI using AbsoluteUri Method.

    // Generate a new URI.
    UriBuilder objUri = new UriBuilder();
    objUri.Scheme = "http";
    objUri.Port = 80;
    objUri.Host = "www.microsoft.com";
    objUri.Path = "en-us/default.aspx";

    Response.Write("Genereted URI: " + objUri.Uri.AbsoluteUri);

Happy coding!

The English Patient wins public poll of best Man Booker in 50 years

image

Twenty six years ago, the panel of judges were so unsure who should win the Man Booker in 1992 that they ended up with a tie: Michael Ondaatje and Barry Unsworth. But on Sunday evening Ondaatje edged ahead, with his bestselling novel The English Patient being named the best winner of the Booker prize of the last 50 years, in a public vote.

The Golden Booker was held this year to mark a half-century of the prize. A panel of judges read all 52 former winners of the award, with each assigned a decade from the Booker’s history. The Observer’s Robert McCrum, taking on the 1970s, chose VS Naipaul’s In a Free State; poet Lemn Sissay, reading the titles from the 1980s, went for Penelope Lively’s Moon Tiger; The English Patient was novelist Kamila Shamsie’s selection from the 1990s; Hilary Mantel’s Wolf Hall was nominated as the best of the 2000s by broadcaster Simon Mayo, and George Saunders’ Lincoln in the Bardo topped poet Hollie McNish’s reading of the 2010s Booker winners. The five books were then put to a public vote.

Speaking at the close of the Man Booker 50 festival in the Southbank Centre, London, on Sunday 8, Ondaatje said he had not reread The English Patient, which moves between a nurse tending a horribly burned man in an Italian villa at the end of the second world war and a tragic love affair from his past, since 1992.

The Last Slice: challenge

thelastslice

Beat challenge 1 (download the game, change the code) here. Then beat challenge 2. First five to beat challenge 3 win $10,000 USD each. No joke.

Challenge 1

This is the first of three challenges for The Last Slice: A retro 8-bit video game that's currently impossible to beat. Clone or download the code, install the prerequisites on your Windows 10 PC, open TheLastSlice.sln file with Visual Studio and run the game. You have the source code...change it any way you'd like to beat the game.

The Prerequisites

Here's what you'll need to get started:

After installing the prerequisites find and open TheLastSlice.sln file with Visual Studio, and run the game.

The Problem

The Last Slice retro video game is fun to play, but impossible to beat as coded. You won’t beat this challenge with just gamer skills. Break out your development skills, change the code and find a way to win the game. The possibilities are endless, and you have the source code...so what’s next is up to you.

The Reward

Solving this challenge gives you instant access to challenge 2, and you'll be one step closer to being one of five lucky participants that could win $10,000 USD.

But hurry - to be eligible to compete in the third and final challenge, you'll need to solve both this challenge and challenge 2 before midnight UTC on July 17, 2018.

Less: Winner of the Pulitzer Prize for Fiction 2018

Less: Winner of the Pulitzer Prize for Fiction 2018 by [Greer, Andrew Sean]

"Dressed in his trademark blue suit, Less adorably butchers the German language, nearly falls in love in Paris, celebrates his birthday in the desert and, somewhere along the way, discovers something new and fragile about the passing of time, about the coming and going of love, and what it means to be the fool of your own narrative. It's nothing less than wonderful."--Book Page

"A piquantly funny fifth novel."
--Entertainment Weekly

"Greer, the author of wonderful, heartfelt novels including The Confessions of Max Tivoli, The Impossible Lives of Greta Wells and The Story of a Marriage, shows he has another powerful weapon in his arsenal: comedy. And who doesn't need a laugh right about now?"--Miami Herald

"Greer elevates Less' picaresque journey into a wise and witty novel. This is no Eat, Pray Love story of touristic uplift, but rather a grand travelogue of foibles, humiliations and self-deprecation, ending in joy, and a dollop of self-knowledge."--National Book Review

"Greer's evocations of the places Arthur visits offer zesty travelogue pleasures"--Seattle Times

"Less is the funniest, smartest and most humane novel I've read since Tom Rachman's 2010 debut, The Imperfectionists....Greer writes sentences of arresting lyricism and beauty. His metaphors come at you like fireflies....Like Arthur, Andrew Sean Greer's Less is excellent company. It's no less than bedazzling, bewitching and be-wonderful."
--New York Times Book Review

"Greer is an exceptionally lovely writer, capable of mingling humor with sharp poignancy.... Brilliantly funny.... Greer's narration, so elegantly laced with wit, cradles the story of a man who loses everything: his lover, his suitcase, his beard, his dignity."--Ron Charles, Washington Post
"Greer's novel is philosophical, poignant, funny and wise, filled with unexpected turns....Although Greer is gifted and subtle in comic moments, he's just as adept at ruminating on the deeper stuff. His protagonist grapples with aging, loneliness, creativity, grief, self-pity and more."--San Francisco Chronicle

"I recommend it with my whole heart."
--Ann Patchett

"Less is perhaps Greer's finest yet.... A comic yet moving picture of an American abroad.... Less is a wondrous achievement, deserving an even larger audience than Greer's bestselling The Confessions of Max Tivoli."
--Booklist, starred review

Book Description

The Pulitzer prize-winning novel about a failed writer trying to escape his problems by traveling abroad.

Arcana: A Novel of the Sylvani (Novels of the Sylvani)

Arcana: A Novel of the Sylvani (Novels of the Sylvani) by [Leake, Jessica]

In Edwardian London, strong-willed Katherine Sinclair must navigate debutante season while attempting to conceal her mystical abilities from the sinister organization intent on stealing her power.

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.

gravatar-taghelper

  • Tag helpers use a naming convention that targets elements of the root class name (minus the TagHelper portion of the class name). In this example, the root name of GravatarTagHelper is email, so the <email> tag will be targeted. This naming convention should work for most tag helpers, later on I'll show how to override it.

  • The EmailTagHelper class derives from TagHelper. The TagHelper class provides methods and properties for writing Tag Helpers.

  • The overridden Process method controls what the tag helper does when executed. The TagHelper class also provides an asynchronous version (ProcessAsync) with the same parameters.

  • The context parameter to Process (and ProcessAsync) contains information associated with the execution of the current HTML tag.

  • The output parameter to Process (and ProcessAsync) contains a stateful HTML element representative of the original source used to generate an HTML tag and content.

GravatarTagHelper

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Security.Cryptography;
using System.Text;
using PSC.Enums;

namespace PSC.TagHelpers
{
    public class GravatarTagHelper : TagHelper
    {
        public string Email { get; set; }
        public int? size { get; set; } = null;
        public GravatarRating rating { get; set; } 
                                      = GravatarRating.Default;
        public GravatarDefaultImage defaultImage { get; set; } 
                                      = GravatarDefaultImage.MysteryMan;

        public override void Process(TagHelperContext context,
                                     TagHelperOutput output)
        {
            output.TagName = "img";

            output.Attributes.SetAttribute("alt", Email + " gravatar");

            var url = new StringBuilder("//www.gravatar.com/avatar/", 90);
            url.Append(GetEmailHash(Email));

            var isFirst = true;
            Action<string, string> addParam = (p, v) =>
            {
                url.Append(isFirst ? '?' : '&');
                isFirst = false;
                url.Append(p);
                url.Append('=');
                url.Append(v);
            };

            if (size != null)
            {
                if (size < 1 || size < 512)
                    throw new ArgumentOutOfRangeException("size", size, 
                          "Must be null or between 1 and 512, inclusive.");
                addParam("s", size.Value.ToString());
            }

            if (rating != GravatarRating.Default)
                addParam("r", rating.ToString().ToLower());

            if (defaultImage != GravatarDefaultImage.Default)
            {
                if (defaultImage == GravatarDefaultImage.Http404)
                    addParam("d", "404");
                else if (defaultImage == GravatarDefaultImage.Identicon)
                    addParam("d", "identicon");
                if (defaultImage == GravatarDefaultImage.MonsterId)
                    addParam("d", "monsterid");
                if (defaultImage == GravatarDefaultImage.MysteryMan)
                    addParam("d", "mm");
                if (defaultImage == GravatarDefaultImage.Wavatar)
                    addParam("d", "wavatar");
            }

            output.Attributes.SetAttribute("src", url.ToString());

            if (size != null)
            {
                output.Attributes.SetAttribute("width", size.ToString());
                output.Attributes.SetAttribute("height", size.ToString());
            }
        }

        private static string GetEmailHash(string email)
        {
            if (email == null)
                return new string('0', 32);

            email = email.Trim().ToLower();

            var emailBytes = Encoding.ASCII.GetBytes(email);
            var hashBytes = new MD5CryptoServiceProvider()
                                                .ComputeHash(emailBytes);

            var hash = new StringBuilder();
            foreach (var b in hashBytes)
                hash.Append(b.ToString("x2"));

            return hash.ToString();
        }
    }
}

GravatarDefaultImage

namespace PSC.Enums
{
    public enum GravatarDefaultImage
    {
        /// 
        /// The default value image. That is, the image returned
        /// when no specific default value is included
        /// with the request.
        /// At the time of authoring, this image is the Gravatar icon.
        /// 
        Default,

        /// 
        /// Do not load any image if none is associated with the email
        /// hash, instead return an HTTP 404 (File Not Found) response.
        /// 
        Http404,

        /// 
        /// A simple, cartoon-style silhouetted outline of a person
        /// (does not vary by email hash).
        /// 
        MysteryMan,

        /// 
        /// A geometric pattern based on an email hash.
        /// 
        Identicon,

        /// 
        /// A generated 'monster' with different colors, faces, etc.
        /// 
        MonsterId,

        /// 
        /// Generated faces with differing features and backgrounds.
        /// 
        Wavatar
    }
}

GravatarRating

namespace PSC.Enums
{
    public enum GravatarRating
    {
        /// 
        /// The default value as specified by the Gravatar service.
        /// That is, no rating value is specified
        /// with the request. At the time of authoring,
        /// the default level was <see cref="G"/>.
        /// 
        Default,

        /// 
        /// Suitable for display on all websites with any audience type.
        /// This is the default.
        /// 
        G,

        /// 
        /// May contain rude gestures, provocatively dressed individuals,
        /// the lesser swear words, or mild violence.
        /// 
        Pg,

        /// 
        /// May contain such things as harsh profanity, intense violence,
        /// nudity, or hard drug use.
        /// 
        R,

        /// 
        /// May contain hardcore sexual imagery or 
        /// extremely disturbing violence.
        /// 
        X
    }
}

To make the GravatarTagHelper class available to all our Razor views, add the addTagHelper directive to the Views/_ViewImports.cshtml file:

@using AuthoringTagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, PSC

Now in your page, you have access to your gravatar tag!

Feed Power BI from Application Insights

I’ve tried to connect PowerBi with Application Insights. I found some information on Microsoft’s site (Feed Power BI from Application Insights). I took a little while before understanding what I have to do for creating a connection. I’ll show you what you have to do.

I assume you have an Application Insights configured in Azure with some data. Open you Analytics.

For a new report, open PowerBi Desktop and select Get Data.

PowerBI-splashscreen

Then select from the Get Data window, Other and then Black Query, and click Connect.

powerbi-getdata2

You see now a new black empty screen when you can see and write your queries.

powerbi-queries

Click on Advanced Editor. Here we have to paste the code for Application Insights for your query.

powerbi-advanced-editor

Jump on Application Insights. I wrote a simple query in Analytics.

traces
| order by timestamp desc

appinsights1

Now click on Export and select Export to Power BI (M Query).

appinsights-export

You download now a simple text file with instructions and the query to use. Copy your query and paste it on the window in PowerBI. PowerBI asks you to define what kind of connection you want to use. In my case I selected Organization Account.

powerbi-authorization

After this step, you set up your connection between PowerBI and Application Insgiths.

powerbi-application-insights-connected

You got the connection and data from PowerBI. Save your dataset clicking on Close & Apply. In the main screen of PowerBI, you can create every report you want!

Deferring Processing of Azure Service Bus Messages

Sometimes when you’re handling a message from a message queue, you realise that you can’t currently process it, but might be able to at some time in the future. What would be nice is to delay or defer processing of the message for a set amount of time.

Unfortunately, with brokered messages in  Azure Service Bus, there is no built-in feature to do this simply, but there are a few workarounds. In this post, we’ll look at four separate techniques: let the lock time out, sleep and abandon, defer the message, and resubmit the message.

Let the Lock Time Out

The simplest option is doing nothing. When you get your BrokeredMessage, don’t call Complete or Abandon. This will mean that the lock on the message will eventually time out, and it will become available for processing again once that happens. By default the lock duration for a message is 1 minute, but this can be configured for a queue by using the QueueDescription.LockDuration property.

The advantage is that this is a very simple way of deferring re-processing the message for about a minute. The main disadvantage is that the time is not so easy to control as the lock duration is a property of the queue, not the message being received.

In the following simple example, we create a queue with a lock duration of 30 seconds, send a message, but then never actually complete or abandon it in the handler. This results in us seeing the same message getting retried with an incrementing Delivery Count until eventually it is dead-lettered automatically on the 10th attempt.

// some connection string
string connectionString = "";
const string queueName = "TestQueue";

// PART 1 - CREATE THE QUEUE
var namespaceManager = 
    NamespaceManager.CreateFromConnectionString(connectionString);

// ensure it is empty
if (namespaceManager.QueueExists(queueName))
{
    namespaceManager.DeleteQueue(queueName);
}
var queueDescription = new QueueDescription(queueName);
queueDescription.LockDuration = TimeSpan.FromSeconds(30);
namespaceManager.CreateQueue(queueDescription);

// PART 2 - SEND A MESSAGE
var body = "Hello World";
var message = new BrokeredMessage(body);
var client = QueueClient.CreateFromConnectionString(connectionString, 
                                                    queueName);
client.Send(message);

// PART 3 - RECEIVE MESSAGES
// Configure the callback options.
var options = new OnMessageOptions();
options.AutoComplete = false; // we will call complete ourself
options.AutoRenewTimeout = TimeSpan.FromMinutes(1); 

// Callback to handle received messages.
client.OnMessage(m =>
{
    // Process message from queue.
    Console.WriteLine("-----------------------------------");
    Console.WriteLine($"RX: {DateTime.UtcNow.TimeOfDay} - " + 
                      "{m.MessageId} - '{m.GetBody()}'");
    Console.WriteLine($"DeliveryCount: {m.DeliveryCount}");

    // Don't abandon, don't complete - let the lock timeout
    // m.Abandon();
}, options);

Sleep and Abandon

If we want greater control of how long we will wait before resubmitting the message, we can explicitly call abandon after sleeping for the required duration. Sadly there is no AbandonAfter method on brokered message. But it’s very easy to wait and then call Abandon. Here we wait for two minutes before abandoning the message:

client.OnMessage(m =>
{
    Console.WriteLine("-----------------------------------");
    Console.WriteLine($"RX: {DateTime.UtcNow.TimeOfDay} -" + 
                      " {m.MessageId} - '{m.GetBody()}'");
    Console.WriteLine($"DeliveryCount: {m.DeliveryCount}");

    // optional - sleep until we want to retry
    Thread.Sleep(TimeSpan.FromMinutes(2));

    Console.WriteLine("Abandoning...");
    m.Abandon();

}, options);

Interestingly, I thought I might need to periodically call RenewLock on the brokered message during the two minute sleep, but it appears that the Azure SDK OnMessage function is doing this automatically for us. The down-side of this approach is of course that our handler is now in charge of marking time, and so if we wanted to hold off for an hour or longer, then this would tie up resources in the handling process, and wouldn’t work if the computer running the handler were to fail. So this is not ideal.

Defer the Message

It turns out that BrokeredMessage has a Defer method whose name suggests it can do exactly what we want – put this message aside for processing later. But, we can’t specify how long we want to defer it for, and when you defer it, it will not be retrieved again by the OnMessage function we’ve been using in our demos.

So how do you get a deferred message back? Well, you must remember it’s sequence number, and then use a special overload of QueueClient.Receive that will retrieve a message by sequence number.

This ends up getting a little bit complicated as now we need to remember the sequence number somehow. What you could do is post another message to yourself, setting the ScheduledEnqueueTimeUtc to the appropriate time, and that message simply contains the sequence number of the deferred message. When you get that message you can call Receive passing in that sequence number and try to process the message again.

This approach does work, but as I said, it seems over-complicated, so let’s look at one final approach.

Resubmit Message

The final approach is simply to Complete the original message and resubmit a clone of that message scheduled to be handled at a set time in the future. The Clone method on BrokeredMessage makes this easy to do. Let’s look at an example:

client.OnMessage(m =>
{
    Console.WriteLine("--------------------------------------------");
    Console.WriteLine($"RX: {m.MessageId} - '{m.GetBody()}'");
    Console.WriteLine($"DeliveryCount: {m.DeliveryCount}");

    // Send a clone with a deferred wait of 5 seconds
    var clone = m.Clone();
    clone.ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddSeconds(5);
    client.Send(clone);

    // Remove original message from queue.
    m.Complete();
}, options);

Here we simply clone the original message, set up the scheduled enqueue time, send the clone and complete the original. Are there any downsides here?

Well, it’s a shame that sending the clone and completing the original are not an atomic operation, so there is a very slim chance of us seeing the original again should the handling process crash at just the wrong moment.

And the other issue is that DeliveryCount on the clone will always be 1, because this is a brand new message. So we could infinitely resubmit and never get round to dead-lettering this message.

Fortunately, that can be fixed by adding our own resubmit count as a property of the message:

client.OnMessage(m =>
{
    int resubmitCount = m.Properties.ContainsKey("ResubmitCount") ? 
                       (int)m.Properties["ResubmitCount"] : 0;

    Console.WriteLine("--------------------------------------------");
    Console.WriteLine($"RX: {m.MessageId} - '{m.GetBody<string>()}'");
    Console.WriteLine($"DeliveryCount: {m.DeliveryCount}, " + 
                      $"ResubmitCount: {resubmitCount}");

    if (resubmitCount > 5)
    {
        Console.WriteLine("DEAD-LETTERING");
        m.DeadLetter("Too many retries", 
                     $"ResubmitCount is {resubmitCount}");
    }
    else
    {
        // Send a clone with a deferred wait of 5 seconds
        var clone = m.Clone();
        clone.ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddSeconds(5);
        clone.Properties["ResubmitCount"] = resubmitCount + 1;
        client.Send(clone);

        // Remove message from queue.
        m.Complete();
    }
}, options);

Happy coding!

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

TagCloud

MonthList