DNCMag 201507 ThirdAnniv Issue19
DNCMag 201507 ThirdAnniv Issue19
CONTENTS
Transitioning from WPF
ASP.NET WEB ItemsControl
API 2 TO MVC 6 Fundamentals
08 42
86 68
Art Director
Minal Agarwal
minalagarwal@a2zknowledgevisuals.com
Contributing Authors
Ahmed Ilyas
Craig Berntson
Filip W
Kent Boogaart
Kunal Chandratre
Mahesh Sabnis
Punit Ganshani
Ravi Kiran
Shoban Kumar
Subodh Sohoni
Technical Reviewers
Damir Arh
Mahesh Sabnis
Shoban Kumar
Suprotim Agarwal
Next Edition
1st Sep 2015
www.dotnetcurry.com/magazine
Legal Disclaimer:
The information in this magazine has been
reviewed for accuracy at the time of its POWERED BY
publication, however the information is distributed
without any warranty expressed or implied.
Windows, Visual Studio, ASP.NET, Azure, TFS & other Microsoft products & technologies are trademarks of the Microsoft group of companies. ‘DNC Magazine’ is an independent
publication and is not affiliated with, nor has it been authorized, sponsored, or otherwise approved by Microsoft Corporation. Microsoft is a registered trademark of Microsoft
corporation in the United States and/or other countries.
FROM THE
EDITOR
If you want to grow old running websites or
publishing magazines, you can’t do it alone.
Today when we reach this milestone of 3 years,
my note isn’t meant to be a retrospective nor
am I looking out to share any future plans. I
simply want to express my gratitude, if you will.
@filip_woj @ganshani
@kent_boogaart @kunalchandratre
WRITE FOR US
W
hile some of the concepts
(controllers, filters and so
on) may look similar at first
glance, because of Microsoft's
approach to rewrite everything from
scratch, transitioning your applications
from current Web API application model to
MVC 6 is actually not that simple.
WebApiCompatibilityShim
FROM
framework - and WebApiCompatShim
provides just that - a nice bridge between
the old Web API 2 world and the modern
reality of ASP.NET 5.
WEB API 2
be more used to, from Web API 2.
TO MVC 6
WebApiCompatShim introduces, that
are missing in MVC 6 but existed in Web
API; is the same as it used to be in the
Web API framework. Additionally, the
shim also references System.Net.Http for
This article will look at the parallels between the you in order to reintroduce the familar
Web API framework pipeline and the upcoming MVC 6 classes of HttpRequestMessage and
framework - attempting to ease your transition into the HttpResponseMessage.
new ASP.NET 5 world.
All of this to minimize the pain related
www.dotnetcurry.com/magazine 9
ModelStateDictionary modelState); (MediaTypeFormatter, HttpError) or System.Net.
Http specific (MediaTypeHeaderValue).
public static HttpResponseMessage
CreateErrorResponse(this
HttpRequestMessage request, The shim introduces several other pain-relieving
HttpStatusCode statusCode, HttpError mechanisms, all of which I have discussed
error); extensively in an article at http://www.strathweb.
com/2015/01/migrating-asp-net-web-api-mvc-6-
public static HttpResponseMessage exploring-web-api-compatibility-shim/.
CreateResponse<T>(this
HttpRequestMessage request, T value);
//process context.Response
} TypeFilters allow you to have a custom filter
} class instantiated on demand for each request
(potentially with extra parameters). Consider the
following example:
www.dotnetcurry.com/magazine 11
[TypeFilter(typeof(MyFilter))]public first place, otherwise this code would produce an
ActionResult Process(); error. On the contrary, in our previous example, our
MyFilter class didn't need to be registered in the
This allows you to write a MyFilter class, container - however it could consume dependencies
implementing IFilter itself, and have it that were coming from the container.
instantiated for you on every request. Why would you
want this? To have constructor dependency injection One extra feature worth mentioning is that MVC 6
into your filter! Normally this was not allowed in Web filters are sortable out-of-the-box, so each filter
API without heavily modifying the filter pipeline. In will have an Order property. Web API 2 lacked this
this case, MyFilter could look as follows: feature and that was actually quite constraining.
public class MyFilter : IActionFilter
DependencyResolver vs built in
{
private IMyFancyService _fancy; dependency injection
public MyFilter(IMyFancyService fancy) In ASP.NET Web API, the most common way to
{
enable dependency injection was to use the
_fancy = fancy;
} IDependencyResolver abstraction. Out-of-the-
box, DI was not possible - you had to explicitly
public void enable it by plugging in one of the community-
OnActionExecuted(ActionExecutedContext provided implementations; pretty much every
context) major IoC container for .NET had its own
{
IDependencyResolver version.
//do stuff
}
Another option in Web API was to create a custom
public void IHttpControllerActivator, which was
OnActionExecuting(ActionExecutingContext responsible for instantiating controllers. There you
context)
could either resolve them by hand, or from a global
{
//do stuff DI container of your choice.
}
} As far as dependency injection into other
components in the Web API pipeline - message
In other words, IMyFancyService above is actually handlers, filters, formatters - constructor
being resolved from the built-in ASP.NET 5 IoC dependency injection was generally not supported.
container. You can also pass some extra arguments to The only reasonable workaround was to use a
the constructor of MyFilter explicitly - TypeFilter service-locator like approach - obtain an instance
exposes Arguments object array for that. of a registered IDependencyResolver from the
current HttpRequestMessage and use it to resolve
ServiceFilters are similar, only a bit simpler. Consider the necessary dependencies.
the following signature:
[ServiceFilter(typeof(OtherFilter))] In ASP.NET MVC 6 things are much cleaner - as the
public ActionResult Process(); underlying ASP.NET 5 runtime supports dependency
injection out-of-the-box, without the need of
In this case, OtherFilter will be immediately plugging in an external IoC container. The built-in
resolved from the ASP.NET 5 IoC container (where ASP.NET 5 IoC container is not very sophisticated,
you'd normally register services) - hence the name but it will fill the majority of needs most of the time.
"service". Obviously, that type would also need to
implement IFilter. Because the filter in this You configure the ASP.NET 5 DI in the Startup
case would be attempted to be obtained from the class, inside the ConfigureServices method.
container, it must have been registered in it in the
www.dotnetcurry.com/magazine 13
• POST /item?quantity=1&name=foo, empty attribute should be applied.
body
public class
• POST /item?quantity=1, body: FromBodyApplicationModelConvention :
name=foo, content-type: application/x- IApplicationModelConvention {
www-form-urlencoded public void Apply(ApplicationModel
application)
• POST /item, body: {
name=foo&quantity=1, content-type: foreach (var controller in
application/x-www-form-urlencoded application.Controllers)
{
In other words, you are able to mix-and-match foreach (var action in controller.
Actions)
between body parameters and query parameters, {
however - and this is very important - this approach foreach (var parameter in action.
will only work for application/x-www-form- Parameters)
urlencoded content type. If you try to send your {
body as JSON or XML, the default MVC 6 input if (parameter.BinderMetadata is
binding behavior will not pick it up, and only bind IBinderMetadata ||
ValueProviderResult.
from query string! MVC 6 does not even support CanConvertFromString(parameter.
working with JSON out of the box - the following ParameterInfo.ParameterType))
request will not be bound correctly: {
// behavior configured or simple
type so do nothing
POST /item }
Content-Type: application/json else
{"name": "foo", "quantity": 1} {
// Complex types are by-default
This is obviously much different from the traditional from the body.
parameter.BinderMetadata = new
Web API behavior and can come back to haunt FromBodyAttribute();
you if you are not aware of these model binding }
changes. }
}
In order to force your API to use formatters to }
}
deserialize JSON/XML input from the body, you have }
to explicitly decorate your action parameter with
[FromBody] attribute.
Then you have to enable this convention in the
[Route("item")] Startup class.
public void Post([FromBody]Item item) {}
services.Configure<MvcOptions>(opt =>
You can also do it globally, for your entire {
opt.ApplicationModelConventions.
application, which changes the default behavior Add(new
of MVC 6 to more Web API-like. The code FromBodyApplicationModelConvention());
below utilizes an extensibility point called });
IApplicationModelConvention that allows
you to iterate through all controllers, actions Similarily as in Web API, once you have decided
and parameters of all MVC 6 endpoints at the to use [FromBody] in your action, you can only
application startup and programmatically read one thing from the body, that is the following
alter them. Because of that, you can inject signature will be invalid:
FromBodyAttribute without having to manually
add it everywhere. In there you could also establish [Route("test")]
your own convention or logic about when this given public void Post([FromBody]Item item1,
[FromBody]Item item2) {}
www.dotnetcurry.com/magazine 15
API 2 was IHttpActionResult, which was Content negotiation
used as a return type from an action, and
was really an interface representing various
In ASP.NET Web API, content negotiation was
factories for HttpResponseMessage. In fact,
handled by IContentNegotiator interface.
Web API shipped with a large number of
Normally, you would not use it directly, as the
implementations of IHttpActionResult
framework would handle content negotiation
in the box that you could use straight away
for you - when you returned a POCO object from
in your API - such as BadRequestResult or
an action (instead of HttpResponseMessage
CreatedNegotiatedContentResult<T> to name a
or IHttpActionResult), or when you
few.
called one of the extension methods on the
HttpRequestMessage (i.e. CreateResponse).
On the other hand, classic MVC framework has
However, in some scenarios (for example
long had ActionResult as a base abstract
determining the response media types for caching
type representing various responses. MVC 6 has
purposes) you'd need direct access to the ConNeg
been aligned closely with that approach, and
engine.
IActionResult is the new abstraction that should
be used in your actions. Since Web API and MVC
To facilitate these types of (now legacy) use cases,
frameworks have been unified in MVC 6, various
WebApiCompatibilityShim actually reintroduces
IActionResult implementations can handle both
all of the types involved in the content negotiation
traditional API scenarios (i.e. content negotiated
- so not only IContentNegotiator, but also
object responses, No Content responses) and
DefaultContentNegotiator (the default
traditional MVC scenarios (i.e. view results).
implementation) or ContentNegotiationResult.
So all your old content negotiation code can be
public interface IActionResult
{ pretty much ported verbatim to ASP.NET MVC 6.
Task ExecuteResultAsync(ActionContext
context); On the other hand, ASP.NET MVC 6 does not
} have explicit service dedicated to running
content negotiation. Instead, the logic
Obviously, there are plenty of implementations of responsible for selecting the relevant formatter
that interface that come bundled in the framework is baked into the ObjectResult class. Inside its
itself, many of which can be mapped one to one to ExecuteResultAsync, responsible for writing
IHttpActionResult implementations from Web to the response stream, the framework will walk
API - for example BadRequestObjectResult is the through the available formatters and select a
rough equivalent of the old BadRequestResult. relevant one.
When building HTTP APIs with MVC 6, you will find
yourself working the most with ObjectResult The logic for choosing a formatter is similar to that
which is the type of IActionResult that has in ASP.NET Web API, and based on the following
content negotiation built in - more on that later. order of precedence:
Interestingly, when working with Web API, one of the • Accept header
annoyances was the lack of IHttpActionResults
• Content-Type header
that dealt with serving files, and more generally
• selection based on type match
speaking, binary content. Such components would
have to be built by hand or referenced through open
source packages that grew around Web API in its ASP.NET Web API also had a very useful concept of
vibrant community. This has been addressed in MVC 6, MediaTypeMappings. Mappings allowed you to
which introduces several specialized action results in override content negotiation for specific request
that area - FileContentResult, FilePathResult, structure - an extension (i.e. .json), querystring
FileResult and FileStreamResult. (i.e. ?format-json) or a predefined header (i.e.
Format: json).
The whole mechanism is a little less extensible Finally, we should also briefly touch on the
than it used to be in Web API - in order to use this, changes in the configuration of the framework. In
you are forced to create a route with a format Web API, everything was controlled through the
placeholder or use a format querystring. Example HttpConfiguration type, which was the gateway
routes are shown below: to all important Web API components:
What's interesting is that ASP.NET MVC 6 maps json public class MvcOptions
format to application/json out of the box. This {
means that by simply appending a ?format=json public AntiForgeryOptions
querystring to a request, you will always get a AntiForgeryOptions {get; set;}
JSON response. You can disable this behavior by public FormatterMappings
calling ClearMediaTypeMappingForFormat on FormatterMappings { get; }
FormatterMappings object. public ICollection<IFilter> Filters {
get; private set; }
options.FormatterMappings. public
ClearMediaTypeMappingForFormat("json"); IList<OutputFormatterDescriptor>
OutputFormatters { get; }
It is also worth mentioning, that if you wish public IList<InputFormatterDescriptor>
MVC 6 to issue 406 (Not Acceptable) response InputFormatters { get; }
codes for situations when content negotiation is
public
unnsuccessful - the framework defaults to JSON IList<ExcludeValidationDescriptor>
responses if it can't determine the media type ValidationExcludeFilters { get; }
- you do it by simply inserting a new formatter,
HttpNotAcceptableOutputFormatter to the public int MaxModelValidationErrors
{get; set;}
www.dotnetcurry.com/magazine 17
public IList<ModelBinderDescriptor> scale changes, there are certainly some hidden
ModelBinders { get; } landmines and subtle differences, and those are
usually the most frustrating to deal with. However,
public if you pay attention to the points highlighted in this
IList<ModelValidatorProviderDescriptor>
ModelValidatorProviders { get; } article, it shouldn’t be too frustrating of a task.
Conclusion
Although some 3rd party profiling and debugging Figure 1: Empty ASP.NET MVC application
tools like RedGate’s Ants Performance Profiler for
.NET applications makes the job easy for you Visual In this MVC application, add a new SQL Server
Studio 2015 and recent Visual Studio 2013 updates Database of the name ApplicationDB.mdf in the
have also introduced new capabilities to maximize App_Data folder. In this database, add a table called
developer productivity and improve code quality. ‘EmployeeInfo’ with the following structure.
Before we get started with these features, let us set using System.Collections.Generic;
up a sample application. using System.Linq;
using MVC_ForDebugging.Models;
namespace MVC_ForDebugging.DataAccess
Set up a Sample MVC Application {
for Debugging public class EmployeeDAL
{
ApplicationDBEntities ctx;
Step 1: Open Visual Studio 2015 and create a public EmployeeDAL()
new empty ASP.NET MVC application as shown in {
Figure 1: ctx = new ApplicationDBEntities();
www.dotnetcurry.com/magazine 21
} return isValid;
}
public List<EmployeeInfo>
GetEmployees() { public void DeleteEmployee(int id,
return ctx.EmployeeInfoes. EmployeeInfo emp) {
ToList(); var e = ctx.EmployeeInfoes.Find(id);
} if (e != null)
{
public EmployeeInfo GetEmployee(int ctx.EmployeeInfoes.Remove(e);
id) { ctx.SaveChanges();
return ctx.EmployeeInfoes.Find(id); }
} }
}
public void }
AddNewEmployee(EmployeeInfo emp)
{ This class will be used for performing CRUD
ctx.EmployeeInfoes.Add(emp); operations using the Entity Framework model we
ctx.SaveChanges();
added in Step 2.
}
public void UpdateEmployee(int id, Step 4: In the Controllers folder, add a new MVC
EmployeeInfo emp) { controller with the name ‘EmployeeInfoController’.
var e = ctx.EmployeeInfoes. Add the following code in it:
Find(id);
if (e != null)
using System.Web.Mvc;
{
e.EmpName = emp.EmpName; using MVC_ForDebugging.Models;
e.Salary = emp.Salary; using MVC_ForDebugging.DataAccess;
e.DeptName = emp.DeptName;
e.Designation = emp.Designation; namespace MVC_ForDebugging.Controllers {
public class EmployeeInfoController :
ctx.SaveChanges(); Controller {
} EmployeeDAL obj;
} public EmployeeInfoController()
{
public bool CheckEmpNameExist(string obj = new EmployeeDAL();
ename) { }
bool isExist = false;
// GET: EmployeeInfo
foreach (var item in ctx. public ActionResult Index()
EmployeeInfoes.ToList()) {
{ var emps = obj.GetEmployees();
if (item.EmpName.Trim() == return View(emps);
ename.ToUpper().Trim()) }
{
isExist = true; // GET: EmployeeInfo/Details/5
break; public ActionResult Details(int id)
} {
} var emp = obj.GetEmployee(id);
return isExist; return View(emp);
} }
// GET: EmployeeInfo/Create
public bool public ActionResult Create()
CheckValidSalForDesignation(int sal) { {
bool isValid = true; var emp = new EmployeeInfo();
if (sal < 5000) return View(emp);
{ }
isValid = false;
} // POST: EmployeeInfo/Create
// POST: EmployeeInfo/Edit/5
[HttpPost] Figure 3: Changing Routing information
public ActionResult Edit(int id,
EmployeeInfo emp) This will display the Index View when the
{ application runs.
try
{
obj.UpdateEmployee(id, emp); Now that we have setup the application, let’s jump
return RedirectToAction("Index"); into the new Debugging features in Visual Studio
} 2015.
catch
{
return View();
}
} New Debugging Features
// GET: EmployeeInfo/Delete/5
in Visual Studio 2015 RC
public ActionResult Delete(int id){
var emp = obj.GetEmployee(id); Understanding Debugging with
return View(emp); Stepping
}
www.dotnetcurry.com/magazine 23
will be hit. We will make use of F10 (Step Over) Debugging a specific method from
and F11 (Step Into). We will use F10 to debug the
a statement with out of Multiple
GetEmployees() method call from Index() method
and check values returned from it.
Method Calls
In Visual Studio 2015, we can make use of Locals Consider a scenario in the debugging code, where
and Autos window to check return values from the we have a statement calling more than one method,
GetEmployees() method without jumping into it, as as shown in Figure 6:
shown in Figure 4:
using System.Web.Script.Serialization;
Figure 8: Step Into Specific option Add the following lines in the Index Action method
(highlighted)
Figure 8 shows a list of all methods called in the
currently debugged statement. From here, we can public ActionResult Index()
now select specific methods to be debugged. This {
will apply one-time breakpoint to the entry-point to var Emps = obj.GetEmployees();
that method, and the method will be debugged.
var jObj = new JavaScriptSerializer();
Select CheckEmpNameExist() method from the list var jsonData = jObj.Serialize(Emps);
and this method will get debugged as shown here:
return View(Emps);
}
This feature gives us the benefit of selection based Figure 10: Debug magnifier
debugging for a specific method. One important
thing to note here is that we can directly jump Click on the dropdown of the magnifier to display
to the specific statement for debugging using the data visualizer options window:
Run to Cursor option from the context menu
(available in Visual Studio 2013 as well). In the
CheckEmpNameExist() method, right-click the
if statement and select Run to Cursor, and the
if statement will be hit by the debugger. This Figure 11: Data Visualizer Options
eliminates the need to apply and remove breakpoint
on a specific statement for debugging. To go back to
Select the JSON Visualizer to display a window with
the immediate statement from which we started the
JSON data:
debugging, we can make use of the Step Out feature
from the Debug menu.
www.dotnetcurry.com/magazine 25
Figure 13 below displays a Search window to search data from In this code, the DebuggerDisplay accepts the string
the received data. parameter. Here Emp represents the constant string
and the {EmpNo} represents the EmpNo property
which will represent the value of the Employee
Record. Debug the Index action method and view
the value for Emps as shown in Figure 14.
[DebuggerDisplay("Emp {EmpNo}")]
public partial class EmployeeInfo
{
public int EmpNo { get; set; }
public string EmpName { get; set; }
public int Salary { get; set; }
public string DeptName { get; set; } Figure 15: Add Watch option
public string Designation { get;
set; }
} This will display the watch window as shown in
www.dotnetcurry.com/magazine 27
The Lambda Expression with its result can be seen
in Figure 21.
Conclusion:
USING DataCenter
2. Azure VM based ADFS OR on-
premise ADFS
ADFS
3. Self-Signed SSL Certificates
4. Visual Studio 2013 Community
Edition
Important ADFS
WITH
configurations
In this section, I will demonstrate what
ADFS should consist of, in order to
integrate well with your ASP.NET MVC
AZURE
application. I will be using the same
setup as demonstrated over here.
ASP.NET MVC
important details of each ADFS user
must be configured in Active Directory.
This section highlights settings which
APPLICATION
are necessary for a user to enable
him/her for use of claims-aware
application.
Login to the Active Directory server. In my case, it Now we will add another user in the same active
is the Azure VM. In your case it may be Azure VM directory. Right click on “Users” in the left hand
or on-premises AD server. Remember the steps are panel and select option as “New User”.
going to be same irrespective of Azure VM or on-
premises Server. For this article, we will use Azure
VM.
www.dotnetcurry.com/magazine 31
this URL in a browser like IE, then this is what you
will see –
https://YourCloudServiceName.cloudapp.net/
FederationMetadata/2007-06/FederationMetadata.
xml
www.dotnetcurry.com/magazine 33
ADFS can get this information about the application
when we configure the application as Relying Party.
Our application is going to rely on ADFS for security
token and authentication therefore it is called as
the Relying Party.
www.dotnetcurry.com/magazine 35
“Enter data about relying party manually” and click configure multi-factor authentication settings for
on Next to continue. Now we are going to use our this relying party trust at this time” and click Next
localhost URL as relying party therefore we are to continue. Select “Permit all users to access this
providing the name as localhost application. relying party” and click Next to continue.
Click Next to continue. In the Choose Profile In the “Ready to add trust” window, click Next to
window, select “ADFS Profile” option and click Next continue. In the “Finish” window, select the checkbox
to continue. The ADFS configured on Windows to open the claims rules and click on Close.
Server 2012 is ADFS 3.0 therefore we are not
selecting 1.0 and 1.1 profile option.
www.dotnetcurry.com/magazine 37
ShowClaims.cshtml and add the following code in bound to get frustrated. That’s where I thought
the view as shown here – it is worth to spend some time explaining a
simple technique to bypass ADFS authentication
mechanism during development work.
www.MelissaData.com 1-800-MELISSA
www.dotnetcurry.com/magazine 39
WORKING HARD, PARTYING HARDER
www.dotnetcurry.com/magazine 41
WPF
A
W
ItemsControl
Fundamentals
casual glance at WPF’s ItemsControl may
not elicit much excitement, but behind
its modest façade lies a wealth of power
and flexibility. Gaining a deep understanding of
the ItemsControl is crucial to your efficacy as a
WPF developer. Such an understanding will enable
you to recognize and rapidly solve a whole class
of UI problems that would otherwise have been
debilitating. This two part article will help you
obtain this understanding.
<ItemsControl Background="Red"/>
Populating Items
The simplest way to get some items into our Figure 4 Some textual items in an ItemsControl
ItemsControl is via the Items property. This
www.dotnetcurry.com/magazine 43
What happened here is that any text is Let’s start out by just assigning a List<string> to
automatically placed inside a TextBlock. Per the the DataContext of our Window:
rules of XML parsing, all three “items” are parsed as
one piece of text. We can confirm this via the public MainWindow()
WPF Visualizer – see Figure 5. {
InitializeComponent();
this.DataContext = new List<string>
{
"London",
"Amsterdam",
"Adelaide"
};
}
<ItemsControl ItemsSource="{Binding}"/>
Figure 5 Our text has been hosted inside a single TextBlock The result is shown in Figure 6. It is visually
identical to what we’d get if we manually added
OK, so now we know we can add any number of user three TextBlock controls to the Items property of
interface elements to an ItemsControl simply by our ItemsControl. The resulting visual tree is also
including them as children of the ItemsControl very similar, but not exactly the same. When using
element in our XAML. But what’s the point? How is ItemsSource, each of our TextBlock controls
this any better than simply including the items as is hosted inside a ContentPresenter whereas
children of a StackPanel instead? In fact, if you when using Items they are not. The reasons are
look at Figure 5 you’ll see that a StackPanel is not terribly important here, but it comes down to
hosting our items anyway (we’ll find out why later). ItemsControl container generation logic, which
is responsible for wrapping items in a container if
required.
The answer is: you normally wouldn’t. At least,
not with an ItemsControl. You might use this
approach with subclasses of ItemsControl,
for reasons we’ll discover later. Regardless, it’s
an instructive stepping-stone on our path to
a data-driven ItemsControl, which is where
ItemsSource comes in. Figure 6 Our ItemsControl is now obtaining its data from a
List<string>
The Items and ItemsSource properties are
mutually exclusive – it makes sense to set only ItemsControl also provides a HasItems property,
one of them and any attempt to use both will but I haven’t found it to be of any use. If you need
result in an exception. ItemsSource allows us to to trigger UI changes based on your available data,
give the ItemsControl a data source from which to you’re better off modelling those requirements in
materialize the items it displays. This could be an your view models. Not only does this give you more
XML document or a list of CLR objects. In practice I centralized logic and greater flexibility (for example,
have found XML document data sources to be of use what if you need to know when you have only one
only in standalone demos, so I am going to ignore item?), it also enables you to test such scenarios too.
them here. In a production system, you will almost
certainly want to create view models around your Now that we know how to get items into our
data – whether it’s XML-based or otherwise – and ItemsControl, can we stop ignoring the fact that
bind your ItemsControl to them instead. the items are visually boring? How can we adjust
their appearance?
// in our constructor
this.DataContext = new
List<CityViewModel>
{
new CityViewModel("London"),
new CityViewModel("Amsterdam"),
Figure 7 Using the ItemStringFormat property to modify the new CityViewModel("Adelaide")
text shown for each item };
The result is that each of our items is prefixed with If we revert our ItemsControl so that it does
“City: “, as you can see in Figure 7. Of course, all the not specify ItemStringFormat and run the
usual rules and behavior for .NET string formatting application, we see Figure 9. Clearly this is not what
apply here. In this case, our data items are of type we’re after. What’s happening here is WPF is calling
string, so we’re a little limited in our formatting ToString on each of our view models in order to
capabilities. Let’s change to using dates: obtain a default representation of them. After all, we
haven’t told WPF that we actually want to show the
this.DataContext = new List<DateTime> Name property on our view model.
{
DateTime.Now,
new DateTime(2013, 02, 13),
new DateTime(2004, 12, 31)
};
Now we can set our ItemStringFormat as follows: Figure 9 Default visualization of our view models
<ItemsControl
We can do exactly that by specifying the
ItemsSource="{Binding}"
DisplayMemberPath property:
ItemStringFormat="MMMM dd, yyyy"/>
<ItemsControl
The result is depicted in Figure 8. ItemsSource="{Binding}"
DisplayMemberPath="Name"/>
www.dotnetcurry.com/magazine 45
<ItemsControl new CityViewModel(
ItemsSource="{Binding}" "London",
DisplayMemberPath="Name" 8.308f,
ItemStringFormat="City: {0}"/> BitmapLoader
.Current
This gets us the same UI as shown in Figure 7. .LoadFromResource(
"pack://application:,,,/
ItemsControlArticle;component/
The view model we created above is pretty Images/gb.png",
pointless. All it does is wrap our city name so it’s not null,
adding any value. In reality, we’d likely have several null))
properties for each city:
Again, the details aren’t terribly important for the
public sealed class CityViewModel :
ReactiveObject purposes of this article.
{
private readonly string name; Now that we have view models with more
private readonly float population; interesting data in them, how can we take
private readonly advantage of this from our view? The
ObservableAsPropertyHelper<IBitmap>
countryFlag; ItemsControl class includes an ItemTemplate
property that allows us to specify a rich visual tree
public CityViewModel(string name, float to represent each item. Suppose we want to display
population, Task<IBitmap> countryFlag) the city name in bold with the population count
{ underneath it. Off to the right, we want to display
this.name = name; the country flag. We can achieve this as follows:
this.population = population;
this.countryFlag = countryFlag <ItemsControl ItemsSource="{Binding}">
.ToObservable() <ItemsControl.ItemTemplate>
.ToProperty(this, x => <DataTemplate>
x.CountryFlag); <Grid>
} <Grid.RowDefinitions>
public string Name => this.name; <RowDefinition Height="Auto"/>
public float Population => this. <RowDefinition Height="Auto"/>
population; </Grid.RowDefinitions>
public IBitmap CountryFlag => this. <Grid.ColumnDefinitions>
countryFlag.Value; <ColumnDefinition Width="*"/>
} <ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
I’ve added population (in millions) and a country <TextBlock
Text="{Binding Name}"
flag image. I’m using Splat for the image so that our FontWeight="Bold"
view model remains agnostic of the platform on FontSize="10pt"/>
which it is running. You’ll notice I’m also deriving <TextBlock
from ReactiveObject and using something called Grid.Row="1"
ObservableAsPropertyHelper. These are types Text="{Binding Population,
from ReactiveUI . ReactiveUI is outside the scope StringFormat=Population {0:0.#}
million}"
of this article, but you can see that our bitmap is FontSize="8pt"
loaded asynchronously. I’m using ReactiveUI as a Foreground="DarkGray"/>
simple means of surfacing the asynchronously- <Image Grid.Column="1"
loaded bitmap as a property. Until it has loaded, our Grid.RowSpan="2"
CountryFlag returns null. Once loaded, a property Source="{Binding CountryFlag,
changed notification is raised for CountryFlag, and Converter={StaticResource
ToNativeConverter}}"/>
it returns the loaded bitmap. </Grid>
</DataTemplate>
I then construct the view models in this manner: </ItemsControl.ItemTemplate>
</ItemsControl>
www.dotnetcurry.com/magazine 47
CityDataTemplate> Of course, the flexibility that we get from
<DataTemplate> ItemTemplateSelector does not end there. We
<Grid> could have it choose from any number of templates
<Grid.RowDefinitions> based on any programmable factor we desired. That
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/> said, the use of ItemTemplate is far more common
</Grid.RowDefinitions> than ItemTemplateSelector. Most of the time
<TextBlock you will know at design-time what the item should
Text="{Binding Name}" look like, and there’s rarely a need to vary that
FontWeight="Bold" appearance dynamically.
FontSize="8pt"/>
<TextBlock
Grid.Row="1" Conclusion
Text="{Binding Population,
StringFormat=Population {0:0.#}
million}" You should now have a firm grasp on
FontSize="8pt" ItemsControl fundamentals – how to declare one
Foreground="DarkGray"/> in XAML, how to populate it with data, and how to
</Grid> customize the appearance of items within it. For
</DataTemplate> some simple scenarios, this is all the knowledge you
</local:PlaceDataTemplateSelector.
need to create a solution. However, there is much
CityDataTemplate>
</local:PlaceDataTemplateSelector> and more to learn beyond what we’ve covered in
this first part of the article. In part 2 of this article,
We could also inline the definition within our we’ll dig much deeper and acquire the necessary
ItemsControl, but I usually find it cleaner to skills to utilize ItemsControl in advanced
separate any relatively complex elements out into scenarios
the resources section, or even other files altogether.
Regardless, we can now modify our ItemsControl
thusly:
About the Author
<ItemsControl
ItemsSource="{Binding}" Kent Boogaart is a Microsoft MVP in
ItemTemplateSelector="{StaticResource Windows Platform Development since
PlaceDataTemplateSelector}"/> 2009. He lives in Adelaide, Australia
with his wife and two kids. You can
The end result is shown in Figure 10. As you can find his blog at
see, we’re only showing the flag now if the item http://kent-boogaart.com and follow
him on Twitter @kent_boogaart.
represents a country. In addition, the font size for
the country name is larger than the font size for city
names.
kent boogaart
Open Source of these small devices with the Internet, ultimately, will lead
towards their inter-connectivity; where not only data exchange,
but decision making will be a shared responsibility of these smart
Technologies devices. That means the real value of Internet of Things (IoT) does
not lie in just home automation, but rather in the data collection
for Connected
by these smart devices and analytics, further up the value chain.
In this article, we will explore the possibility of developing
applications for IoT devices that capture data from low-cost
www.dotnetcurry.com/magazine 51
Smart Garbage Bin Setting up the Azure Environment
One of the ideas that really fascinates me is With the tech stack mentioned earlier, we are
the Smart Garbage Bin that some nations have aiming to have our IoT device code use Javascript/
adopted. Smart Garbage Bins tend to decrease the jQuery to send the sensor data to Azure Cloud
operational cost of monitoring the garbage bins by Services. From an Azure perspective, we have the
intelligent monitoring for waste and recyclables. option to choose one of the multiple ways available
There are different versions of Smart Bins available to receive this data, for e.g. service bus queues/
in market but our rationale (for this article) is - topics, event hubs, blobs, tables, etc. For this
"
application, we will use Azure Service Bus Queues.
We need to develop a smart bin that detects if the bin
is full and should report to a centralized cloud service. So as the next step, we need to create a queue on
Detection of level of garbage in the bin can be done Azure Management Portal (or using PowerShell
either by calibrating the weight of garbage or the scripts) with name Q.FromSensorRealtimeValue
height of garbage in the bin.
Setting up the IoT board Once the queue has been created, we can navigate
to the Configure tab and create shared access policy
with the following settings:
To begin with, we need the following electronic
components:
• Name: DeviceSharedKey
• Permissions: Send
• IoT board – let’s take Intel Galileo Gen 2 running
Yocto (Embedded Linux)
This will restrict the device to only publish
• Force sensitive resistor (FSR) 0.5” or 6”
messages to the queue.
(depending upon surface area of bin)
• Resistor – 22K Ω
• LED Matrix 8x16 HT16K33
• Jumper cables
• Breadboard
var closed = [
npm install os "0000000000000000", "0000000000000000",
npm install azure "0000000000000000", "0000000000000000",
npm install galileo-io "0000000000000000", "0000000000000000",
npm install johnny-five "0000000000000000", "0000000000000000",
];
Once the modules have been installed on our IoT
var THRESHOLD = 500;
device, we can paste the following code snippet in a fsr.scale([0, 1000]).on("data",
file (say, smartbin.js) function () {
if (this.value > THRESHOLD) {
var message = {
var serviceBusConnectionString = Hostname: os.hostname(),
"Endpoint=sb://iotcomm-ns.servicebus. SensorType: "FSR",
windows.net/; SharedAccessKeyName= MeasuredValue: this.value,
DeviceSharedKey;SharedAccessKey= RecordedAt: new Date()
};
matrix.draw(closed);
serviceBusService.
www.dotnetcurry.com/magazine 53
sendQueueMessage("Q. {
FromSensorRealtimeValue", JSON. "Hostname": "quark09877",
stringify(message), function (error) "SensorType": "FSR",
{ "MeasuredValue": 700,
if (!error) { "RecordedAt": "Wed Apr 29 2015 18:00:10
console.log("FSR sent to Azure GMT+0000"
Queue"); }
}
else { When we expand this solution to run on a network
console.log("Error sending to
Azure" + error); of IoT devices, we should ensure that the time-
} zones in the devices are either set to UTC and are
}); //sendQueueMessage synchronized, or the Azure Worker Role handles
} different time-zones.
else {
matrix.draw(open);
} Azure – Managed code to collect
}); //fsr.on("data") IoT data
}); //board.on('ready')
To deploy this code on our IoT device, we can use To collect the data sent by IoT device, we need a
FTP tools like FileZilla or use shared folders. Once Worker Role process that can pop the message
we have telnet / putty to the device, we can run our out of the Service Bus Queue and save it in SQL
IoT NodeJS code using database using Entity Framework. A typical Worker
Role requires implementation of 3 methods –
node smartbin.js OnStart, Run and OnStop. Our Worker Role
process will initiate the queue connection in the
The code will connect to Azure using the connection OnStart method, subscribe to the Queue in Run
string and will then initialize the Galileo board method and should close the queue connection in
using Johnny-Five libraries. OnStop method.
www.dotnetcurry.com/magazine 55
Using
REST APIs of TFS and
Visual Studio Online
I
Microsoft has been providing APIs n the early days of TFS, we were clients in technologies other than
for Team Foundation Services (TFS) expected to write only Microsoft Microsoft.NET; like Java, JavaScript and
from the earliest version of TFS (since .NET clients. We could give many others. For these technologies,
Visual Studio 2005). Using these APIs, reference to the components the components that are written in
we can create TFS clients and also that contained these APIs, and .NET are not useful.
write event handlers for the events use the referred classes in the code To assist such programming, Microsoft
raised by TFS. to access various TFS services. Over has recently published the APIs in
the years, to facilitate collaboration the form of RESTful services that
This article is co-authored by between different platforms, we encapsulate the services of TFS and
Subodh Sohoni and Manish Sharma are now also expected to create Visual Studio Online.
In the case of APIs we used in the early versions of
TFS, whenever we wanted to access a TFS service
programmatically from a client, we had to give
reference to assemblies that encapsulated calls to
webservices or WCF Services of TFS. It also meant
that these assemblies should be present on the
computer, the compatible .NET Framework should
be installed, and the assemblies should be stored
in the Global Assembly Cache. In a nutshell, Team
Explorer had to be installed on that computer.
These prerequisites were quite restrictive.
Since we are now dealing with RESTful services,
we do not have to worry about these conditions. As
long as we can create a HTTP request and send it Now you can create your first team project on VSO.
over the transport to TFS, and are able to read the You can provide a name to that Team Project and
response; we can write a TFS client. It can be using select process template between SCRUM, Agile and
any technology on any operating system, and on CMMI. For our example, we selected the SCRUM
any device. What sounds particularly interesting is a process template. That defines the work item types
case where a TFS client is able to run on a mobile that will be present in the team project. You can
device. also choose the version control mechanism – TFVC
or Git.
Accessing Visual Studio Online (VSO) using
such a client that uses RESTful services of TFS,
has one issue that we have to overcome. That
issue is related to security set up by VSO. While
accessing through the browser, the Team Web
Access application which is an ASP.NET application,
uses credentials of the logged-in user. These
credentials are usually the users Microsoft account
credentials like those derived from Hotmail or Live
account. RESTful services of TFS do not support
authentication using such credentials. It either
supports Basic authentication or OAuth. For each
account of VSO, we can enable Basic authentication.
www.dotnetcurry.com/magazine 57
Let us now locate the RESTFul services which we
can call to access VSO services. For each account
the APIs are available from the base URL https://
{account}.visualstudio.com/defaultcollection/_apis/.
From here we can access various services of VSO
like Projects, Work Item Tracking, Version Control,
Test Management, Team Room, Shared Services and
Build services. To get URL of each service API, you
can visit the page https://www.visualstudio.com/
en-us/integrate/api/overview. These services mainly
use GET and PATCH methods.
The instance of this class can now send a request and The code for this entire functionality will look like
it does that asynchronously. That means, we can call the following:
Get() method on the URL as GetAsync() which returns
a result of call as HttpResponseMessage object. static async void GetWorkItem(string
username, string password, int WiId)
HttpResponseMessage response = client. {
GetAsync(Url).Result; try
{
using (HttpClient client = new
To read the contents of that response message, we HttpClient())
need to use the await keyword. {
client.DefaultRequestHeaders.Accept.
string responseBody = await response. Add(new System.Net.Http.Headers.
Content.ReadAsStringAsync(); MediaTypeWithQualityHeaderValue
("application/json"));
www.dotnetcurry.com/magazine 59
client.DefaultRequestHeaders. URL of the method that creates a Task looks like
Authorization this:
= new AuthenticationHeaderValue https://{account}/DefaultCollection/{TeamProject}/_
("Basic",Convert.ToBase64String(
apis/wit/workitems/$Task?api-version=1.0
System.Text.ASCIIEncoding.ASCII.
GetBytes(
string.Format("{0}:{1}", username, In addition to that, this method accepts following
password)))); data in the JSON format:
string Url = "https://ssgsonline. [
visualstudio.com/defaultcollection/ {
_apis/wit/workitems?id=
"op": "add",
1&api-version=1.0";
"path": "/fields/System.Title",
using (HttpResponseMessage response = "value": "JavaScript implementation
client.GetAsync(Url).Result) for Microsoft Account"
{ }
response.EnsureSuccessStatusCode(); ]
string responseBody = await
response.Content. The value of variable “op” indicates that the field
ReadAsStringAsync(); is to be added, “path” is the name of the field to be
WorkItemDetails wiDetails =
JsonConvert.DeserializeObject given the value and “value” obviously is the value to
<WorkItemDetails>(responseBody); be given to that field. It has to be sent as collection
Console.WriteLine("Work Item ID: of fields. The code for creation of work item will
\t" + wiDetails.id); look like this:
foreach (KeyValuePair<string,
string> static async void CreateWorkItem(string
fld in wiDetails.fields) username, string password)
{ {
Console.WriteLine(fld.Key + ":\t" + try
fld.Value); {
} using (HttpClient client = new
} HttpClient())
} {
Catch (Exception ex) client.DefaultRequestHeaders.Accept.
{ Add(new System.Net.Http.Headers.
Console.WriteLine(ex.Message); MediaTypeWithQualityHeaderValue
} ("application/json-patch+json"));
}
client.DefaultRequestHeaders.
The output looks similar to the following: Authorization = new
AuthenticationHeaderValue
("Basic",Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.
GetBytes(
string.Format("{0}:{1}", username,
password))));
wiPostData.op = "add";
To create a new work item, we will use the PATCH wiPostData.path =
method for this service. PATCH method of this "/fields/System.Title";
wiPostData.value = "Employee edits
service accepts a parameter that indicates work other employees profile";
item of which work item type is to be created. The
www.dotnetcurry.com/magazine 61
client.DefaultRequestHeaders.Accept. The only two differences are as follows:
Add(new System.Net.Http.Headers.
MediaTypeWithQualityHeaderValue 1. Variable “op” has value “replace” as we are
("application/json-patch+json"));
replacing the title of work item
client.DefaultRequestHeaders.
Authorization = new 2. URL now changes so that team project name
AuthenticationHeaderValue("Basic", is removed and instead of work item type we are
Convert.ToBase64String( sending the ID of work item to be updated.
System.Text.ASCIIEncoding.ASCII.
GetBytes(string.Format("{0}:{1}", So far we have been using BASIC authentication
username, password)))); which is useful for applications like Console
Application, Windows Desktop (WinForms)
WorkItemPostData wiPostData = application, Windows Store Applications, other
new WorkItemPostData();
technology applications and can also be used
wiPostData.op = "replace"; for ASP.NET web applications. One issue in Basic
authentication is that password is sent over the
wiPostData.path = network in plain text. Although we are using a
"/fields/System.Title"; secure protocol like https, it still is less secure
wiPostData.value = "Employee edits compared to any other authentication mechanism
own profile in broser based app";
that does not require us to send any password over
List<WorkItemPostData> wiPostDataArr the internet. One such mechanism is OAuth.
= new List<WorkItemPostData> {
wiPostData }; Using OAuth
string wiPostDataString=JsonConvert.
SerializeObject(wiPostDataArr); OAuth is a service for authentication and
authorization (delegation based authorization)
HttpContent wiPostDataContent
which follows open standards. Open Standard is
= new StringContent(wiPostDataString,
Encoding.UTF8, something which is freely adopted, can be freely
"application/json-patch+json"); used and implemented, and can be extended.
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
www.dotnetcurry.com/magazine 63
4. Once we have got the details, we will use this
information in the application program to get
OAuth Token from the provider on behalf of end
user, and use the token to Log In and access the
VSO.
www.dotnetcurry.com/magazine 65
6. After Validating the details, Authorization Server Some points to remember:
(Provider) returns an access token i.e. OAuth Token to
Consumer Application (oauthToken from our earlier 1. The current version of OAuth is OAuth 2.0
code).
2. OAuth 2.0 Tokens can be shared only on secured
7. Consumer application uses this token to access channel i.e. HTTPS. It relies on SSAL to provide
resources on behalf of the user, Consumer App has encryption.
to send the token with every request to the Resource
Provider, which in our case is VSO 3. Facebook, Google, Twitter and Microsoft Servers
are some of the OAuth Providers.
[HttpPost]
public ActionResult
Create(EntityForCreateAndUpdate c) Conclusion
{
if (DateTime. Visual Studio Online and TFS 2015 (RC Onwards)
Parse(Session["TokenTimeout"].
provides RESTful APIs that allow you to extend
ToString()) <= DateTime.Now)
return RedirectToAction("RefreshToken", the functionality of VSO from your apps and
"Account", new { url = Request.Url. services. The possibilities of integration via client
LocalPath }); applications using any platform or device are
endless; right from iOS, Node.js, Android and our
if (ModelState.IsValid) very own Windows
{
ViewBag.Op = "Created";
var t = helper. Download the entire source code from GitHub at /
CreateWorkItemAsync(((AccessToken) bit.ly/dncm19-vsotfsrestapi
Session["AuthToken"]),
c.WorkItemTitle);
t.Wait();
return View("Details", t.Result);
}
else
return View(); About the Authors
}
Subodh Sohoni, Team System
8. Resource Provider validates the token and returns MVP, is an MCTS – Microsoft Team
Foundation Server – Configuration
the resources needed by the Consumer Application.
and Development and also is a
In this code, we created a new work item in our team Microsoft Certified Trainer(MCT)
project. since 2004. Subodh has his own
company and conducts a lot of
These steps will be easier to understand using the corporate trainings. He is an M.Tech.
in Aircraft Production from IIT
following visual:
Madras. He has over 20 years of
experience working in sectors like
subodh sohoni Production, Marketing, Software
development and now Software
Training. Follow him on twitter
@subodhsohoni
I T Y
L E I B I L
N G S
SI PON E
E S P
R N C I ening: L S e e d s )
P R I G a rd
re a
oft w
(S
In the last edition (May-June 2015 concepts that had been around languages as well.
edition) of the DNC Magazine, I for years and put them together.
covered some basics of Object However, he didn’t have them The Single Responsibility Principle
Oriented Programming (OOP). in SOLID order. We can credit (SRP) states that a class should do
As a quick review, I discussed Michael Feathers for coming one thing and one thing only. After
different types of inheritance, up with the SOLID acronym. So, years of working with OOP code,
polymorphism, encapsulation, what is SOLID? Well, it is five I’ve found that many developers
loose coupling, and tight cohesion. OOP principles, the first letter of violate this principle all the time.
Now I want to dive deeper into each spelling out SOLID: Single Yes, we write classes and methods,
good OOP techniques and begin a Responsibility, Open/Closed, Liskov but we tend to write one big
discussion on SOLID. Substitution, Interface Segregation, method that does something in
and Dependency Inversion. Over a procedural manner rather than
First introduced by Robert the next five issues, I’ll cover having smaller classes that do one
"Uncle Bob" Martin, SOLID is each one of these concepts. While thing. Here’s some typical code
not new. Uncle Bob simply took originally targeting OOP, many of that demonstrates this.
these concepts apply to non-OOP
public class CsvFileProcessor because it is difficult to unit test, but it increases
{ the odds of introducing bugs. If you change the
public void Process(string filename) code in the Parsing section, and you add a bug, then
{ Reading and Storing are also broken. And, because
TextReader tr = new
StreamReader(filename); unit tests will not exist or are very complex, it also
tr.ReadToEnd(); takes longer to track down and fix the bug.
tr.Close();
In order to fix this, we need to break down the code
var conn = new into the individual pieces. You may be thinking you
SqlConnection("server=(local);
integrated security=sspi; can just have three methods, one for each piece of
database=SRP"); functionality. But go back to the definition of SRP. It
conn.Open(); says that a class should have only one purpose. So,
we need three classes to do the work. Alright, we’ll
string[] lines = tr.ToString(). actually have more as you’ll see in a moment.
Split(new string[] {@"\r\l"},
StringSplitOptions.RemoveEmptyEntries);
foreach( string line in lines) The way to fix this code is through code refactoring.
{ Initially, we’ll put each piece of functionality into its
string[] columns = line.Split(new own method.
string[] {","}, StringSplitOptions.
RemoveEmptyEntries);
var command = conn.CreateCommand(); public class CsvFileProcessor
command.CommandText = "INSERT INTO {
People (FirstName, LastName, Email) public void Process(string filename)
VALUES (@FirstName, @LastName, {
@Email)"; var csvData = ReadCsv(filename);
command.Parameters.AddWithValue("@ var parsedData = ParseCsv(csvData);
FirstName", columns[0]); StoreCsvData(parsedData);
command.Parameters.AddWithValue("@ }
LastName", columns[1]);
command.Parameters.AddWithValue("@ public string ReadCsv(string filename)
Email", columns[2]); {
command.ExecuteNonQuery(); TextReader tr = new
} StreamReader(filename);
conn.Close(); tr.ReadToEnd();
} tr.Close();
} return tr.ToString();
}
How many things is this class doing? One? Two?
public string[] ParseCsv(string
Three? More? You may be tempted to say one. csvData)
That is, the class processes a CSV file. Look at this {
class another way. How would you unit test this? It return csvData.ToString().
wouldn’t be easy. What if you had other things like Split(new string[] { @"\r\l" },
data validation and error logging? How would you StringSplitOptions.
unit test it then? RemoveEmptyEntries);
}
The truth is, this class is doing three things: public void StoreCsvData(string[]
csvData)
1. Reading a CSV file {
var conn = new
2. Parsing the CSV file SqlConnection("server=(local);
3. Storing the data integrated security=sspi;
database=SRP");
Doing lots of things in a class is bad not just conn.Open();
foreach (string line in csvData)
www.dotnetcurry.com/magazine 69
{ public void
string[] columns = line.Split(new Process(IContactDataProvider cdp,
string[] { "," }, IContactParser cp, IContactWriter cw)
StringSplitOptions. {
RemoveEmptyEntries); var providedData = cdp.Read();
var command = conn. var parsedData =
CreateCommand(); cp.Parse(providedData);
command.CommandText = cw.Write(parsedData);
"INSERT INTO People (FirstName, }
LastName, Email) VALUES }
(@FirstName, @LastName, @Email)";
command.Parameters.AddWithValue("@ public class CSVContactDataProvider :
FirstName", columns[0]); IContactDataProvider
command.Parameters.AddWithValue("@ {
LastName", columns[1]); private readonly string _filename;
command.Parameters.AddWithValue("@
Email", columns[2]); public CSVContactDataProvider(string
command.ExecuteNonQuery(); filename)
} {
conn.Close(); _filename = filename;
} }
}
public string Read()
As you can see, things still aren’t quite right. We’re {
parsing the CSV file into rows in the ParseCsv() TextReader tr = new StreamReader(_
filename);
method, but additional parsing is happening in
tr.ReadToEnd();
the StoreCsvData() method to get each row into tr.Close();
columns. The way to fix that is with a ContactDTO return tr.ToString();
that stores the data from each row. }
}
The next step is to add the DTO, but I’ll skip a step
public class CSVContactParser :
and also break out each method into its own class. IContactParser
But I’m going to think ahead here too. What if {
the data doesn’t come in as CSV? What it its XML public IList<ContactDTO> Parse(string
or JSON or something else? You solve this with csvData)
interfaces. {
IList<ContactDTO> contacts = new
List<ContactDTO>();
public interface IContactDataProvider string[] lines = csvData.
{ Split(new string[] { @"\r\l" },
string Read(); StringSplitOptions.
} RemoveEmptyEntries);
foreach (string line in lines)
public interface IContactParser {
{ string[] columns = line.Split(new
IList<ContactDTO> Parse(string string[] { "," },
contactList); StringSplitOptions.
} RemoveEmptyEntries);
var contact = new ContactDTO
public interface IContactWriter {
{ FirstName = columns[0],
void Write(IList<ContactDTO> LastName = columns[1],
contactData); Email = columns[2]
} };
contacts.Add(contact);
public class ContactProcessor }
{
}
craig Blog: www.craigberntson.com/blog,
www.dotnetcurry.com/magazine 71
Build a
WINDOWS 10
UNIVERSAL APP
- First Look Unless you have been living under a rock
for the last couple of months, you probably
already know that Microsoft’s next version
of Windows will be called Windows 10 and
it will be available from July 29th 2015
onwards. I have been using the
Windows 10 preview version in my
Windows Phone and Surface and I am
really excited for the final launch. As a
passionate developer, I would encourage
every fellow developer to try out the
preview version and experience why it is
the right time be a Microsoft Developer.
www.dotnetcurry.com/magazine 73
and cleaner XAML code. immediately in the app. Hosted Web Apps can also
use Cortana to have unique user experience in their
Adaptive Visual States allow us to change the UI website.
based on the changes in size of the window without
writing any extra code. If your website does not have a Windows App, then
this may be a good starting point with very less
New controls like calendar, split view etc. have been code, time and investment.
introduced and existing controls have been updated
to work well in different screens.
Cortana
Device Preview toolbar in Visual Studio allows us to
preview the UI in different devices without running Cortana is now a part of Windows 10 and is more
the app. Here is a screenshot of the toolbar. open for developers. Our App (even Hosted Web
App) can now react to voice commands and even
override the default app behaviour (Imagine
developing a Weather App which will be the default
weather app for Cortana)
Reference Links
Here are some links for you to get started with
Windows 10
www.dotnetcurry.com/magazine 75
<Image Grid.Column="0" Source="Assets/
Repeat.png" x:Name="btnRepeat"
Tablet
Height="25" Stretch="Uniform" />
<Image Grid.Column="1" Source="Assets/
Previous.png" x:Name="btnPrevious"
Height="25" Stretch="Uniform" />
<Image Grid.Column="2" Source="Assets/
Play.png" x:Name="btnPlay"
Stretch="Uniform" Height="50" />
<Image Grid.Column="3"
Source="Assets/Next.png"
x:Name="btnNext" Stretch="Uniform"
Height="25"/>
<TextBlock Margin="20,0"
VerticalAlignment="Center" Grid.
Column="4" Foreground="#a2a7a9"
x:Name="txtStart" Text="00:13"
FontSize="30" />
<Slider Grid.Column="5"
Value="50" x:Name="sldProgress"
VerticalAlignment="Center" Width="450"
/>
<TextBlock Margin="20,0"
HorizontalAlignment="Right"
VerticalAlignment="Center" Grid.
Column="6" Foreground="#a2a7a9"
x:Name="txtEnd" Text="00:13"
FontSize="30" />
<Image Grid.Column="7" Source="Assets/
Shuffle.png" x:Name="btnShuffle"
Stretch="Uniform" Height="25"/>
</Grid>
</Grid>
Windows Phone
In this code, we have added the following
www.dotnetcurry.com/magazine 77
Service Oriented
Solutions using
MSMQ and WCF
www.dotnetcurry.com/magazine 79
is approved almost immediately, it will create a - C#
message object which will contain the order details
and finally send this off to DNC Acme Shippers. We install MSMQ (Message Queuing) via “Programs
and Features/Turn on or off Windows Features” and
DNC Goods website does not need to know the install with HTTP Support and Multicasting support.
technical implementation detail such as how We also install Distributed Transactions.
the communication channel works or even if it
is between the business hours that DNC Acme This is all that is needed for DNC Goods.
Shippers are operating on. All the website needs to
do is place the MSMQ message on the queue – that For DNC Acme Shippers, we need to create a queue,
is literally it. which is transactional. To do so, open the MMC
console, and go to File > Add/Remove Snap-ins and
MSMQ will then try to connect to the destination select “Computer Management” from the available
(which is provided in the MSMQ message object) snap-ins:
and send the message. If it cannot connect, it
will try again later. MSMQ takes care of this
communication for us, amongst other things that is
exposed in the MSMQ message object.
- Windows 7 Ultimate
- MSMQ (installed from control panel)
- Visual Studio 2012 (non express SKU) Figure 2. Message Queueing
- WCF
- .NET Framework 4.0 In the Private Queues, we will create a transaction
[DataMember(IsRequired = true)]
public string ShipToAddress { get;
set; }
[DataMember(IsRequired = true)]
public string ShipToCity { get; set;
}
[DataMember(IsRequired = true)]
public string ShipToCountry { get;
set; }
[DataMember(IsRequired = true)]
public string ShipToZipCode { get;
set; }
Figure 3. Creating a transactional MSMQ }
}
Now that we have MSMQ installed with a
transactional queue created, we need to write some In order to simulate the messages being sent
client code which will place an order to the queue. (and received), we first create a simple application
We first need to create a common project which has (Console/Winforms/WPF) which will create a
our contract agreement class “Order” which will be message and place it on the MSMQ named
created and placed on the queue. “ShippingOrders”. Be aware that this is not
production quality code but simply to illustrate how
Create a new project in Visual Studio (using .NET messages can be sent and received.
3.5 or higher) named “Acme.Shared.Contracts” and
create a class named Order. Add a reference to Create a new project named “Acme.Dispatcher”
“System.Runtime.Serialization” which is a .NET and add a reference to the “System.Messaging”
assembly and will expose the attributes we need .NET assembly, which gives us access to the
to apply to the class and properties, in order to MSMQ classes to interact with, and the “System.
serialize the object to and from the MSMQ using Transactions” assembly which gives us access to the
WCF as the communication protocol. TransactionScope class. Also add a project reference
to the “Acme.Shared.Contracts” project, as it contains
The following code will be written as a data the data contract we will be using to create and
contract: send the Order message. The order message will be
sent to the transactional private queue we created
using System; above “ShippingOrders”.
using System.Runtime.Serialization;
The code shown here is what is used to create a
namespace Acme.Shared.Contracts sample Order and place it on the queue:
{
[DataContract]
public class Order namespace DNCDispatcher
{ {
public Order() class Program
{ {
} static void Main(string[] args)
{ needed and in this setup, it is not needed. For more
// create a fake order, for information about FormatName, please visit the
simulation: MSDN resource here: https://msdn.microsoft.com/
var anOrder = new Order { OrderID = en-us/library/ms700996(v=vs.85).aspx
1, ShipToAddress = "123 Abc avenue",
ShipToCity = "DNC", ShipToCountry =
"A country", ShipToZipCode = "12345", We are specifying that we want to send the
SubmittedOn = DateTime.UtcNow }; message to the remote computer. The “xx.xx.xx.
xx” should be replaced with the IP Address you are
// create a MessageQueue to tell MSMQ intending on sending the message to.
where to send the message and how to
connect to it
var queue = new When you run the simulator, you will see that the
MessageQueue(ConfigurationManager. message was sent, and when you pull up MSMQ in
AppSettings["MessageQueuePath"]); Microsoft Management Console (MMC), you will see
that the number of messages will be set to “1”:
// Create a Message and set the body
to the order object above
var msg = new Message { Body =
anOrder };
Figure 4. Message waiting
// Create a transaction
using (var ts = new Now we know our order is waiting to be read, we
TransactionScope can now create a final project which will be the one
(TransactionScopeOption.Required)) to read the message from MSMQ. To do this, for this
{
exercise, let us create another Console/Winforms/
queue.Send(msg,
MessageQueueTransactionType. WPF project named “Acme.OrderReader” and add
Automatic); // send the message the “Acme.Shared.Contracts” project reference. Also
ts.Complete(); // complete the add the “System.Transactions”, “System.Messaging”,
transaction “System.Runtime.Serialization” and “System.
} ServiceModel” .NET assembly references for us to be
able to process the incoming messages from MSMQ
Console.WriteLine("Message Sent");
Console.ReadLine(); through WCF.
}
} In order for MSMQ to dispatch the message to
} the reader application through WCF (since WCF
is the one to read the messages from the queue),
The “MessageQueuePath” is a setting pulled from WCF needs to know the type of the object we are
the app.config file which contains the queue path expecting so that it can deserialize it and finally
for MSMQ to know where to send the message to. dispatch it to our application for processing. To do
The app.config setting looks like as follows: so, we use the ServiceKnownType attribute.
<appSettings>
<add key="MessageQueuePath" Let us create an interface called
value="FormatName:Direct=TCP:xx.xx.xx. “IOrderInboundMessageHandlerService” and
xx\private$\ShippingOrders"/> provide a single method that the implementer must
</appSettings> implement:
www.dotnetcurry.com/magazine 83
sender, EventArgs e) <security mode="None"/>
{ </binding>
Console.WriteLine("Faulted!"); // </msmqIntegrationBinding>
Change to something more sensible </bindings>
– this is just an example showing </system.serviceModel>
what happens when the host has
faulted. Notice that the endpoint address is set to look
}
} at the local computer MSMQ – this should once
} again, be changed to the machine where the queue
is located on the receiving end. For this exercise,
We are getting very close to completing our project. we are sending to a remote computer and the
The final step is to setup the application so that it OrderReader is running directly on the machine
will open the WCF service host and start reading where the messages are being sent to, thus the
the messages from the MSMQ. To do so, we use the reason to read the messages from the local MSMQ
ServiceHost class. But first, we must configure WCF endpoint.
settings in the config file (app.config). We simply need
to tell WCF the details about the service such as A B We are now finally ready to run the solution. First,
C (Address, Binding, Contract). The following is what fire up the OrderReader app and then secondly fire
we would enter in the config file: up the Dispatcher app. The dispatcher will send
<system.serviceModel> the message and the OrderReader will almost
<behaviors> immediately read the incoming message and
<endpointBehaviors> display the results in the console:
<behavior name=
"IncludeExceptionDetails">
<callbackDebug
includeExceptionDetailInFaults=
"true" />
</behavior>
</endpointBehaviors>
</behaviors> Figure 5. Order sent and received
<services>
<service name="Acme.OrderReader. As you can see, the message was sent and the order
OrderInboundMessageHandlerService"> was received.
<endpoint address="msmq.
formatname:DIRECT=OS:
.\private$\ShippingOrders" Whilst this solution works – in the real world,
binding="msmqIntegrationBinding" things differ slightly. You can have messages that
bindingConfiguration= are invalid and the application not expecting it,
"IncomingMessageHandlerBinding" therefore it would be known as a poison message
contract="Acme.OrderReader.Interfaces. and MSMQ will automatically place it in its own
IOrderInboundMessageHandlerService"> queue because the reader is unable to process the
</endpoint>
</service> message (i.e it cannot deserialize it and does not
</services> know its type) and terminate the transaction.
<bindings>
<msmqIntegrationBinding> You can allow the receiver (OrderReader) to handle
<binding these poison messages if you wish within the code.
name="IncomingMessageHandlerBinding"
closeTimeout="00:30:00" For more information, please visit the following
receiveTimeout="01:00:00" MSDN resource. https://msdn.microsoft.com/en-us/
retryCycleDelay="00:00:10" library/aa395218(v=vs.110).aspx
receiveRetryCount="0"
exactlyOnce="true"
maxRetryCycles="3"
receiveErrorHandling="Move">
www.dotnetcurry.com/magazine 85
TYPESCRIPT 1.4 AND 1.5 BETA
As JavaScript’s popularity continues to grow and a
lot of exciting new features are added to its next
versions, compile-to-JavaScript languages have
a lot of challenges to face. TypeScript, the typed
superset of JavaScript from Microsoft has taken
up these challenges and continues adding more
features to the language to make developers more
productive. At the time of this writing, though the
language supports comparatively lesser number of
features of the next version of JavaScript, the team
has promised that it will have full support for ES6
by the time TypeScript 2.0 is released. In addition,
popularity of the language got a big push after the
AngularJS team chose to use TypeScript as their
language of development over AtScript.
Union Types
Because of the optional type system in TypeScript,
it was not so easy to define a function that takes
different types of parameters across different
invocations. It was also a challenge to write type
Type Aliases
definitions for such functions, as we needed to
write a declaration for each possible invocation. While writing considerably larger apps using
TypeScript adds a new feature in 1.4 called Union TypeScript, it is natural to have the application
Types. This feature allows us to specify multiple divided into several modules and each module
types for the same argument without having to depending on other modules to achieve its
write multiple declarations for the same function. functionality. If a class or an interface defined in a
module has to be used a number of times in the
Let us say I have to write a function that accepts importing module, we will have to keep referring to
either a number, or an array of numbers and returns the types using module’s reference again and again.
square of the number, or array of squares depending Also some types imported from another module
on the input passed in. Following is the function in may have longer names, or you may want to refer
TypeScript: to these types with different names. Thankfully,
TypeScript 1.4 adds a feature called Type Aliases,
which allows us to create alias names for a type.
function square(nums: number |
number[]): number | number[]{
if(typeof nums === 'number'){ Say I have a module with some interfaces
return nums * nums; representing contracts to define different types of
} cars. To keep it simple, I included two types of cars
else{ here, cheap and costly. Following is the module:
var squares = [];
nums.forEach(num => {
squares.push(num*num); module Cars{
}); interface ICar{
return squares; manufacturer: string;
} price: number;
}
drive(speed: number);
See the type of argument mentioned in the }
function. It says, the input can be either a number or, export interface ICheapCar extends
an array of numbers. Similarly, the function returns ICar
two types of values, so the return type is also {
specified in a similar way. mileage: number;
}
This feature eases the job of writing type export interface ICostlyCar extends
declarations for existing libraries. For example, ICar
jQuery’s find() method can be called by passing a {
string selector, an element or a jQuery object to it. If length: number;
you see the type declaration for this method in the width: number;
Definitely Typed project (http://bit.ly/1RImmxS), it }
}
has three declarations. They are:
The only way we know to refer to these interfaces, is
find(selector: string): JQuery;
find(element: Element): JQuery; by using the module name.
find(obj: JQuery): JQuery;
var car1 : Cars.ICheapCar;
Using the Union types, it can be replaced with a var car2 : Cars.ICostlyCar;
single declaration, as shown here:
Using this syntax over and over to refer to
find(seo: string | Element | JQuery): these types would tire us. So, let’s create aliases.
JQuery; Following snippet creates the aliases:
www.dotnetcurry.com/magazine 87
type IEconomicCar = Cars.ICheapCar; workers[count].buildADoor();
type ILuxuriousCar = Cars.ICostlyCar; }
else{
Now you can use the alias names to refer to the workers[count].startFarming();
}
interfaces. }
var car1 : IEconomicCar;
var car2 : ILuxuriousCar; The loop that iterated over the items in the
collection checks for the type of the instance, before
it performs an operation.
It is also possible to create types on primitive types.
Here are some examples:
When marked with the keyword const, the compiler for(let c = 0; c< 10; c++){
doesn’t create an object for the enum. So it is not console.log(c*c);
allowed to access the const enum as an object in }
TypeScript. We can use the values alone and the
compiler replaces all usage occurrences with their The const keyword in ES6 is used to define scoped
corresponding values. constants. TypeScript now supports this keyword.
Any attempt to reassign value of a constant would
result in an error. The following function uses the
const enum Days {Sunday, Monday,
Tuesday, Wednesday, Thursday, Friday, const keyword:
Saturday};
var days = Days; //not allowed function findArea(radius: number):
console.log(Days.Monday); //0 number{
const pi=3.4159;
return pi * radius * radius;
ES6 Features }
console.log(findArea(20));
As I stated in the introduction of my first article on
ES6 (http://www.dotnetcurry.com/javascript/1090/
ecmascript6-es6-new-features), ES6 got a lot Template Strings
of features from some compile-to-JavaScript
languages and from popular libraries. ES6 got some Appending values to strings in JavaScript has never
of its features like classes, arrow functions, some been enjoyable. ES6 adds support for template
part of module system and a couple of others from strings to make it easier to add values of variables
TypeScript as well. So some of the ES6 features are to a string and to easily assign multi-line values
already available in TypeScript. The team started to strings. TypeScript 1.4 adds this feature to the
implementing features of ES6 into the language language. The following snippet uses this feature:
and TypeScript 1.5 is going to have a decent support
for ES6. var person={
firstName:'Ravi',
ES6 output mode lastName:'Kiran',
occupation:'Author'
};
By default, TypeScript code gets converted to ES5 console.log(`${person.firstName}
or, ES3 version of JavaScript. Now we can transpile ${person.lastName} is a/an ${person.
TypeScript code to ES6 code using a compilation occupation}.`);
option. Use the following command: var template=`<div>
<span>Some text goes here...</span>
• tsc --target ES6 file.ts </div>`;
www.dotnetcurry.com/magazine 89
ES6 that saves a lot of time in extracting values to export objects out of the module.
out of arrays and objects. It defines a shorter way
of assigning the values from arrays and objects
into variables. TypeScript 1.5 adds the support of class Employee{
id: number;
destructuring to the language and it gets transpiled name: string;
to its best possible alternative in the target version. dob:Date;
www.dotnetcurry.com/magazine 91
class MyClass {
emp: Employee;
constructor(e: Employee){
this.emp = e;
}
}
Conclusion
ravi kiran