Move e-books from Adobe Digital Editions to Kindle with Calibre

Just so you know – if you bought books that are not available from Amazon (like Swedish books) and want to read them on your Kindle – there is a plugin for Calibre that will help you do that. Just saying. http://bit.ly/1huf42M

Posted by jdanforth
Filed under:

Form Validation Formatting in ASP.NET MVC 5 and Bootstrap 3

When creating a new MVC project in ASP.NET MVC 5, Bootstrap is already included. For some reason proper formatting for form errors (the red colored error message and the red border around the controls) are not working. There are loads of articles and blog posts how to change this and that to enable this, but in ASP.NET MVC 5, the only thing you actually have to do is add a few classes to your Site.css file. Why they aren’t in there from the outset I don’t know.

Site.css

/* styles for validation helpers */
.field-validation-error {
color: #b94a48;
}

.field-validation-valid {
display: none;
}

input.input-validation-error {
border: 1px solid #b94a48;
}


select.input-validation-error {
border: 1px solid #b94a48;
}

input
[type="checkbox"].input-validation-error {
border: 0 none;
}

.validation-summary-errors {
color: #b94a48;
}

.validation-summary-valid {
display: none;
}

Sample form.cshtml

@model WebApplication6.Models.TestModel

@{
ViewBag.Title = "Home Page";
}
<br /><br />

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
<br />
@Html.ValidationMessageFor(m => m.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.GenderId, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.GenderId, new SelectList(Model.Genders, Model.GenderId), "", new { @class = "form-control" })
<br />
@Html.ValidationMessageFor(m => m.GenderId)
</div>
</div>


<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="OK" />
</div>
</div>
}


Sample TestModel.cs

public class TestModel
{
[Required(ErrorMessage = "Name is required")]
[MinLength(3, ErrorMessage = "Name must be at least 3 letter")]
public string Name { get; set; }
[Display(Name= "Gender")]
[Required(ErrorMessage = "Gender is required")]
public string GenderId { get; set; }

public string[] Genders = new[] {"Male", "Female"};
}


Posted by jdanforth
Filed under: ,

Subsequent calls to AcquireToken()

Using the Active Directory Authentication Library (ADAL) and getting that annoying flash from the authentication dialog on subsequent calls? Maybe you’re creating a new AuthenticationContext every time? In that case the call to AcquireToke() by the context cannot keep and lookup the cached token and refreshtokens. You should try to keep a cached or static version of the AuthenticationContext alive between calls. Something like this of you’re calling a web api or similar:

private static readonly AuthenticationContext AuthenticationContext = new AuthenticationContext("https://login.windows.net/domain.com");

private static AuthenticationResult GetAuthenticationToken()
{
var acquireToken = AuthenticationContext.AcquireToken("https://domain.com/WebApp-something.azurewebsites.net", //resource id of the web api
"acca2f90-5f76-45b5-8ec3------", //the client id
new Uri("https://domain.com/YourClientRedirectUrl")); //client redirect url

return acquireToken;
}

public static async Task<string> GetRequestAsync(string requestUri)
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
var authorizationHeader = GetAuthenticationToken().CreateAuthorizationHeader();
request.Headers.TryAddWithoutValidation("Authorization", authorizationHeader);
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
return responseString;
}

Posted by jdanforth | 1 comment(s)
Filed under: , ,

Secure ASP.NET Web API with Windows Azure AD

Note that the APIs, tools and methods change quickly in this area, this blog post will get old and die eventually…

Many organizations now look at the Azure environment to host their websites and web APIs, and some decide to move their mail and Active Directory too. Now with the latest updates and previews in Azure, you’re able to secure your web APIs with Azure AD. Vittorio Bertocci wrote an article for MSDN Magazine about Secure ASP.NET Web API with Windows Azure AD and Microsoft OWIN Components and it worked fine up until a couple of weeks ago when things moved around in these parts of Azure Smile

I will try to describe in detail how to secure your web API with Azure Active Directory now, using Visual Studio 2013 and the preview of ADAL (Active Directory Authentication Library) package.

Create a web API project

Fire up Visual Studio and create a new ASP.NET Web Application. I’m calling mine “johandanforth”, I’m selecting “Web API” and click the “Change Authentication”

image

In the next dialog, click “Organizational Account” and enter the domain of your Azure AD tenant, in my case it’s “irm.se”:

image

After you press “OK” you’ll be asked to login with your Azure AD account, then “OK” again and Visual Studio will create a web application resource in your Azure AD. Now look it up in the Azure Management application. Note that you may have to log out and in again or restart the Azure management web app to see the newly created application.

In my case the application has been named “johandanforth” and is for securing your development project on localhost. The SIGN-ON URL (also called the APP URL in the management application) is https://localhost:44310/ which can be seen both on the applications overview and if you click on the application and go to the CONFIGURE “tab”:

image

The sign-on url should be the same as where the web API is hosted, in this case the same localhost-settings as you got in the development project web-settings.

Open up web.config of your web API project and have a look at these settings:

    <add key="ida:Audience" value="https://irm.se/johandanforth" />
    <add key="ida:ClientID" value="d169beb7-34bc-441b-8b93-87e3181a1132" />

The “ida:Audience” in web.config correspond to the value of APP ID URI of the application resource in the management portal and the “ida:ClientID” correspond to the CLIENT ID in the portal.

image

Update the web application manifest

Before you any application can access this resource, we must update the “manifest”. Still on the CONFIGURE tab for your web API resource, there should be a MANAGE MANIFEST menu option down at the bottom toolbar. Click it and select “Download Manifest”. It’s a json-text-file, and should save it somewhere where you know is, because we will add a section to it and then upload it again using the same menu option:

image

Open the json-manifest and replace the "appPermissions": [], section with this:

"appPermissions":[
{
"claimValue":"user_impersonation",
"description":"Allow the application full access to the service on behalf of the signed-in user",
"directAccessGrantTypes":[

],
"displayName":"Have full access to the service",
"impersonationAccessGrantTypes":[
{
"impersonated":"User",
"impersonator":"Application"
}
],
"isDisabled":false,
"origin":"Application",
"permissionId":"b69ee3c9-c40d-4f2a-ac80-961cd1534e40",
"resourceScopeType":"Personal",
"userConsentDescription":"Allow the application full access to the service on your behalf",
"userConsentDisplayName":"Have full access to the service"
}
],
 
At the moment, there doesn’t seem to much in way of documentation on this manifest file, but it should work without modifications. I’ll try to write something about this manifest file as soon as I get some more docs on it.
 
Next thing you do is upload the modified manifest file. Note that the portal may give you an error message during upload, but things seems to work anyway! It may look like this:
image

Create a client

Now let’s try and access the sample ValuesController Web API in your development environment using a web browser, Fiddler or similar. In my case it’s https://localhost:44309/api/values and you should get a HTTP/1.1 401 Unauthorized error back. To be able to access the protected resource, you must add a client resource in the AD and configure it to access the web API.

If you are not there already, in the Azure management portal, go to Active Directory, click on your domain name and select the APPLICATIONS tab. Then click the ADD-icon down the center of the bottom toolbar. Then go ahead and select “Add an application my organization is developing”:

image

Enter a name for your client (I’m going with “johandanforth-client”, and make sure you select NATIVE CLIENT APPLICATION because we’re going to write a simple Windows WPF client to call our web API:

image

On the second page, type in a redirect url for your client – it can be anything as long as it is a valid url. I’m going with https://irm.se/johandanforth-client.

image

Your client is now created, but the last step to do is to give permission to our web API. Scroll down to the bottom of the client application CONFIGURE page and look at the “permissions to other applications (preview)” section. In the dropdown marked “select application” you should be able to see and select your web API. You must also select the “Delegated permissions” dropdown and mark the only option available for you. As you can see, the description matches the text in the manifest file:

image

Remember to SAVE!

Almost there, hang on…

Create a Windows WPF application for testing

Add a new Windows WPF Application to your solution, I’m calling it “johandanforth.client”, and create a button with a click-event or something to hold the code that will authenticate and get values from your API. Bring up NuGet and search for “ADAL”, make sure you have “Include Prerelease” selected:

image

Install the prerelease package from February 2014 (it will probably be updated soon), then paste this code into the click-event of that button you created earlier:

using System;
using System.Net.Http;
using System.Windows;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace johandanforth.client
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
//this is to accept dev certificates - do not use in production!
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((a, b, c, d) => true);

var ac = new AuthenticationContext("https://login.windows.net/irm.se"); //ad domain = irm.se

var ar1 = ac.AcquireToken("https://irm.se/johandanforth", //app id uri of the web api
"91b4bc31-92c2-4699-86f5-fa84a718da30", //the client id
new Uri("https://irm.se/johandanforth-client")); //the client redirect uri

var authHeader = ar1.CreateAuthorizationHeader();

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44310/api/values");
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show(responseString);
}
}
}

There are a few lines that must be change to work with your sample code. First change the AuthenticaitonContext to match your Azure AD domain/tenant name:

var ac = new AuthenticationContext("https://login.windows.net/irm.se");

Next look at the code part which acquires a token – this is when the login dialog pops up and asks the user to log in using his or hers organizational account. This line corresponds to the web API uri, which is the same as the “ida:Audience” in your web.config file, so update it to match that value:

var ar1 = ac.AcquireToken("https://irm.se/johandanforth",  

The next line is the client id of the application client you created in Azure AD, look it up and change the id accordingly:

"91b4bc31-92c2-4699-86f5-fa84a718da30",

The last line is the redirect-uri of the client, look it up on the same page in the Azure management portal:

new Uri("https://irm.se/johandanforth-client"));

              

You must also modify the line with the call to the web API method to match your web server localhost settings:

var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44310/api/values");

Now, start the web API program in debug mode and wait until you see the Home Page, then right click and start debug of the WPF client. Click the button and you should be prompted to log in with your organizational account (this is the look of it in Swedish):

image

After a successful login, the code continues and you should be greeted with this:

image

Still with me?

Deploy to Azure

This is all well and good (hopefully), but we want to deploy our web API to Azure and run our clients against it in the cloud. To do that we need to:

1) Create a web site to host our web API in Azure

2) Publish our code to the site

3) Create an Azure AD resource for the web API (VS does this for you)

4) Modify the manifest for the web API (like before)

5) Give the client permission to the new resource (like before)

6) Update web.config and the client code to match the IDs and URIs of the new resources (ida:Audience == APP ID URI == the resource you want to access)

7) Publish the code again (to get the updated web.config uploaded)

8) Run!

Here’s some quick shots of some of the steps. First create a web site in Azure by selecting “WEB SITES” in the left hand menu of the Azure Portal, press the big plus-sign down in the corner and create a custom web site. I’m calling mine “johandanforth” (ignore the error message Winking smile )

image

Now go back to Visual Studio, right click the web API project and select “Publish…”.

image

Press the “Import…” button to download and import the publishing profile of the web site you created, and select the newly created Web Site in the dropdown. Click OK.

image

You have to authenticate one or two times to get past these steps, but should finally get to the last step of the Publish process:

image

When Visual Studio is done publishing, a browser page will open up with the Home Page showing:

image

Visual Studio should now have created a new application resource in the Azure Active Directory, so get back to the portal and have a look at the list of AD applications. A resource named “WebApp-xxxxxxxxx.azurewebsites.net” should be listed there. Note – you may have to sign out and sign in to the portal to show the web api resource. This has happened to me a couple of times!

image

Click on the resource and look at the details in the CONFIGURE tab.

image

Copy the name of the “APP ID URI” and past it into the “ida:Audience” value in the web.config file of your web API project in Visual Studio:

    <add key="ida:Audience" value="https://irm.se/WebApp-johandanforth.azurewebsites.net" />

The same value must also be updated in the WPF client:

var ar1 = ac.AcquireToken(https://irm.se/WebApp-johandanforth.azurewebsites.net,  

You must also (of course) update the call to the web API method to point at the web site in the cloud:

var request = new HttpRequestMessage(HttpMethod.Get, "https://johandanforth.azurewebsites.net/api/values");

We’re not done yet though… now you have to do the same steps you did for the localhost resource earlier - download and update the manifest file for the web API resource and give the client resource permission to use the service.

Finally (yes finally) – publish the web API project again to get the updated web.config file to the cloud site!

Once the code is published, you should be able to run the client successfully.

Please give feedback if you have problems with any step/s of this walkthrough. Other questions, bugs and such is better asked on the Windows Azure Active Directory forum. I’m still learning these things and trying to keep up with the changes Smile

Trust Certificates

Just as a reminder to myself – when developing (this code should be removed in production) you may work with dev certs and get errors like "Could not establish a trust relationship for the SSL/TLS secure channel". This code snippet helps:

System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);

Posted by jdanforth
Filed under:

Productivity Tools for Visual Studio 2013

I just installed the popular extension for VS2013 and it looks better than ever. I especially like the “Structure Visualiser” feature which gives you visual cues to code blocks:

image

Read about it and download here.

Posted by jdanforth

Center Aligning a Table with CSS

So you want to center align a table, try text-align: center and it doesn’t work…. I have to look this up every time, so here goes:

<

table style="margin-left: auto; margin-right: auto;">

This is because text-align applies to inline content, not to a block-level element like a table and this article describes it in detail:

 http://www.granneman.com/webdev/coding/css/centertables/

Thanks Scott Granneman for the detailed article.

Posted by jdanforth

Binding MediaElement to a ViewModel in a Windows 8 Store App

If you want to play a video from your video-library in a MediaElement control of a Metro Windows Store App and tried to bind the Url of the video file as a source to the MediaElement control like this, you may have noticed it’s not working as well for you:

<MediaElement Source="{Binding Url}" />

I have no idea why it’s not working, but I managed to get it going using  ContentControl instead:

<ContentControl Content="{Binding Video}" />

The code behind for this is:

protected override void OnNavigatedTo(NavigationEventArgs e)

{

    _viewModel = new VideoViewModel("video.mp4");

    DataContext = _viewModel;

}

And the VideoViewModel looks like this:

public class VideoViewModel

{

    private readonly MediaElement _video;

    private readonly string _filename;

 

    public VideoViewModel(string filename)

    {

        _filename = filename;

        _video = new MediaElement { AutoPlay = true };

        //don't load the stream until the control is ready

        _video.Loaded += VideoLoaded;

    }

 

    public MediaElement Video

    {

        get { return _video; }

    }

 

    private async void VideoLoaded(object sender, RoutedEventArgs e)

    {

        var file = await KnownFolders.VideosLibrary.GetFileAsync(_filename);

        var stream = await file.OpenAsync(FileAccessMode.Read);

        _video.SetSource(stream, file.FileType);

    }

}

I had to wait for the MediaElement.Loaded event until I could load and set the video stream.

Posted by jdanforth | 3 comment(s)
Filed under: ,

File Activation in Windows RT

The code sample for file activation on MSDN is lacking some code Winking smile so a simple way to pass the file clicked to your MainPage could be:

protected override void OnFileActivated(FileActivatedEventArgs args)

{

    var page = new Frame();

    page.Navigate(typeof(MainPage));

    Window.Current.Content = page;

 

    var p = page.Content as MainPage;

    if (p != null) p.FileEvent = args;

    Window.Current.Activate();

}

And in MainPage:

public MainPage()

{

    InitializeComponent();

    Loaded += MainPageLoaded;

}

void MainPageLoaded(object sender, RoutedEventArgs e)

{

    if (FileEvent != null && FileEvent.Files.Count > 0)

    {

        //… do something with file

    }

}

Posted by jdanforth | 1 comment(s)
Filed under: , , , , ,

Read All Text from Textfile with Encoding in Windows RT

A simple extension for reading all text from a text file in WinRT with a specific encoding, made as an extension to StorageFile:

public static class StorageFileExtensions
{
    async public static Task<string> ReadAllTextAsync(this StorageFile storageFile)
    {
        var buffer = await FileIO.ReadBufferAsync(storageFile);
        var fileData = buffer.ToArray();
        var encoding = Encoding.GetEncoding("Windows-1252");
        var text = encoding.GetString(fileData, 0, fileData.Length);
        return text;
    }
}

Posted by jdanforth
Filed under: , ,
More Posts Next page »