RSS

Tag Archives: .net

Unit Testing WIF’s ClaimsPrincipalPermission.CheckAccess

WIF 4.5 has ClaimsPrincipalPermission.CheckAccess method, very useful to check user’s authorization. You can use this as method call or attribute.

// Imperative method call
using System.IdentityModel.Services;
public ActionResult Index()
{
    ClaimsPrincipalPermission.CheckAccess("foo", "bar");

    return View();
}

// Attribute
[ClaimsPrincipalPermission(SecurityAction.Demand, Operation="foo", Resource="bar")]
public ActionResult ViewFoobar()
{
    return View();
}

Either way, how do we unit test this? My approach is to first abstract out ClaimsPrincipalPermission and create a new wrapper class that will be injected to the dependent class.

Abstract Out

using System.IdentityModel.Services;

public class ClaimsPrincipalWrapper : IClaimsPrincipalWrapper
{
    public void CheckAccess(string resource, string action)
    {
        ClaimsPrincipalPermission.CheckAccess(resource, action);
    }
}

Dependency Injection

using System.IdentityModel.Services;

public class HomeController : Controller
{
    private readonly IClaimsPrincipalWrapper _ClaimsPrincipalWrapper;

    public HomeController(IClaimsPrincipalWrapper claimsPrincipalWrapper)
    {
        _ClaimsPrincipalWrapper = claimsPrincipalWrapper;
    }

    public ActionResult Index()
    {
        _ClaimsPrincipalWrapper.CheckAccess("foo", "bar");

        return View();
    }
}

Unit Test

[TestMethod]
public void TestIndex()
{
    // Arrange
    var _claimsPrincipal = new Mock<IClaimsPrincipalWrapper>();
    _claimsPrincipal.Setup(m => m.CheckAccess(It.IsAny<string>, It.IsAny<string>));
    var _controller = new HomeController(_claimsPrincipalMock.Object);

    // Act
    var _result = _controller.Index() as ViewResult;

    // Assert
    Assert.IsTrue(_result.View != null);
}
Advertisements
 
Leave a comment

Posted by on May 4, 2015 in General

 

Tags: , , , , , , ,

Visual Studio 2012: Debugging Unit Tests Doesn’t Work

There’s a problem in Visual Studio 2012 where debugging unit tests doesn’t work. This often happens when you enable code coverage.

The solution is fairly simple, un-check any selected test setting file under Test > Test Settings.

This behavior is expected, at least according to Microsoft, they just don’t support debugging for code coverage.

 
Leave a comment

Posted by on May 1, 2015 in General

 

Tags: , ,

Learning Paths

With so many tutorials, articles and resources available out there on the Internet, learning new programming language, framework and library become much more easier. However, as much as its advantage, readily available resources have also become its own problem: where should I start?

With so many options available, it can be confusing to even start learning. I present you my learning paths to solve this problem. Learning paths will guide you through learning programs for each subject of your interests. Think of this as a curriculum to the degree you want to get.

Most of the courses are from Pluralsight.com, but this learning paths are not limited to just Pluralsight.com. I also include some free courses from other sources. While I understand that you may have to pay for some of these courses, I can assure you that paying the subscription is worth it (especially Pluralsight!).

I will update this learning paths to include more subjects and courses in the future. Stay tuned!

Android

Level Course
0100 Get the Android SDK (http://developer.android.com/sdk/index.html)
0101 Prerequisite: 0100
Getting Started (http://developer.android.com/training/index.html)
0102 Introduction to Android Development (http://pluralsight.com/training/Courses/TableOfContents/android-intro)
0200 Prerequisite: 0101 or 0102
Android Async Programming and Services (http://pluralsight.com/training/Courses/TableOfContents/android-services)

AngularJS

Level Course
0100 AngularJS Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/angularjs-fundamentals)
0200 Prerequisite: 0100
AngularJS In-Depth (http://pluralsight.com/training/Courses/TableOfContents/angularjs-in-depth)
0201 Prerequisite: 0100
Testing AngularJS From Scratch (http://pluralsight.com/training/Courses/TableOfContents/testing-angularjs-from-scratch)

ASP.NET MVC

Level Course
0100 ASP.NET MVC Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/aspdotnet-mvc)
0200 Prerequisite: 0100
ASP.NET MVC 5 Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/aspdotnet-mvc5-fundamentals)

ASP.NET Web API

Level Course
0100 Introduction to the ASP.NET Web API (http://pluralsight.com/training/Courses/TableOfContents/aspnetwebapi)
0200 Prerequisite: 0100
Web API v2 Security (http://pluralsight.com/training/Courses/TableOfContents/webapi-v2-security)
0201 Prerequisite: 0100
Web API Design (http://pluralsight.com/training/Courses/TableOfContents/web-api-design)

C#

Level Course
0100 C# Basic (http://csharp-station.com/Tutorial/CSharp)
0101 C# From Scratch (http://pluralsight.com/training/Courses/TableOfContents/csharp-from-scratch)
0102 Prerequisite: 0101
C# From Scratch – Part 2 (http://pluralsight.com/training/Courses/TableOfContents/csharp-from-scratch-part2)
0200 Prerequisite: 0100 or 0102
Object-Oriented Programming Fundamentals in C# (http://pluralsight.com/training/Courses/TableOfContents/object-oriented-programming-fundamentals-csharp)

Entity Framework

Level Course
0100 Getting Started with Entity Framework 5 (http://pluralsight.com/training/Courses/TableOfContents/entity-framework5-getting-started)
0200 Prerequisite: 0100
Entity Framework Code First Migrations (http://pluralsight.com/training/Courses/TableOfContents/efmigrations)

JavaScript & jQuery

Level Course
0100 W3Schools’s JavaScript Tutorial (http://www.w3schools.com/js/default.asp)
0101 JavaScript Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/jscript-fundamentals)
0120 Prerequisite: 0100 or 0101
DO Factory’s JavaScript + jQuery Design Pattern Framework – JavaScript & Pattern Essentials (http://www.dofactory.com/products/javascript-jquery-design-pattern-framework)
0200 Prerequisite: 0100 or 0101
JavaScript Design Patterns (http://pluralsight.com/training/Courses/TableOfContents/javascript-design-patterns)
0300 Prerequisite: 0200
jQuery Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/jquery-fundamentals)

WIF, Claims-based Identity, OAuth2

Level Course
0100 Introduction to Identity and Access Control in .NET 4.5 (http://pluralsight.com/training/Courses/TableOfContents/iac-intro)
0200 Prerequisite: 0100
Identity and Access Control in ASP.NET 4.5 (http://pluralsight.com/training/Courses/TableOfContents/iac-aspnet)
0201 Prerequisite: 0100
Identity and Access Control in WCF 4.5 (http://pluralsight.com/training/Courses/TableOfContents/iac-wcf)
0202 Prerequisite: 0100
Web API v2 Security (http://pluralsight.com/training/Courses/TableOfContents/webapi-v2-security)
0300 Prerequisite: 0200 or 0201 or 0202
Introduction to OAuth2, OpenID Connect and JSON Web Tokens (JWT) (http://pluralsight.com/training/Courses/TableOfContents/oauth2-json-web-tokens-openid-connect-introduction)
 
1 Comment

Posted by on September 15, 2014 in General

 

Tags: , , , , , , , , , , ,

What is CLR?

The Common Language Runtime (CLR) is the virtual machine component of Microsoft’s .NET framework and is responsible for managing the execution of .NET programs.

A language like C# requires the .NET Common Language Runtime (CLR) to execute. Essentially, as an application that is written in C# executes, the CLR is managing memory, performing garbage collection, handling exceptions, and providing many more services that you, as a developer, don’t have to write code for. The C# compiler produces Intermediate Language (IL) , rather than machine language, and the CLR understands IL. When the CLR sees the IL, it Just-In-Time (JIT) compiles it, method by method, into compiled machine code in memory and executes it. The CLR manages the code as it executes.

Read more: Common Language Runtime – Wikipedia

 
Leave a comment

Posted by on March 21, 2014 in General

 

Tags: ,

Compare Two URL Strings

URL String Compare

What is the best approach to compare two URLs and determine if they are the same or not?

For example:
https://stack247.wordpress.com and stack247.wordpress.com are the same URL.
https://stack247.wordpress.com and stack247.wordpress.com are the same URL.
https://stack247.wordpress.com/tag/interview-question/ and stack247.wordpress.com/tag are NOT the same URL.

 
Leave a comment

Posted by on July 31, 2013 in General

 

Tags: , , ,

HttpWebRequest x WebRequest x WebClient (x HttpRequest)

Differences

What are all the differences? Well, first off, let’s look at the inheritance hierarchy for each one of them.

HttpWebRequest

System.Object
    System.MarshalByRefObject
        System.Net.WebRequest
            System.Net.HttpWebRequest

WebRequest

System.Object
    System.MarshalByRefObject
        System.Net.WebRequest

WebClient

System.Object
    System.MarshalByRefObject
        System.ComponentModel.Component
            System.Net.WebClient

HttpRequest

System.Object
    System.Web.HttpRequest

Based on that findings, we know that HttpWebRequest inherits from WebRequest. They both have general purposes of sending and receiving data through a network connection. There are also FileWebRequest and FtpWebRequest classes that inherit from WebRequest. Normally, you would use WebRequest to, well, make a request and convert the return to either HttpWebRequest, FileWebRequest or FtpWebRequest, depend on your request. Below is an example:


var _request = (HttpWebRequest)WebRequest.Create("https://stack247.wordpress.com");
var _response = (HttpWebResponse)_request.GetResponse();

WebClient

WebClient provides common operations to sending and receiving data from a resource identified by a URI. Simply, it’s a higher-level abstraction of HttpWebRequest. This ‘common operations’ is what differentiate WebClient from HttpWebRequest, as also shown in the sample below:

var _client = new WebClient();
var _stack247Content = _client.DownloadString("https://stack247.wordpress.com");</code>

There are also DownloadData and DownloadFile operations under WebClient instance. These common operations also simplify code of what we would normally do with HttpWebRequest. Using HttpWebRequest, we have to get the response of our request, instantiate StreamReader to read the response and finally, convert the result to whatever type we expect. With WebClient, we just simply call DownloadData, DownloadFile or DownloadString.

However, keep in mind that WebClient.DownloadString doesn’t consider the encoding of the resource you requesting. So, you would probably end up receiving weird characters if you don’t specify and encoding.

HttpRequest

Unlike any other classes mentioned in this post, HttpRequest has nothing to do with sending and receiving data. Well, sort of. When a request is made from a client to your application, you can access this request through HttpRequest class.

In short, it’s kind of like this: HttpWebRequest, WebRequest and WebClient are client-classes which mean they are the one making a request to a resource, or a server. HttpRequest is sitting on that resource’s (or server’s) side, interpreting the request by reading its HttpRequest object.

 
Leave a comment

Posted by on July 26, 2013 in General

 

Tags:

Windows Identity Foundation (WIF): A Potentially Dangerous Request.Form Value Was Detected from the Client (wresult=”<trust:RequestSecuri…")

windows-identity-foundation-wif-a-potentially-dangerous-request-form-value-was-detected-from-the-client-wresult

On WIF 3.5, the token is sent in XML-like format, contains tags. The error is caused by request validation in ASP.NET feature to reject request with any tag. This feature prevents cross-site scripting attack (XSS).

Quick Workaround

To workaround this issue, add the following config in your ASP.NET application’s web.config:

<system.web>
    <httpRuntime requestValidationMode="2.0" />
</system.web>

This tells the ASP.NET to only perform request validation on .aspx pages – (2.0 represents ASP.NET 2.0). The request validation will not apply to all other pages / routings, so if you are on ASP.NET MVC (2, 3 or 4), disabling this open your application to the cross-site scripting attack.

Solution

To properly handle the exception error, create a class to validate the request.

This is what I have on my ASP.NET MVC 4.0

web.config

<system.web>
    <httpRuntime requestValidationType="WsFederationRequestValidator" />
</system.web>

Request validator class

public class WsFederationRequestValidator : RequestValidator
{
    protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
    {
        validationFailureIndex = 0;
        if (requestValidationSource == RequestValidationSource.Form && !String.IsNullOrEmpty(collectionKey) && collectionKey.Equals(WSFederationConstants.Parameters.Result, StringComparison.Ordinal))
        {
            var _unvalidatedFormValues = System.Web.Helpers.Validation.Unvalidated(context.Request).Form;

            SignInResponseMessage _message = WSFederationMessage.CreateFromNameValueCollection(WSFederationMessage.GetBaseUrl(context.Request.Url), _unvalidatedFormValues) as SignInResponseMessage;

            if (_message != null)
            {
                return true;
            }
        }

        return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
    }
}
 
Leave a comment

Posted by on June 12, 2013 in General

 

Tags: , , ,

 
%d bloggers like this: