Monthly Archives: April 2012

Twin Cities Code Camp – Day 2

Expressing Yourself with C# Expression Trees – Chad Kulesa

Code == Data

  • Dynamically modify code at run time.
  • Create new code at run time.
  • Translate code to another Langauge (SQL, XPath, etc.)
  • Strongly typed.

Expression<Func<string, bool>> expression = x => x == "Value";

var x = Expresion.Parameter(typeof(string), "x");
Expression<Func<string, bool>> expression =
     Expression.Lambda<Func<string, bool>>(
          body: Expression.Equal(
               left: x,
               right: Expression.Constant("Value")),
          parameters: x);

Lambda

  • Easier to read
  • Don’t need to learn the API
  • Compiler will simplify constant expressions

API

  • Additional commands available
  • Dynamically create expression trees

Expression Trees are Immutable – you cannot change them at runtime.

Most C# programmers use expression trees all of the time without even knowing it. For example, LINQ syntax uses expression trees. Func<T, bool>

Expression trees are not useful for just querying. It also has it’s uses for what is called Fluent Configuration. The logic is that is is much better to get configuration errors at compile time rather than runtime. (Don’t know if I’m in agreement with this – I prefer web.config files for configuration changes. They recycle and restart your app when you change them. You also don’t need to recompile your code to change a configuration.)

Source code for presentation at: http://chadkulesa.com

Extending .NET Applications with MEF Plugins – J Wynia

How to extend .NET Applications with MEF plugins. Not how to create METH-amphetamines.

Why should we bother using an extensible architecture? The dominant reason is that the decision of what code to run is not known at compile time. The classic sign that you should be using a plugin based architecture is that you are using a switch statement with a ton of cases. Another, is if you have an app that needs to act differently depending on what kind of record it is in the context of. If the context matters as to what code you want to run. Another great reason is if you want other developers to build upon your product.

The reason the Microsoft focus is on MEF is because Visual Studio’s plug architecture is all MEF based as of 2010.

"I need a" = "Import"

&quotI need some" = "Import Many"

"I have a" or "I am a" = "Export"

"Match up the needs with the providers" = "Compose"

Source code dealt with a loan processing company that did just that – processed loans – console app.

Loan processors became Interfaces injected into the LoanApplication so that many types of Loan Processors can be defined.

Morphed app to use DI/IoC to import the needed LoanProcessor.

Usually, he creates a default implementation of an Export in the assembly so his app does not throw exceptions if there are no imports/exports found. Because of this, he always includes an AssemblyCatalog in the final composition catalog that contains the executing assembly. J calls this Plugin selection with fallback.

Showed an awesome way to load modules. He usually uses the ImportMany attribute to import everything and let the application choose how to load the modules. His example had a method called ChoosePlugins.

caveat. Metro apps IoC containers only work with MEF.

Source available here.

check out if this then that

Advertisements

Andy Cohen

April 14, 2012

I attended the Social Media presentation given by Brandy Favilla just before lunch.  I’m torn between the following presentations:

Each has it’s benefits. I’m trying to weigh in on which technologies I might actually leverage in upcoming apps and my level of enthusiasm for each.

I’m thinking that the Async talk on the upcoming features of .NET 4.5 will be discussed would be the most broad. Probably on the table will be the Async CTP that should be going RTM by October.

On the other hand, I’m involved in a ton of web apps. SignalR is an emerging technology I’ve wanted to pursue since attending KRTConf in Portland late last year.

Alternatively, considering Dart, which I’ve never heard of – the possibility of a programming alternative to JavaScript is a little daunting. Recently I’ve worked with .less, an abstraction of css which ultimately renders css. It has come not without it’s hiccups. If Dart is anything similar, I do not see wide adoption. Dotless (.less) is a compiled form of less. Without native support in the browser, I do not see this going very far.

Hmm… choices.

Twin Cities Code Camp 2012 – Day 1

This post will be a compilation of my notes from Twin Cities Code Camp 2012.

Understanding WebAPI in ASP.NET MVC 4 – Matt Milner – Rapson 56

What is web api?

  • API for HTTP Services – client and server components
  • WCF vs MVC – why do we need this api?
  • WCF – some people just want HTTP, REST services is complicated. Global error handling is almost impossible. Goal was to make WCF extremely flexible. Transport neutral just like SOAP. Because WCF was trying to cover ALL transports and protocols, HTTP became buried.

MVC was primarily built to pass back a View – typically HTML. JSON/JSONP were after thoughts. This is not a perfect model for RESTful services.

HTTP is a protocol in and of itself. Don’t need another protocol (e.g. SOAP). The protocol has been optimized over the years.

HTTP is widely accessible and MUCH easier to reach ALL devices.

Web API MVC Integration

  • MVC is for web applications
  • Web API is for web APIs
  • what they have in common is usually the model or domain

Cool new features: media type formatters for resource type handling. validation at the handler level which supports cancelation and pass-through instead of lowest level – the action. Better json support with the new System.Json library. Self-hosted testing built upon a partial wcf service stack. Support for OData URI queries. Simply return IQueryable. CONS: partial support for OData – only $page, $filter, and $sort – not $select. Doesn’t seem like the will be adding support for this. There is talk about adding built in support for Expression for DTO transformation on the server side.

There is also talk about combining the ServiceResolver configuration (configuration.ServiceResolver.SetResolver) to support both MVC and WebAPI in the same call. For example, right now you configure your MVC service resolving and a separate configuration for WebAPI service resolving. Simplification of this is on the table. Hopefully by the time the release comes around, we see a unified method.

TAKEAWAY MESSAGE: FORGET COMPLICATED SOAP PROTOCOL which is the standard for RIA Services and WCF. Simplify your api with REST. Forget about the mvc paradigm of method based access to your resources. You now access your resources via GET, POST, PUT, DELETE. You access a resource from a Controller. One controller per type of resource. Web API has content negotiation. It returns the data in the format that your request based on the Accept header. If I want JSON, I get JSON. You could expand upon this to return resources in whatever format you need; image, doc, resume, and more. The same for xml. Etc… Input validation is handled by the model binding mechanisms of MVC which builds a model state object.

Note: WebAPI is NOT a replacement for WCF. If you still need to support multiple endpoints in different protocols (for example pure TCP), then WCF is still the best option out there. If you want a simplified API that will be accessible for the widest audience, consider WebAPI.

NOTE TO SELF: check out $.validator.unobtrusive.revalidate(form, validationResult) – validationResult is the json object; { “Speaker”: “Speaker is required” } – where in this example Speaker is the name attribute of the form input element – this takes a json object and interprets it using jquery.validation unobtrusive. Is this a NEW method?

Async Today and Tomorrow – Joe Mayo – Rapson 54

Talk about the Async CTP. How we use async programming today and how we will use it in the future. The Async CTP hides the complexity of async programming. It leverages the TPL (Tasks Parallel Library).

Why do we need async for UI responsiveness? Ex. click on a button in a Windows Form. The program does some long running operation. The user doesn’t know what is happening until all of a sudden, the UI shows something. NOT A GOOD USER EXPERIENCE.

TPL at it’s core revolves around the Task class. It has a fluent api. Uses continuation methods (similar to callbacks).

  • Language Integration – Changes to C# and VB in .NET. Async – the await and async Context Keywords.
  • Every platform – Desktop, Web, and Device
  • leverage Opportunities – Clarity, lifetime, progress, UI, and exceptions

void functions – regular event handlers
functions that return typeof Task<T>– represents the ongoing operation – get exceptions off of that task. The Task wraps the <T> – it holds information about what happened when it returned the <T>.

Async CTP code looks like synchronous code except for the await and async keywords.

Previous convention was to write methods with the Async as the end of the method name. For example WriteAsync. The new paradigm is to write the method as WriteTaskAsync.

Everything after the await keyword is the continuation.

Multiple tasks in parallel… Task.WhenAll.  Or alternatively, Task.WhenAny.  NEAT!

Task based Async Patterns – continuation, cancellation, etc. Task.Wait(), AggregateException, ae.InnerExceptions, CancellationToken

Notes:  this is going to be a fun library to work with.  I can hardwly wait to get home and start coding!  That was not sarcasm but true enthusiasm.

Android Development for the .NET Developer

This is about native Android development, not developing using PhoneGap or MonoDevelop.

http://mike-marshall.net outlines the way to install the JDK, SDK, and everything you need to get an Android IDE up and running here.

  • android.app.Activity class
  • Combined with layouts (views), represents a single type of work that can be accomplished in your application
  • Reusable
    • Can be chained within your application to build a workflow
    • Can be published for use by other applications through :Intents” (more later)

Outlines how to create an Android Application Project within Eclipse.

The .net delegate event handler does not apply.

Working with resources can be annoying.

“Form” designer is very similar to XAML designer in visual studio.  Nothing is absolutely positioned unless you tell it to be as such.