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

Create a well formed URI using UriBuilder class with C#

C# .NET language

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!

Read More

The Last Slice: challenge

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…

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

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…

Read More

Given, When, Then

Given-When-Then is a style of representing tests specifying a system’s behavior. It’s an approach developed by Dan North and Chris Matts as part of Behavior-Driven Development (BDD). It appears as a structuring approach for many testing frameworks such as Cucumber. You can also look at it as a reformulation of the Four-Phase Test pattern. The essential idea is to break down writing a scenario (or test) into three sections: The given part describes the state of the world before you begin the behavior you’re specifying in this scenario. You can…

Read More

7 Popular Unit Test Naming Conventions

Following are 7 popular unit tests naming conventions that are found to be used by majority of developers and compiled from above pages: MethodName_StateUnderTest_ExpectedBehavior: There are arguments against this strategy that if method names change as part of code refactoring than test name like this should also change or it becomes difficult to comprehend at a later stage. Following are some of the example: isAdult_AgeLessThan18_False withdrawMoney_InvalidAccount_ExceptionThrown admitStudent_MissingMandatoryFields_FailToAdmit MethodName_ExpectedBehavior_StateUnderTest: Slightly tweeked from above, but a section of developers also recommend using this naming technique. This technique also has disadvantage that if…

Read More

MongoDb example

Simple example for MongoDB. Save and retrieve data from Azure Cosmos DB. Create an Azure Cosmos Db as MongoDb For creating a new MongoDb on Azure, search from the list of resources, Azure Cosmos Db. Then Add a new database and you see the following screen. Overview When you created a new MongoDb, you see an Overview where there are general information about how many queries the database did (split on insert, update, cancel, query, count, others). Under Connection String you have the connection to use in your application. In…

Read More

Add a macOS project to your existing solution

With the new version of Xamarin, we can create apps for macOS. But how can I add a macOS project to my solution? I explain step by step what we have to do. Add new project The first step is to add a new project for macOS in your solution. Right-click on your solution and select Add New project… Now select from the list App under Mac and then Cocoa App. Then name your project, usually, we call this project with yourprojectname.macOS.

Read More

Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin

microsoft xamarin heros c# iOS Android UWP

Join Craig Dunn explains what’s new in iOS 11 and how to take advantage of the latest updates – from drag-and-drop for iPad to machine learning and more – 100% in .NET and Visual Studio. Whether you’re building new or updating existing Xamarin.iOS apps, you’ll see how to implement new frameworks, APIs, and UI features, walk-through code samples, get expert tips and tricks, so you can start shipping iOS 11-ready apps to your users. In this webinar, you’ll: Explore iOS 11 UI changes, including adapting to the iPhone X form…

Read More

What Singleton Pattern is in C# and its implementation

In another post I discussed how to implement Inversion of Control Pattern in C#. In this post I should explain what a singleton is. The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created and usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance – as otherwise, a second request for an instance but with a different parameter could…

Read More

How To Append ‘st’, ‘nd’, ‘rd’ or ‘th’ To Day Numbers in Dates

For a new project, my client required to output date strings in a format that included the two letter suffix added to the day number, like in British date (“January 1st 2018” as opposed to “January 1 2018”). The solution makes use of the custom formatting capabilities in the framework whereby it is possible to implement the IFormatProvider and ICustomFormatter interfaces to provide custom string formatting for use with methods that support formatting such as String.Format() or Console.WriteLine(). I decided to extend the existing DateTime format provision in the framework…

Read More

Enable and control iOS 11 Large Titles in Xamarin.Forms

microsoft xamarin heros c# iOS Android UWP

Apple introduced with iOS 11 a new UI in particular for larger titles: if you open your email, you see at the top a large title. That sit in the Navigation Bar and can be scrolled away when more space is needed. We can enable large titles with a renderer. For this example, I only created a new project and added the following renderer in the iOS project under Renderers folder. You can easily add to all your solution the following renderer in your iOS project: using System; using YourProject.iOS.Renderers;…

Read More

UriBuilder in Xamarin Forms

In Xamarin Forms there is a native function called UriBuilder: it allow you to create a well-formed url. In my implementation, all parameters are in a Dictionary called parameters. Using Linq, I put in builder.Query only the parameters with a value. UriBuilder builder = new UriBuilder(yourUrl); Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add(“reference”, Reference); parameters.Add(“param1”, Param1); builder.Query = string.Join(“&”, parameters.Where(p => !string.IsNullOrWhiteSpace(p.Value)) .Select(p => string.Format(“{0}={1}”, Uri.EscapeDataString(p.Key), Uri.EscapeDataString(p.Value)))); return builder.ToString(); Happy coding!

Read More

Binding FormattedString for Xamarin Forms

Xamarin Forms doesn’t have a Label with a Bindable FormattedString. For example, if you want a bindable bold word in the middle of a sentence in a Label, it’s very hard to design it with common control. For that, I create my own component for that. LabelRenderer.cs using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Runtime.CompilerServices; using Xamarin.Forms; namespace PSC.Controls { public class Label : Xamarin.Forms.Label { protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); UpdateFormattedTextBindingContext(); } protected override void OnPropertyChanged( [CallerMemberName] string propertyName = null) { base.OnPropertyChanged(propertyName); if (propertyName ==…

Read More

Xamarin Forms Repeater View

microsoft xamarin heros c# iOS Android UWP

A ListView is a kind of repeater but isn’t always what I want. It’s surprising something like this isn’t included in the framework but making your own is fairly simple. namespace PSC.Controls { /// <summary> /// Repeater view. /// </summary> public class RepeaterView : StackLayout { /// <summary> /// The item template property. /// </summary> public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create( “ItemTemplate”, typeof(DataTemplate), typeof(RepeaterView), null, propertyChanged: (bindable, value, newValue) => Populate(bindable)); /// <summary> /// The items source property. /// </summary> public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create( “ItemsSource”, typeof(IEnumerable),…

Read More

Xamarin, Android and starting a service at device boot

In my previous post called Xamarin: how to Start an Application at Device Boot in Android, I explained how you can change your Android Xamarin’s project to launch your app at the device boot. It is a good start but my problem was a bit more complex. I want to create a background service to track the geolocation of a device. I googled a lot to find a solution without a great success. Then I started to implement my code with some tests. Finally, I found a good way and…

Read More

Xamarin: how to Start an Application at Device Bootup in Android

This tutorial will explain to stat an application while the Android device boot-up. For this, we need to  listen to the BOOT_COMPLETED action and react to it. BOOT_COMPLETED is a Broadcast Action that is broadcast once, after the system has finished booting. You can listen to this action by creating a BroadcastReceiver that then starts your launch Activity when it receives an intent with the BOOT_COMPLETED action. Add this permission to your manifest In your Android.Manifest you must add thi permission: <uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED” />   Then open this file and…

Read More

Eat Cookies!

What are Cookies? Cookies are data, stored in small text files, on your computer. When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user. Cookies were invented to solve the problem "how to remember information about the user": When a user visits a web page, his name can be stored in a cookie. Next time the user visits the page, the cookie "remembers" his name. Cookies are saved in name-value pairs like: username = John…

Read More

C# and multicultural IsDate() and ToDate()

C# does not provide IsDate() function. Sometimes in your developer environment region settings are different from the live environment. In my case, I don’t know what region settings there are in my company servers. For this reason, I created a function to check is a string is a date in a culture and to convert a string to a date. /// /// Determines whether the specified text is date. /// /// The text. /// /// true if the specified text is date; /// otherwise, false. /// public static bool IsDate(this…

Read More

Device name in Xamarin

microsoft xamarin heros c# iOS Android UWP

Using Device Information Plugin for Xamarin and Windows, you have access to same information for a device: GenerateAppId: used to generate a unique Id for your app. Id: this is the device specific Id Device Model: get the model of the device Version: get the version of the Operating System If you want the device name, it’s not in this list. Then for that we can create our functions. IDevice interface First of all we have to create an interface, I call it IDevice. using System; namespace myApp.Interfaces { public…

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

A Simple Speedtest Application

The purpose of this code is the detect how slow is your connection downloading a file from a site. First of all, you have to create a file with a known size: for that you can use fsutil in the prompt (see another post in this blog for info). When yo do put your file in a webserver (or you can use my url), we can create the code to check the connection speed. using System; using System.Collections.Generic; using System.Text; using System.Net; namespace SpeedTest { class Program { static void…

Read More