Skip to content

Jimmy Bogard
Syndicate content
Strong opinions, weakly held
Updated: 6 hours 8 min ago

C# 6 Exception Filters Will Improve Your Home Life

Fri, 07/17/2015 - 23:00

If you’re like me and you enjoy nice, peaceful weekends, but keep getting hassled when something bad happens in production to shatter the blissful silence you’re enjoying, a great new feature of C# 6 will help you out:

try {
  // Do stuff
} catch (Exception e) when (
  (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
  || (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)) {
  // Swallow
}

Swallow exceptions – but only on weekends! Now you won’t get bothered any more, the app will always be up and running! The error logs will be nice and clean as if nothing has gone wrong at all.

This can be extended if it’s just one person hassling you a lot:

try {
  // Do stuff
} catch (Exception e) when (Thread.CurrentPrincipal.Identity.Name == "JBOGARD") {
  // Swallow
}

The possibilities are endless.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

Entity Framework extensions for AutoMapper

Wed, 07/08/2015 - 16:12

I pushed out a little library I’ve been using for the last couple years for helping to use AutoMapper and Entity Framework together. It’s a series of extension methods that cuts down the number of calls going from a DbSet to DTOs. Instead of this:

Mapper.CreateMap<Employee, EmployeeDto>()
  .ForMember(d => d.FullName, opt => opt.MapFrom(src => src.FirstName + " " + src.LastName));

var employees = await db.Employees.ProjectTo<EmployeeDto>().ToListAsync();

You do this:

public class Employee {
  [Computed]
  public string FullName { get { return FirstName + " " + LastName; } }
}
Mapper.CreateMap<Employee, EmployeeDto>();

var employees = await db.Employees.ProjectToListAsync<EmployeeDto>();

The extension methods themselves are not that exciting, it’s just code I’ve been copying from project to project:

public static async Task<List<TDestination>>
  ProjectToListAsync<TDestination>(this IQueryable queryable)
{
  return await queryable
    .ProjectTo<TDestination>()
    .DecompileAsync()
    .ToListAsync();
}

I have helper methods for:

  • ToList
  • ToArray
  • ToSingle
  • ToSingleOrDefault
  • ToFirst
  • ToFirstOrDefault

As well as all their async versions. You can find it on GitHub:

https://github.com/AutoMapper/AutoMapper.EF6

And on NuGet:

https://www.nuget.org/packages/automapper.ef6

Enjoy!

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

AutoMapper dev builds moved to MyGet

Tue, 07/07/2015 - 20:08

I’m moving the dev builds for AutoMapper to MyGet, here:

https://www.myget.org/F/automapperdev/api/v2

I’ll still have pre-release builds on NuGet, but it’ll be a little less noisy having the NuGet builds be only builds from master.

<eom>

 

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

NDC talk on SOLID in slices not layers video online

Thu, 07/02/2015 - 20:21

The talk I gave at NDC Oslo 2015 is up on SOLID architecture in slices not layers:

https://vimeo.com/131633177

In it I talk about flipping this style architecture:

To one that focuses on vertical deliverable features:

Enjoy!

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

End-to-end Hypermedia: Building a React Client

Wed, 07/01/2015 - 18:06

In the last post, I walked through what is to me the most interesting part of REST – the client. It’s easy to build a server API, but no API is complete without someone actually using that API. This is where most REST examples fall down for me – they show all sorts of pretty pictures of hypermedia-rich JSON from the server, but no real examples of how to consume that API.

I walked through some jQuery code in the last post, but why stop with jQuery? That’s so 2010. Instead, I want to build around React. React is perfect for hypermedia because of its component-oriented nature. A resource’s representation can be broken down into its components, and React components then matched accordingly. But before we get into the client, I’ll need to modify my sample to consume React.

Installing React

As a shortcut, I’m just going to use ReactJS.Net to build React into my existing MVC app. I install the ReactJS.Net NuGet package, and add a script reference to my downloaded react.js library. Normally, I’d go through the whole Bower/npm path, but this seemed like the simplest path to integrate into my sample.

I’m going to create just a blank JSX file for all my React components for this page, and slim down my Index view to the basics:

<h2>Instructors</h2>
<div id="content"></div>
@section scripts{
    <script src="@Url.Content("~/Scripts/react-0.13.3.js")"></script>
    <script src="@Url.Content("~/Scripts/InstructorInfo.jsx")"></script>
    @{
        var href = Url.Action("Index", "Instructor", new {httproute = ""});
    }
    <script>
        React.render(
            React.createElement(InstructorsInfo, {href: '@href'}),
            document.getElementById("content")
        );
    </script>
}

All of the div placeholders are removed except one, for content. I pull in the React library and my custom React components. The ReactJS.Net package takes my JSX file and transpiles it into Javascript (as well as builds the needed files for in-browser debugging). Finally, I render my base React component, passing in the root URL for kicking off the initial request for instructors, and the DOM element in which to render the React component into.

Once I’ve got the basic React library up and running, it’s time to figure out how we would like to componentize our page.

Slicing our Page

If we look at the page we want to create, we need to take this page and create React components from the parts we find. Here’s our page from before:

Looking at this, I see three individual tables populated with collection+json data. I’m thinking I create one overall component composed of three individual items. Inside the table, I can break things up into the table, rows, header, cells and links:

I might need a few more, but this is a good start. Next, we can start building our React components.

React Components

First up is our overall component that contains our three tables of collection+json data. Since I have an understanding of what’s getting returned on the server side, I’m going to make an assumption that I’m building out three tables, and I can navigate links to drill down to more. Additionally, this component will be responsible for making the initial AJAX call and keeping the overall state. State is important in React, and I’ve decided to keep the parent component responsible for the resource state rather than each table. My InstructorInfo component is:

class InstructorsInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      instructors: { },
      courses: { },
      students: { }
    };
    this._handleSelect = this._handleSelect.bind(this);
  }
  componentDidMount() {
    $.getJSON(this.props.href)
      .done(data => this.setState({ instructors: data }));
  }
  _handleSelect(e) {
    $.getJSON(e.href)
      .done(data => {
        var state = e.rel === "courses"
          ? { students: {}}
          : {};

        state[e.rel] = data;

        this.setState(state);
      });
  }
  render() {
    return (
      <div>
        <CollectionJsonTable data={this.state.instructors}
          onSelect={this._handleSelect} />
        <CollectionJsonTable data={this.state.courses}
          onSelect={this._handleSelect} />
        <CollectionJsonTable data={this.state.students}
          onSelect={this._handleSelect} />
      </div>
    )
  }
}

I’m using ES6 here, which makes building React components a bit nicer to work with. I first declare my React component, extending from React.Component. Next, in my constructor, I set up the initial state, a object with empty values for the instructors/courses/students state. Finally, I set up the binding for a callback function to bind to the React component as opposed to the function itself.

In the componentDidMount function, I perform the initial AJAX call and set the instructors collection state based on the data that gets back. The URL I use to make the initial call is based on the “href” of my components properties.

The _handleSelect function is the callback of the clicked link way down on one of the tables. I wanted to have the parent component manage fetching new collections instead of a child component figuring out what to do. That method makes the AJAX call based on the “href” passed in from the collection+json data, gets the state back and updates the relevant state based on the “rel” of the link. To make things easy, I matched up the state’s property names to the rel’s I knew about.

Finally, the render function just has a div with my three CollectionJsonTable components, binding up the data and select functions. Let’s look at that component next:

class CollectionJsonTable extends React.Component {
  render() {
    if (!this.props.data.collection) {
      return <div></div>;
    }
    if (!this.props.data.collection.items.length){
      return <p>No items found.</p>;
    }

    var containsLinks = _(this.props.data.collection.items)
      .some(item => item.links && item.links.length);

    var rows = _(this.props.data.collection.items)
      .map((item, idx) => <CollectionJsonTableRow
        item={item}
        containsLinks={containsLinks}
        onSelect={this.props.onSelect}
        key={idx}
        />)
      .value();

    return (
      <table className="table">
        <CollectionJsonTableHeader
          data={this.props.data.collection.items}
          containsLinks={containsLinks} />
        <tbody>
          {rows}
        </tbody>
      </table>
    );
  }
}

This one is not quite as interesting. It only has the render method, and the first part is just to manage either no data or empty data. Since my data can conditionally have links, I found it easier to inform child components whether or not links exist (through the lodash code), rather than every component having to re-figure this out.

To build up each row, I map the collection+json items to CollectionJsonTableRow components, setting up the necessary props (the item, containsLinks, onSelect and key items). In React, there’s no event aggregator so I have to pass down a callback function to the lowest component via properties all the way down. Finally, since I’m building a collection of components, it’s best practice to put some sort of key on these items so that React knows how to re-render correctly.

The final rendered component is a table with a CollectionJsonTableHeader and the rows. Let’s look at that header next:

class CollectionJsonTableHeader extends React.Component {
  render() {
    var headerCells = _(this.props.data[0].data)
      .map((datum, idx) => <th key={idx}>{datum.prompt}</th>)
      .value();

    if (this.props.containsLinks) {
      headerCells.push(<th key="links"></th>);
    }

    return (
      <thead>
        <tr>
          {headerCells}
        </tr>
      </thead>
    );
  }
}

This component also only has a render method. I map the data items from the first item in the collection, producing header cells based on the prompt from the collection+json data. If the collection contains links, I’ll add an empty header cell on the end. Finally, I render the header with the header cells in a row.

With the header done, I can circle back to the CollectionJsonTableRow:

class CollectionJsonTableRow extends React.Component {
  render() {
    var dataCells = _(this.props.item.data)
      .map((datum, idx) => <td key={idx}>{datum.value}</td>)
      .value();

    if (this.props.containsLinks) {
      dataCells.push(<CollectionJsonTableLinkCell
        key="links"
        links={this.props.item.links}
        onSelect={this.props.onSelect} />);
    }

    return (
      <tr>
        {dataCells}
      </tr>
    );
  }
}

The row’s responsibility is just to build up the collection of cells, plus the optional CollectionJsonTableLinkCell. As before, I have to pass down the callback for the link clicks. Similar to the header cells, I fill in the data value (instead of the prompt). Next up is our link cell:

class CollectionJsonTableLinkCell extends React.Component {
  render() {
    var links = _(this.props.links)
      .map((link, idx) => <CollectionJsonTableLink
        key={idx}
        link={link}
        onSelect={this.props.onSelect} />)
      .value();

    return (
      <td>{links}</td>
    );
  }
}

This one isn’t so interesting, it just loops through the links, building out a CollectionJsonTableLink component, filling in the link object, key, and callback. Finally, our CollectionJsonTableLink component:

class CollectionJsonTableLink extends React.Component {
  constructor(props) {
    super(props);
    this._handleClick = this._handleClick.bind(this);
  }
  _handleClick(e) {
    e.preventDefault();
    this.props.onSelect({
      href : this.props.link.href,
      rel: this.props.link.rel}
    );
  }
  render() {
    return (
      <a href='#' rel={this.props.link.rel} onClick={this._handleClick}>
        {this.props.link.prompt}
      </a>
    );
  }
}
CollectionJsonTableLink.propTypes = {
  onSelect: React.PropTypes.func.isRequired
};

The link clicks are the most interesting part here. I didn’t want my link itself to have the behavior of what to do on click, so I call my “onSelect” prop in the click event from my link. The _handleClick method calls the onSelect method, passing in the href/rel from the collection+json link object. In my render method, I just output a normal anchor tag, with the rel and prompt from the link object, and the onClick event bound to the _handleClick method. Finally, I indicate that the onSelect prop is required, so that I don’t have to check for its existence when the link is clicked.

With all these components, I’ve got a working example:

I found working with hypermedia and React to be a far nicer experience than just raw jQuery. I could reason about individual components at the same level as the hypermedia controls, matching what I was building much more effectively to the resource representation returned. I still have to have some sort of knowledge of how I’m going to navigate the links and what to do, but that logic is all encapsulated in my topmost component.

Each of the sub-components aren’t tied to my overall logic and can be re-used as much as I want across my application, allowing me to use collection+json extensively and not worry about having to parse the result again and again. I’ve got a component that can effectively render a nice table based on a collection+json representation.

Next, we’ll kick things up a notch and build out a React.Native implementation, pushing the limit of hypermedia with a dynamic native mobile client.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

End-to-End Hypermedia: Building the Client

Thu, 06/18/2015 - 14:41

Now that we’ve built our hypermedia-rich server component, we can focus now on the client portion. Building the server piece, while somewhat involved, isn’t too much different than building a plain JSON API. We had to build a piece to translate our model to a richer hypermedia model, but I don’t see this as much different than what I have to do with views/templates.

The client is a completely different story. My payloads coming back from the server have a lot of metadata in them, and in order to achieve the loose coupling that REST can provide, my clients have to be driven off of that metadata.

Ultimately, my clients can’t be completely agnostic of what we’re doing on the server. A general-purpose client for a standard hypermedia format will look generic and boring. We’re not trying to build a generic client, we’re building one for a specific purpose.

In my case, I’d like to build a basic navigable details screen. Show a table of information, and supply links to drill down into further details.

First, I’ll need to have some understanding of what the server response looks like. I know I’ll have a list of instructors, then a list of courses, then a list of students attending those courses. Each of these will be a table, but I want a place to put that table on the screen. For this, I’ll create divs with IDs that match the RELs of the links in my collection+json response:

<div id="instructors"></div>
<div id="courses"></div>
<div id="students"></div>

When the page loads, I want to kick off the rendering with an initial request:

$(function () {
    fetchCollection('/instructors', 'instructors');
});

Nothing much going on here, I just call a method “fetchCollection”. I pass in the initial URL to hit, and the ID of DIV. The fetchCollection method:

var fetchCollection = function(relativeUrl, target) {
    $.getJSON(root + relativeUrl)
        .done(function (data) {
            renderCollectionJsonTable(data, target);
        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });
};

Will make a call to the API, return the result and render the result to the target DIV via the “renderCollectionJsonTable” method:

var renderCollectionJsonTable = function(data, target) {
    var $target = $('#' + target);
    $target.html('');

    var $table = $('<table>').addClass('table');
    var hasAddedHeader = false;
    var hasLinks = false;

    $.each(data.collection.items, function (idx, item) {

        if (item.links) {
            hasLinks = true;
        }

        if (!hasAddedHeader) {
            var $headerRow = $('<tr>');
            $.each(item.data, function(idx2, datum) {
                $('<th>').text(datum.prompt).appendTo($headerRow);
            });
            if (hasLinks) {
                $('<th>').appendTo($headerRow);
            }
            $headerRow.appendTo($table);
            hasAddedHeader = true;
        }

        var row = $('<tr>');
        $.each(item.data, function (idx2, datum) {
            var $cell = $('<td>');
            if (datum.value) {
                $cell.text(datum.value);
            }
            $cell.appendTo(row);
        });

        if (hasLinks) {
            var $linkCell = $('<td>');
            $.each(item.links, function (idx2, link) {
                var $link = $('<a>').attr('rel', link.rel).attr('href', '#').text(link.prompt + ' ');
                $link.click(function () {
                    fetchCollection(link.href, link.rel);
                    return false;
                });
                $link.appendTo($linkCell);
            });
            $linkCell.appendTo(row);
        }

        row.appendTo($table);
    });

    $table.appendTo($target);
};

This method is…quite involved. We’re trying to render a table, including the header and links. To render the header, I loop through the collection+json data elements and pluck off the prompt for the header text. If the data elements have links, then I render an extra column at the end.

I only render the header once, and since collection+json includes prompt information for every single element in the collection every single time, I have to just pluck off the first item in the collection and render the header row for it (assuming the prompts don’t change).

For rendering the actual data row, it’s pretty straightforward to loop through the data items and render the data portion for each one. Finally, if the item has links, I’ll render all the links together, using the link prompt and rel to indicate where to place the linked data on the screen.

The method to render a table of collection+json data is relatively decoupled from what the collection+data represents. The only real app-specific piece is how to navigate the collections and what to do in each case (render results in a new DIV).

Rendering the table was rather too involved for my taste, and I’d like to componentize it if I can. In the last post, I’ll look at using ReactJS to build React components for the different rendering pieces in the table.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs