Microsoft and Open Source

I love open source and have used open source technologies throughout my career. I programmed using the LAMP stack in the early 2000s, worked with Red Hat Linux before RHEL came about and contributed with unit tests and bug fixes to two open source frameworks: one logging framework and one ORM. So when my colleagues and friends knew I joined Microsoft, they were sure I wouldn’t be able to use open source software or publish any source code under an open source license.

Well… times have changed, like, really really changed! …and the Open Source Community is thriving, even at Microsoft. Talk Openly Develop Openly,  aka TODO, is an organization focusing on the challenges and opportunities of managing open source projects.

There is a Microsoft Code of Conduct that you should follow when you join one of Microsoft OSS communities. And yes, the code is for everyone to see. If you can understand it, there is no reason why that “truth” or source code should be hidden from you.

Do you want to contribute shaping the future of the .NET framework ecosystem and create open source solutions using this platform? Do you want to contribute to the a portion of the actual framework? You can, but you should abey by the rules of an open source community, which might not be as forgiving as a closed code one.

Happy coding!

C# Scripting available in the .NET Framework 4.6

I know I have a few friends and coworkers that prefer to have all the scripting done in their language of choice, C#. Before .NET 4.6+ their best bet for automating DevOps tasks in a Windows based infrastructure was, for the most part, PowerShell.

But, if you’re already familiar with the C# syntax and basic namespaces, why can’t you continue to use your favorite language to write scripts?

Well, now you can.

Thanks to the Roslyn compiler project, you can now use the nuget package to use the Scripting API.

The Scripting API, as of today, requires the .NET Framework Desktop 4.6 as a minimum, with the .NET Core this Scripting API should now be cross-platform. I haven’t tried it yet, but will do in a very near future and will blog about my experience using this Scripting API on CentOS.

Some directives that are present in PowerShell might not be present yet on the Scripting API (I’m thinking cd, ls etc), but it is worth the try.

You can also script away using C# in a browser, any browser… And we now have a new file extension for C# scripts => .csx files.

C# Scripting and csx file projects are highly used in creating Bot services hosted on Azure using the RESTful APIs provided by Azure.

Happy coding and I hope you enjoyed the good news of C# Scripting.

Code away!

Role Based Access Control in ASP.NET MVC

Role Based Access Control in ASP.NET MVC is pretty straight forward. There is also a way to do Claims access control, but the most common way is the authorization of a user based on the roles they have in an organization.

This blog post only explains RBAC using ASP.NET Model-View-Controller framework for web applications.

As a developer, to show or hide action links in a View, depending on the user role you can use the following Razor syntax:

@if (User.IsInRole("Administrator"))
{
...
}

On the Controller class, to avoid access to an action if the user types in the URL directly on the browser, we can annotate the action with the Role check tags.

For example, the following code would limit access to any actions on the AdministrationController to users who are  members of the Administrator group.

[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
}

You can specify multiple roles as a comma separated list;

[Authorize(Roles = "HRManager,Finance")]
public class SalaryController : Controller
{
}

The SalaryController  class above will be only accessible by users who are members of the HRManager role or theFinance role.

If you apply multiple attributes then, a user’s HTTP request, accessing the methods on the controller  must be a member of all the roles specified. The following sample requires that a user must be a member of both the PowerUser and ControlPanelUser role before authorization is granted.

[Authorize(Roles = "PowerUser")]
[Authorize(Roles = "ControlPanelUser")]
public class ControlPanelController : Controller
{
}

You can further limit access by applying additional role authorization attributes at the action level;

[Authorize(Roles = "Administrator, PowerUser")]
public class ControlPanelController : Controller
{
    public ActionResult SetTime()
    {
    }
 
    [Authorize(Roles = "Administrator")]
    public ActionResult ShutDown()
    {
    }
}

In the previous code snippet members of the Administrator role or the PowerUser role can access the controller and the SetTime action, but, only members of the Administrator role can access the ShutDown action.

You can also lock down a controller but allow anonymous, unauthenticated access to individual actions.

[Authorize]
public class ControlPanelController : Controller
{
    public ActionResult SetTime()
    {
    }
 
    [AllowAnonymous]
    public ActionResult Login()
    {
    }
}

There is also a way to use Policies for limiting access, but to keep it simple, since we already have the roles defined, we can use the common RBAC for now until we need something more complex.

When the user requests the URL directly they will get a nasty 401 Unauthorized page from IIS if their request is not Authorized.

The Razor code shown on the first code snippet can be used in the View to show the elements on the View, if the User is part of the Administrators role, but if the requestor (user) is not part of the role, he or she will receive a 401 HTTP Unauthorized response.

We can give them a more friendly page explaining they don’t have permissions to access the resources requested and link them to a request access page.

This is what could be done:

For a 401 you will probably be seeing the standard 401 Unauthorized page, even if you have added 401 to the customerrors section in your web.config. When using IIS and Windows integrated Authentication, the check happens before ASP.NET MVC even sees the request.

By editing the Global.asax file you can redirect to a route created for 401 Unauthorized HTTP response errors, sending the user to the “Unauthorized to see this” View (friendly page). The use case for this scenario would be if someone received a link for a View that requires the user to be authorized but  the user has not completed other steps in the process, such as paperwork needed prior to accessing the secure resource.

In the Global.asax:

void Application_EndRequest(object sender, System.EventArgs e)
{
    // If the user is not authorized to see this page or access this function, send them to the error page.
    if (Response.StatusCode == 401)
    {
        Response.ClearContent();
        Response.RedirectToRoute("ErrorHandler", (RouteTable.Routes["ErrorHandler"] as Route).Defaults);
    }
}

and in the Route.config:

     routes.MapRoute(
               "ErrorHandler",
               "Error/{action}/{errMsg}",
                new { controller = "Error", action = "Unauthorized", errMsg = UrlParameter.Optional }
     );

and in the ErrorController class:

public ViewResult Unauthorized()
{
        //Response.StatusCode = 401; 
        // Do not set this or else you get a redirect loop
        return View();
        //where View is the friendly .cshtml page
}

 

Voila!

Happy coding.

I need to get rid of that switch statement. What is the Strategy Pattern?

I’m a big advocate of software maintainability and there is nothing better for that than applying well known patterns to improve the existing code. Each time I see long if..then..else constructs, or switch statements to drive logic, I think of how much better the code would be if we allow encapsulation and use one of my favorite behavioral pattern… => the Strategy Pattern.

StrategyPatternA Strategy is a plan of action designed to achieve a specific goal

This is what this pattern will do for you: “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.” (Gang of Four);

Specifies a set of classes, each representing a potential behaviour. Switching between those classes changes the application behavior. (the Strategy). This behavior can be selected at runtime (using polymorphism) or design time. It captures the abstraction in an interface, bury implementation details in derived classes.

When we have a set of similar algorithms and its need to switch between them in different parts of the application. With Strategy Pattern is possible to avoid ifs and ease maintenance;

Now, how can we digest that in code, now that you got the gist of the problem and want a better solution than your case statements.

This example I’ll be showing is a pure academic exercise:

The problem to solve is given a string as an input, create a parsing algorithm(s) that given a text stream identifies if the text complies with the following patterns. Angle brackets should have an opening and closing bracket and curly brackets should also have an opening and closing bracket, no matter how many characters are in the middle. These algorithms must be tested for performance.

<<>>{}  True
<<{>>}  False
<<<>    False
<<erertjgrh>>{sgsdgf} True


Continue reading I need to get rid of that switch statement. What is the Strategy Pattern?

Java vs. C# access modifiers looked at by a C# programmer

I’m looking into the SCJP 6 as I don’t have hands on experience on Java projects (only academic apps).

I had bookmarked long time ago a great C# vs. Java comparison Dave Obasanjo made:

A COMPARISON OF MICROSOFT’S C# PROGRAMMING LANGUAGE TO SUN MICROSYSTEMS’ JAVA PROGRAMMING LANGUAGE



I noticed tonight that the member’s access modifiers could use some tuning and show:

C# access modifier

Java access modifier

private

private

public

public

internal

Default (package-private)

protected

N/A

internal protected

protected



In Java, a protected member can only be accessed through classes on the same package and through subclasses whether they are on the same package or not.

The protected modifier specifies that the member can only be accessed within its own package (as with package-private or default) and, in addition, by a subclass of its class in another package. Package + Kids access.

The default access modifier in Java happens when a class member has no modifier (the default is also known as package-private). This means the member is only accessible by a class defined within the package.

Adding an empty item to an IList collection at runtime.

How can I add a new empty item to a datasource (BindingSource) if the collection that it contains has objects of unknown type at design time:

if (dataSource.GetType() == typeof(BindingSource))
{
IEnumerator en = dataSource.GetEnumerator();
en.MoveNext();
Type t = en.Current.GetType();

object o = System.Activator.CreateInstance(t, false);

dataSource.Add(o);
}

where dataSource is of type IList.

This was a request to add an empty line to a windows forms combobox and to a listbox.

BindingSource can be bound to any of the following:

  • Object
  • System.Type
  • IEnumerable
  • ICollection
  • IList
  • IListSource
  • IBindingList
  • IBindingListView